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
de82c9e4ba5f5382181a50882263fc8f24cce356
1,258
// // SoundfieldUITests.swift // SoundfieldUITests // // Created by Zachary Stegall on 1/26/18. // Copyright © 2018 Zachary Stegall. All rights reserved. // import XCTest class SoundfieldUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34
182
0.666137
0e07133f80e7908cba6a83ad76f9e8b65023d8ea
1,983
// // ViewController.swift // ROCController // // Created by mbalex99 on 03/17/2017. // Copyright (c) 2017 mbalex99. All rights reserved. // import UIKit import ROCController import RealmSwift class MinimalChatController: ROCBaseController<MinimalChatMessage> { let conversation: MinimalConversation init(conversation: MinimalConversation){ self.conversation = conversation let chatMessages = conversation.chatMessages.sorted(byKeyPath: "timestamp", ascending: true) super.init(results: chatMessages) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = "Now Chatting" // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func sendButtonDidTap(text: String) { let sampleChatMessage = MinimalChatMessage() sampleChatMessage.userId = SampleAppConstants.myUserId sampleChatMessage.text = text let realm = try! Realm() try! realm.write { conversation.chatMessages.append(sampleChatMessage) } } override func attachmentButtonDidTapped() { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "Take a Picture", style: .default, handler: { [weak self] (_) in })) alertController.addAction(UIAlertAction(title: "Choose from Library", style: .default, handler: { [weak self] (_) in })) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alertController, animated: true, completion: nil) } }
31.983871
124
0.666162
239e612324cd915006fe891942febc0e753c167e
182
public func universalError(_ message: String, file: StaticString = #file, line: UInt = #line) -> Never { fatalError("[DiffableDataSources] \(message)", file: file, line: line) }
45.5
104
0.697802
095cd5e095268c392adc93b9915fab23fefb296b
1,762
import XCTest import JWTComponents class DefaultConstructedJWTComponentsTests: XCTestCase { func test_jwt_shouldReturn_nil() throws { XCTAssertNil(JWTComponents().jwt) } func test_jwtCompact_shouldThrowError_not_signed() throws { XCTAssertThrowsError(try JWTComponents().jwtCompact()) { error in XCTAssertTrue(String(describing: error).contains("not signed")) } } func test_header_shouldReturn_base64URLEmptyJSONObject() throws { XCTAssertEqual(try JWTComponents().header.base64URLDecoded(), "{}") } func test_payload_shouldReturn_nil() throws { XCTAssertNil(JWTComponents().payload) } func test_signature_shouldReturnNil() throws { XCTAssertNil(JWTComponents().signature) } func test_sign_shouldThrowError_no_payload() throws { var jwtc = JWTComponents() let key = "secret".data(using: .ascii)! let signer = try JWTFactory.createJWTSigner(algorithm: .HS256, keyData: key) XCTAssertThrowsError(try jwtc.sign(signer: signer)) { error in XCTAssertTrue(String(describing: error).contains("no payload")) XCTAssertTrue(String(reflecting: error).contains("no payload")) } } func test_verify_shouldThrowError_not_signed() throws { let jwtc = JWTComponents() let key = "secret".data(using: .ascii)! let verifier = try JWTFactory.createJWTVerifier(algorithm: .HS256, keyData: key) XCTAssertThrowsError(try jwtc.verify(with: verifier)) { error in XCTAssertTrue(String(describing: error).contains("not signed"), "Error: \(error)") XCTAssertTrue(String(reflecting: error).contains("not signed"), "Error: \(error)") } } }
35.959184
94
0.679909
71b386d575d4e9b16c9b7970ed4553643106042e
512
// // AgoraLrcScoreConfigModel.swift // AgoraKaraokeScore // // Created by zhaoyongqiang on 2021/12/17. // import UIKit @objcMembers public class AgoraLrcScoreConfigModel: NSObject { /// 评分组件配置 public var scoreConfig: AgoraScoreItemConfigModel? /// 歌词组件配置 public var lrcConfig: AgoraLrcConfigModel? /// 是否隐藏评分组件 public var isHiddenScoreView: Bool = false /// 背景图 public var backgroundImageView: UIImageView? /// 评分组件和歌词组件之间的间距 默认: 0 public var spacing: CGFloat = 0 }
22.26087
54
0.708984
7908c1e512955b95eb966871274f218829d2eb37
108
import Foundation enum UserInfoKeys: String { case kIdentifier case kIpAddress case kLatLong }
13.5
27
0.731481
ac2d503e880d7c2074337450ccabf52d3ae9e57f
396
// RUN: %target-swift-frontend %s -emit-ir // REQUIRES: objc_interop // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/fluidsonic (Marc Knaup) import Foundation class X { var x: [String]? func a(b: [NSObject: AnyObject]) { x = Y().c(b[""]) } } class Y { func c(any: Any?) -> [String]? { return [] } }
19.8
79
0.598485
2f496c1a9c4a02bb24d50dad716e590362ac9c8f
2,141
// // AppDelegate.swift // EmptySpriteKit // // Created by justin on 06/09/2016. // Copyright © 2016 justin. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.553191
285
0.75432
cc18ca12df354fc3c6f97bcb8c6537e07dedb7ef
3,950
import MongoSwiftSync import Nimble import TestsCommon struct AssertCollectionExists: TestOperation { let database: String let collection: String func execute<T: SpecTest>(on runner: inout T, sessions _: [String: ClientSession]) throws -> TestOperationResult? { let client = try MongoClient.makeTestClient() let collectionNames = try client.db(self.database).listCollectionNames() expect(collectionNames).to(contain(self.collection), description: runner.description) return nil } } struct AssertCollectionNotExists: TestOperation { let database: String let collection: String func execute<T: SpecTest>(on runner: inout T, sessions _: [String: ClientSession]) throws -> TestOperationResult? { let client = try MongoClient.makeTestClient() let collectionNames = try client.db(self.database).listCollectionNames() expect(collectionNames).toNot(contain(self.collection), description: runner.description) return nil } } struct AssertIndexExists: TestOperation { let database: String let collection: String let index: String func execute<T: SpecTest>(on _: inout T, sessions _: [String: ClientSession]) throws -> TestOperationResult? { let client = try MongoClient.makeTestClient() let indexNames = try client.db(self.database).collection(self.collection).listIndexNames() expect(indexNames).to(contain(self.index)) return nil } } struct AssertIndexNotExists: TestOperation { let database: String let collection: String let index: String func execute<T: SpecTest>(on _: inout T, sessions _: [String: ClientSession]) throws -> TestOperationResult? { let client = try MongoClient.makeTestClient() let indexNames = try client.db(self.database).collection(self.collection).listIndexNames() expect(indexNames).toNot(contain(self.index)) return nil } } struct AssertSessionPinned: TestOperation { let session: String func execute<T: SpecTest>(on _: inout T, sessions: [String: ClientSession]) throws -> TestOperationResult? { guard let session = sessions[self.session] else { throw TestError(message: "active session not provided to assertSessionPinned") } expect(session.isPinned).to(beTrue(), description: "expected \(self.session) to be pinned but it wasn't") return nil } } struct AssertSessionUnpinned: TestOperation { let session: String func execute<T: SpecTest>(on _: inout T, sessions: [String: ClientSession]) throws -> TestOperationResult? { guard let session = sessions[self.session] else { throw TestError(message: "active session not provided to assertSessionUnpinned") } expect(session.isPinned).to(beFalse(), description: "expected \(self.session) to be unpinned but it wasn't") return nil } } struct AssertSessionTransactionState: TestOperation { let session: String let state: ClientSession.TransactionState func execute<T: SpecTest>(on _: inout T, sessions: [String: ClientSession]) throws -> TestOperationResult? { guard let transactionState = sessions[self.session]?.transactionState else { throw TestError(message: "active session not provided to assertSessionTransactionState") } expect(transactionState).to(equal(self.state)) return nil } } struct TargetedFailPoint: TestOperation { let session: String let failPoint: FailPoint func execute<T: SpecTest>(on runner: inout T, sessions: [String: ClientSession]) throws -> TestOperationResult? { guard let session = sessions[self.session], let server = session.pinnedServerAddress else { throw TestError(message: "could not get session or session not pinned to mongos") } try runner.activateFailPoint(self.failPoint, on: server) return nil } }
37.980769
119
0.701519
0e5a6115889d2c0b4a83a800448fb2999c22de2a
8,326
//Copyright (c) 2018 [email protected] <[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. import UIKit @objc public protocol MSPeekImplementationDelegate: AnyObject { ///Will be called when the current active index has changed @objc optional func peekImplementation(_ peekImplementation: MSPeekCollectionViewDelegateImplementation, didChangeActiveIndexTo activeIndex: Int) ///Will be called when the user taps on a cell at a specific index path @objc optional func peekImplementation(_ peekImplementation: MSPeekCollectionViewDelegateImplementation, didSelectItemAt indexPath: IndexPath) } open class MSPeekCollectionViewDelegateImplementation: NSObject { public let cellPeekWidth: CGFloat public let cellSpacing: CGFloat public let scrollThreshold: CGFloat public let minimumItemsToScroll: Int public let maximumItemsToScroll: Int public let numberOfItemsToShow: Int public let scrollDirection: UICollectionView.ScrollDirection public weak var delegate: MSPeekImplementationDelegate? fileprivate var currentScrollOffset: CGPoint = CGPoint.zero fileprivate lazy var itemLength: (UIView) -> CGFloat = { view in var frameWidth: CGFloat = self.scrollDirection.length(for: view) //Get the total remaining width for the let allItemsWidth = (frameWidth //If we have 2 items, there will be 3 spacing and so on - (CGFloat(self.numberOfItemsToShow + 1) * (self.cellSpacing)) //There's always 2 peeking cells even if there are multiple cells showing - 2 * (self.cellPeekWidth)) //Divide the remaining space by the number of items to get each item's width let finalWidth = allItemsWidth / CGFloat(self.numberOfItemsToShow) return max(0, finalWidth) } public init(cellSpacing: CGFloat = 20, cellPeekWidth: CGFloat = 20, scrollThreshold: CGFloat = 50, minimumItemsToScroll: Int = 1, maximumItemsToScroll: Int = 1, numberOfItemsToShow: Int = 1, scrollDirection: UICollectionView.ScrollDirection = .horizontal) { self.cellSpacing = cellSpacing self.cellPeekWidth = cellPeekWidth self.scrollThreshold = scrollThreshold self.minimumItemsToScroll = minimumItemsToScroll self.maximumItemsToScroll = maximumItemsToScroll self.numberOfItemsToShow = numberOfItemsToShow self.scrollDirection = scrollDirection } open func scrollView(_ scrollView: UIScrollView, indexForItemAtContentOffset contentOffset: CGPoint) -> Int { let width = itemLength(scrollView) + cellSpacing guard width > 0 else { return 0 } let offset = self.scrollDirection.value(for: contentOffset) let index = Int(round(offset/width)) return index } open func scrollView(_ scrollView: UIScrollView, contentOffsetForItemAtIndex index: Int) -> CGFloat{ return CGFloat(index) * (itemLength(scrollView) + cellSpacing) } fileprivate func getNumberOfItemsToScroll(scrollDistance: CGFloat, scrollWidth: CGFloat) -> Int { var coefficent = 0 let safeScrollThreshold = max(scrollThreshold, 0.1) switch scrollDistance { case let x where abs(x/safeScrollThreshold) <= 1: coefficent = Int(scrollDistance/safeScrollThreshold) case let x where Int(abs(x/scrollWidth)) == 0: coefficent = max(-1, min(Int(scrollDistance/safeScrollThreshold), 1)) default: coefficent = Int(scrollDistance/scrollWidth) } if coefficent > 0 { coefficent = max(minimumItemsToScroll, coefficent) } else if coefficent < 0 { coefficent = min(-minimumItemsToScroll, coefficent) } let finalCoefficent = max((-1) * maximumItemsToScroll, min(coefficent, maximumItemsToScroll)) return finalCoefficent } } extension MSPeekCollectionViewDelegateImplementation: UICollectionViewDelegateFlowLayout { public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { //Unexpected behavior happens if the scrollview's length is 0 guard scrollDirection.length(for: scrollView) > 0 else { return } //Save the initial content offset that the collection view was going to scroll to let defaultTargetContentOffset = targetContentOffset.pointee //Get the scroll distance by subtracting the default target content offset from the current position that the user scrolled from let currentScrollDistance = scrollDirection.value(for: defaultTargetContentOffset) - scrollDirection.value(for: currentScrollOffset) //Get the number of items to scroll let numberOfItemsToScroll = getNumberOfItemsToScroll(scrollDistance: currentScrollDistance, scrollWidth: itemLength(scrollView)) //Get the destination index. numberOfItemsToScroll can be a negative number so the destination would be a previous cell let destinationItemIndex = self.scrollView(scrollView, indexForItemAtContentOffset: currentScrollOffset) + numberOfItemsToScroll //Get the contentOffset from the destination index let destinationItemOffset = self.scrollView(scrollView, contentOffsetForItemAtIndex: destinationItemIndex) let newTargetContentOffset = scrollDirection.point(for: destinationItemOffset, defaultPoint: defaultTargetContentOffset) //Set the target content offset. After doing this, the collection view will automatically animate to the target content offset targetContentOffset.pointee = newTargetContentOffset //Pass the active index to the delegate delegate?.peekImplementation?(self, didChangeActiveIndexTo: destinationItemIndex) } public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { currentScrollOffset = scrollView.contentOffset } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return scrollDirection.size(for: itemLength(collectionView), defaultSize: collectionView.frame.size) } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { let insets = cellSpacing + cellPeekWidth return scrollDirection.edgeInsets(for: insets) } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return cellSpacing } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.peekImplementation?(self, didSelectItemAt: indexPath) } }
51.395062
261
0.731444
c19ccc3866c577bbcd89e2fcfb62684ece581c30
1,867
import Foundation import MapboxDirections extension URLSession { /** :nodoc: The user agent string for any HTTP requests performed directly within MapboxCoreNavigation or MapboxNavigation. */ public static let userAgent: String = { let bundles: [Bundle?] = [ // Bundles in order from the application level on down .main, .mapboxNavigationIfInstalled, .mapboxCoreNavigation, .init(for: Directions.self), ] let bundleComponents = bundles.compactMap { (bundle) -> String? in guard let name = bundle?.object(forInfoDictionaryKey: "CFBundleName") as? String ?? bundle?.bundleIdentifier, let version = bundle?.object(forInfoDictionaryKey:"CFBundleShortVersionString") as? String else { return nil } return "\(name)/\(version)" } let system: String #if os(OSX) system = "macOS" #elseif os(iOS) system = "iOS" #elseif os(watchOS) system = "watchOS" #elseif os(tvOS) system = "tvOS" #elseif os(Linux) system = "Linux" #endif let systemVersion = ProcessInfo().operatingSystemVersion let systemComponent = "\(system)/\(systemVersion.majorVersion).\(systemVersion.minorVersion).\(systemVersion.patchVersion)" let chip: String #if arch(x86_64) chip = "x86_64" #elseif arch(arm) chip = "arm" #elseif arch(arm64) chip = "arm64" #elseif arch(i386) chip = "i386" #endif let chipComponent = "(\(chip))" let components: [String] = bundleComponents + [ systemComponent, chipComponent, ] return components.joined(separator: " ") }() }
31.116667
131
0.568827
2958eac5b04862d0fd9fe6d812e953831eb4a737
2,850
/*: ## Color Should Be for All! [ColorADD](glossary://ColorADD) code is a color identification system, an innovative universal language that enables to include without discrimination more than 350 million color blind people all over the world! Representing the 3 Primary Colors - Blue, Yellow and Red, by symbols, through the universal “Color Addition Theory”, symbols can be combined, and all colors graphically identified. Black and White symbols appear to indicate the Dark and Light tones of each color. ![Color Addition](ColorADD_Logo_sticker.png) The ColorADD project was presented in several national and worldwide events, also it won a lot of awards among which “Vodafone Mobile Awards” in the Accessibility Category. I'm really excited to collaborate with them. - Experiment: Symbols can help recognize color with any type of colorblindness types. You can apply each of them with different colors. Just play around with it and get a feeling of how it is to have a color vision handicap. */ //#-code-completion(everything, hide) //#-code-completion(bookauxiliarymodule, show) //#-hidden-code import Foundation //#-end-hidden-code let colorBlindType: ColorBlindType = /*#-editable-code*/.none/*#-end-editable-code*/ let pads = [ Pad(sound: /*#-editable-code*/.kick1/*#-end-editable-code*/, color: /*#-editable-code*/.green/*#-end-editable-code*/), Pad(sound: /*#-editable-code*/.chant1/*#-end-editable-code*/, color: /*#-editable-code*/.red/*#-end-editable-code*/), Pad(sound: /*#-editable-code*/.hihat1/*#-end-editable-code*/, color: /*#-editable-code*/.orange/*#-end-editable-code*/), Pad(sound: /*#-editable-code*/.perc1/*#-end-editable-code*/, color: /*#-editable-code*/.lightPurple/*#-end-editable-code*/), Pad(sound: /*#-editable-code*/.kick2/*#-end-editable-code*/, color: /*#-editable-code*/.green/*#-end-editable-code*/), Pad(sound: /*#-editable-code*/.chant2/*#-end-editable-code*/, color: /*#-editable-code*/.red/*#-end-editable-code*/), Pad(sound: /*#-editable-code*/.hihat2/*#-end-editable-code*/, color: /*#-editable-code*/.orange/*#-end-editable-code*/), Pad(sound: /*#-editable-code*/.perc2/*#-end-editable-code*/, color: /*#-editable-code*/.lightPurple/*#-end-editable-code*/) ] //#-hidden-code sendValue(.string(colorBlindType.rawValue)) do { let data = try JSONEncoder().encode(pads) sendValue(.data(data)) } catch let error { print("\(error) Unable to send the message") } //#-end-hidden-code /*: ## Acknowledgments * The sounds used to sample the instruments were downloaded from [Cymatics.fm](https://cymatics.fm/pages/free-download-vault), under a Creative Commons License. * The [ColorADD](http://www.coloradd.net/) code is provided for me with a pro-bono model for educational, distribution for free and in all associated communication supports. */
57
264
0.715088
094b97ee32a4e06aceefa0c71f312be2e7f8d93c
119
import UIKit import PlaygroundSupport public class ContainerLiveView: UIView, PlaygroundLiveViewSafeAreaContainer {}
19.833333
78
0.865546
5dd59644c5c1dfae532b53bb788aa9795ce68818
193
// // AppDelegate.swift // WSUBreak3D // // Created by wsucatslabs on 10/29/21. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? }
12.0625
55
0.694301
5b714dd243222f5b958b360d2177e7d55089aca4
6,397
// // SMTextField.swift // SwiftKit // // Created by OLEKSANDR SEMENIUK on 12/22/16. // Copyright © 2016 VRG Soft. All rights reserved. // import UIKit open class SMTextField: UITextField, SMKeyboardAvoiderProtocol, SMValidationProtocol, SMFormatterProtocol, SMFilterProtocol { open weak var smdelegate: UITextFieldDelegate? open var topT: CGFloat = 0.0 open var leftT: CGFloat = 0.0 open var bottomT: CGFloat = 0.0 open var rightT: CGFloat = 0.0 // MARK: - Override override open func textRect(forBounds bounds: CGRect) -> CGRect { let rect: CGRect = super.textRect(forBounds: bounds) let result: CGRect = rect.inset(by: UIEdgeInsets(top: topT, left: leftT, bottom: bottomT, right: rightT)) return result } override open func editingRect(forBounds bounds: CGRect) -> CGRect { let rect: CGRect = super.editingRect(forBounds: bounds) let result: CGRect = rect.inset(by: UIEdgeInsets(top: topT, left: leftT, bottom: bottomT, right: rightT)) return result } // override open func placeholderRect(forBounds bounds: CGRect) -> CGRect // { // let rect: CGRect = super.placeholderRect(forBounds: bounds) // // let result: CGRect = UIEdgeInsetsInsetRect(rect, UIEdgeInsetsMake(topT, left, bottomT, rightT)) // // return result // } // MARK: - SMFilterProtocol open var filteredText: String? {get {return self.text}} open var filter: SMFilter? open var delegateHolder: SMTextFieldDelegateHolder? override public init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } open func setup() { delegateHolder = SMTextFieldDelegateHolder(textField: self) super.delegate = delegateHolder } // MARK: - SMValidationProtocol open var validatableText: String? { get { return self.text } set { self.text = newValue } } open var validator: SMValidator? { didSet { validator?.validatableObject = self } } open func validate() -> Bool { return validator?.validate() ?? true } open var placeholderColor: UIColor? { didSet { if let placeholder: String = placeholder, let placeholderColor: UIColor = placeholderColor { let atrPlaceholder: NSAttributedString = NSAttributedString(string: placeholder, attributes: [NSAttributedString.Key.foregroundColor: placeholderColor as Any]) self.attributedPlaceholder = atrPlaceholder } } } override open var placeholder: String? { didSet { if let placeholderColor: UIColor = self.placeholderColor { self.placeholderColor = placeholderColor } } } // MARK: - SMFormatterProtocol public var formatter: SMFormatter? { didSet { formatter?.formattableObject = self } } public var formattingText: String? { get { return self.text } set { self.text = newValue } } // MARK: - SMKeyboardAvoiderProtocol public weak var keyboardAvoiding: SMKeyboardAvoidingProtocol? } // MARK: - SMTextFieldDelegateHolder open class SMTextFieldDelegateHolder: NSObject, UITextFieldDelegate { weak var holdedTextField: SMTextField? required public init(textField aTextField: SMTextField) { holdedTextField = aTextField } // MARK: - UITextFieldDelegate public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return holdedTextField?.smdelegate?.textFieldShouldBeginEditing?(textField) ?? true } public func textFieldDidBeginEditing(_ textField: UITextField) { holdedTextField?.keyboardAvoiding?.adjustOffset() holdedTextField?.smdelegate?.textFieldDidBeginEditing?(textField) } public func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return holdedTextField?.smdelegate?.textFieldShouldEndEditing?(textField) ?? true } public func textFieldDidEndEditing(_ textField: UITextField) { holdedTextField?.smdelegate?.textFieldDidEndEditing?(textField) } @available(iOS 10.0, *) public func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) { holdedTextField?.smdelegate?.textFieldDidEndEditing?(textField, reason: reason) } public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { var result: Bool = true if let inputField: SMTextField = textField as? SMTextField { result = inputField.filter?.inputField(inputField, shouldChangeTextIn: range, replacementText: string) ?? result } if result { result = holdedTextField?.formatter?.formatWithNewCharactersIn(range: range, replacementString: string) ?? result } if result { result = holdedTextField?.smdelegate?.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) ?? result } return result } public func textFieldShouldClear(_ textField: UITextField) -> Bool { let result: Bool = holdedTextField?.smdelegate?.textFieldShouldClear?(textField) ?? true return result } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { let result: Bool = holdedTextField?.smdelegate?.textFieldShouldReturn?(textField) ?? true if result { holdedTextField?.keyboardAvoiding?.responderShouldReturn(textField) } return result } }
27.337607
175
0.603877
33777a7bfd49118ee78aa0afef7122f44593f073
1,678
// // UserDataStore.swift // Core-CleanSwift-Example // // Created by Robert Nguyen on 9/13/18. // Copyright © 2018 Robert Nguyễn. All rights reserved. // import CoreBase import CoreRepository class UserDataStore: IdentifiableDataStore { let userDefaults: UserDefaults func make(total: Int, page: Int, size: Int, previous: UserEntity?, next: UserEntity?) -> Paginated? { AppPaginationDTO(total: total, page: page, pageSize: size, next: next?.id as Any, previous: previous?.id as Any) } init() { userDefaults = .standard } func getSync(_ id: String, options: DataStoreFetchOption?) throws -> UserEntity { if let data = userDefaults.data(forKey: id) { return try Constant.Request.jsonDecoder.decode(UserEntity.self, from: data) } throw DataStoreError.notFound } func lastID() throws -> String { throw DataStoreError.notFound } func saveSync(_ value: UserEntity) throws -> UserEntity { let data = try JSONEncoder().encode(value) userDefaults.set(data, forKey: value.id) return value } func saveSync(_ values: [UserEntity]) throws -> [UserEntity] { throw DataStoreError.unknown } func eraseSync() throws { } func getList(options: DataStoreFetchOption) throws -> ListDTO<UserEntity> { ListDTO(data: []) } func deleteSync(_ value: UserEntity) throws { userDefaults.set(nil, forKey: value.id) } func deleteSync(_ values: [UserEntity]) throws { values.forEach { userDefaults.setValue(nil, forKey: $0.id) } } }
27.508197
120
0.627533
8f1c721b039ed29bcc8294f5daa16ac9b3751616
2,142
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// @_implementationOnly import _RegexParser struct MEProgram<Input: Collection> where Input.Element: Equatable { typealias ConsumeFunction = (Input, Range<Input.Index>) -> Input.Index? typealias AssertionFunction = (Input, Input.Index, Range<Input.Index>) throws -> Bool typealias TransformFunction = (Input, Range<Input.Index>) throws -> Any? typealias MatcherFunction = (Input, Input.Index, Range<Input.Index>) throws -> (Input.Index, Any)? var instructions: InstructionList<Instruction> var staticElements: [Input.Element] var staticSequences: [[Input.Element]] var staticStrings: [String] var staticConsumeFunctions: [ConsumeFunction] var staticAssertionFunctions: [AssertionFunction] var staticTransformFunctions: [TransformFunction] var staticMatcherFunctions: [MatcherFunction] var registerInfo: RegisterInfo var enableTracing: Bool = false let captureList: CaptureList let referencedCaptureOffsets: [ReferenceID: Int] let namedCaptureOffsets: [String: Int] } extension MEProgram: CustomStringConvertible { var description: String { var result = """ Elements: \(staticElements) Strings: \(staticStrings) """ if !staticConsumeFunctions.isEmpty { result += "Consume functions: \(staticConsumeFunctions)" } // TODO: Extract into formatting code for idx in instructions.indices { let inst = instructions[idx] result += "[\(idx.rawValue)] \(inst)" if let sp = inst.stringRegister { result += " // \(staticStrings[sp.rawValue])" } if let ia = inst.instructionAddress { result += " // \(instructions[ia])" } result += "\n" } return result } }
31.043478
80
0.64986
89f92901bb13f0699ad11b3790fd0a91f9f6fb90
6,370
// Copyright (c) David Bagwell - https://github.com/dbagwell // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit extension TextField { public struct Styles { // MARK: - Properties public let `default`: Style public let focused: Style public let error: Style public let focusedError: Style // MARK: - Init public init( `default`: Style, focused: Style? = nil, error: Style? = nil, focusedError: Style? = nil ) { self.default = `default` self.focused = focused ?? `default` self.error = error ?? `default` self.focusedError = focusedError ?? error ?? `default` } } public struct Style { // MARK: - Properties public let textFamily: UIFont.Family public let textWeight: UIFont.Weight public let textSize: CGFloat public let textColor: UIColor public let textAlignment: NSTextAlignment public let borderWidth: CGFloat public let cornerRadius: CGFloat public let borderColor: UIColor public let backgroundColor: UIColor public let tintColor: UIColor public let keyboardType: UIKeyboardType public let textContentType: UITextContentType? public let autocapitalizationType: UITextAutocapitalizationType public let autocorrectionType: UITextAutocorrectionType public let returnKeyType: UIReturnKeyType public let width: CGFloat? public let height: CGFloat // MARK: Init public init( textFamily: UIFont.Family, textWeight: UIFont.Weight, textSize: CGFloat, textColor: UIColor, textAlignment: NSTextAlignment, borderWidth: CGFloat = 0, cornerRadius: CGFloat = 0, borderColor: UIColor = .clear, backgroundColor: UIColor = .clear, tintColor: UIColor = .systemBlue, keyboardType: UIKeyboardType = .default, textContentType: UITextContentType? = nil, autocapitalizationType: UITextAutocapitalizationType = .sentences, autocorrectionType: UITextAutocorrectionType = .default, returnKeyType: UIReturnKeyType = .default, width: CGFloat? = nil, height: CGFloat ) { self.textFamily = textFamily self.textWeight = textWeight self.textSize = textSize self.textColor = textColor self.textAlignment = textAlignment self.borderWidth = borderWidth self.cornerRadius = cornerRadius self.borderColor = borderColor self.backgroundColor = backgroundColor self.tintColor = tintColor self.keyboardType = keyboardType self.textContentType = textContentType self.autocapitalizationType = autocapitalizationType self.autocorrectionType = autocorrectionType self.returnKeyType = returnKeyType self.width = width self.height = height } // MARK: - Methods public func customized( textFamily: UIFont.Family? = nil, textWeight: UIFont.Weight? = nil, textSize: CGFloat? = nil, textColor: UIColor? = nil, textAlignment: NSTextAlignment? = nil, borderWidth: CGFloat? = nil, cornerRadius: CGFloat? = nil, borderColor: UIColor? = nil, backgroundColor: UIColor? = nil, tintColor: UIColor? = nil, keyboardType: UIKeyboardType? = nil, textContentType: UITextContentType? = nil, autocapitalizationType: UITextAutocapitalizationType? = nil, autocorrectionType: UITextAutocorrectionType? = nil, returnKeyType: UIReturnKeyType? = nil, width: CGFloat? = nil, height: CGFloat? = nil ) -> Style { return Style( textFamily: textFamily ?? self.textFamily, textWeight: textWeight ?? self.textWeight, textSize: textSize ?? self.textSize, textColor: textColor ?? self.textColor, textAlignment: textAlignment ?? self.textAlignment, borderWidth: borderWidth ?? self.borderWidth, cornerRadius: cornerRadius ?? self.cornerRadius, borderColor: borderColor ?? self.borderColor, backgroundColor: backgroundColor ?? self.backgroundColor, tintColor: tintColor ?? self.tintColor, keyboardType: keyboardType ?? self.keyboardType, textContentType: textContentType ?? self.textContentType, autocapitalizationType: autocapitalizationType ?? self.autocapitalizationType, autocorrectionType: autocorrectionType ?? self.autocorrectionType, returnKeyType: returnKeyType ?? self.returnKeyType, width: width ?? self.width, height: height ?? self.height ) } } }
39.8125
94
0.610047
39cb89f75cda66a759942e0e28a44ab2528b7f56
2,059
// // AppDelegate.swift // Seconds // // Created by George Dan on 15/06/2016. // Copyright © 2016 ninjaprawn. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the 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:. } }
43.808511
279
0.786304
c17ba73ae63042ed93af553d907d65c2e9fc7221
1,548
// // This source file is part of the Web3Swift.io open source project // Copyright 2019 The Web3Swift Authors // Licensed under Apache License v2.0 // // ABITupleEncoding.swift // // Created by Тимофей Солонин on 14.02.2019 // import Foundation /** Raw tuple encoding */ internal final class ABITupleEncoding: CollectionScalar<BytesScalar> { private let parameters: [ABIEncodedParameter] /** Ctor - parameters: - parameters: a collection of parameters to be encoded as a tuple */ internal init(parameters: [ABIEncodedParameter]) { self.parameters = parameters } /** - returns: A sum of heads and tails of the parameters */ internal override func value() throws -> [BytesScalar] { var additionalOffset: Int = headsCount() var heads: [BytesScalar] = [] var tails: [BytesScalar] = [] try parameters.forEach{ parameter in heads += try parameter.heads( offset: additionalOffset ) let parameterTails = try parameter.tails( offset: additionalOffset ) tails += parameterTails additionalOffset += parameterTails.count } return heads + tails } //TODO: headsCount should probably be injected /** - returns: A sum of headsCount of the parameters */ internal func headsCount() -> Int { return parameters.reduce(into: 0) { count, parameter in count += parameter.headsCount() } } }
26.237288
97
0.615633
8afdd3c6b1f51acc9f92f802348a0e2f35dc4bcc
2,436
// // File.swift // NERecordPlay // // Created by 郭园园 on 2021/8/11. // import Foundation public struct Response: Codable { var code: Int var msg: String var requestId: String var ts: Int var data: RecordData? } @objc public class RecordData:NSObject, Codable { var sceneType: String? var record: Record var eventList: Array<Event> var recordItemList: Array<RecordItem> public var snapshotDto: SnapshotDto } public struct Record: Codable { var classBeginTimestamp: Int var recordId: String var roomUuid: String var roomCid: String var startTime: Int var stopTime: Int } struct Event: Codable { var roomUid: String var timestamp: Int var type: Int } public struct RecordItem: Codable { public var role: String? public var userName: String? public var url: String public var duration: Int public var filename: String public var md5: String public var mix: Int var pieceIndex: Int var recordId: String public var roomUid: Int var size: Int public var subStream: Bool public var timestamp: Int public var type: FormatType public func isTeacher() -> Bool { return role == "host" } } public enum FormatType:String, Codable { case mp4,gz,aac } public struct SnapshotDto: Codable { var sequence: Int public var snapshot: Snapshot } public struct Snapshot: Codable { public var room: Room public var members: Array<Member> } // mark - Member public struct Member: Codable { public var userName: String public var userUuid: String public var role: String var rtcUid: Int var streams: Streams var properties: Properties var time: Int public var isTeacher: Bool { return role == "host" } } struct Streams: Codable { var video: Item? var audio: Item? } struct Properties: Codable { var screenShare: Item? } struct Item: Codable { var value: Int var time: Int? } // mark - Room public struct Room: Codable { public var roomName: String public var roomUuid: String public var rtcCid: String var properties: RoomProperties } struct RoomProperties: Codable { var chatRoom: ChatRoom? var whiteboard: Whiteboard? } struct ChatRoom: Codable { var chatRoomId: Int var roomCreatorId: String var time: Int } struct Whiteboard: Codable { var channelName: String }
20.644068
49
0.672414
87001fa4a838133dfcd027fb083134cca43a4386
1,036
// // NFXInfoController.swift // netfox // // Copyright © 2016 netfox. All rights reserved. // import Foundation class NFXInfoController: NFXGenericController { func generateInfoString(_ ipAddress: String) -> NSAttributedString { var tempString: String tempString = String() tempString += "[App name] \n\(NFXDebugInfo.getNFXAppName())\n\n" tempString += "[App version] \n\(NFXDebugInfo.getNFXAppVersionNumber()) (build \(NFXDebugInfo.getNFXAppBuildNumber()))\n\n" tempString += "[App bundle identifier] \n\(NFXDebugInfo.getNFXBundleIdentifier())\n\n" tempString += "[Device OS] \niOS \(NFXDebugInfo.getNFXOSVersion())\n\n" tempString += "[Device type] \n\(NFXDebugInfo.getNFXDeviceType())\n\n" tempString += "[Device screen resolution] \n\(NFXDebugInfo.getNFXDeviceScreenResolution())\n\n" tempString += "[Device IP address] \n\(ipAddress)\n\n" return formatNFXString(tempString) } }
28
131
0.639961
38144719e3e337d993dfc94db9b65b55c1a2dd66
1,846
// // Turntable.swift // Neves // // Created by aa on 2022/2/7. // import UIKit typealias TurntableCell = UIView & TurntableCellCompatible protocol TurntableCellCompatible: UIView { } protocol TurntableViewDataSource { func numberOfOneRound(in turntableView: TurntableView) -> Int func numberOfDisplays(in turntableView: TurntableView) -> Int func numberOfCells(in turntableView: TurntableView) -> Int func turntableView(_ turntableView: TurntableView, cellAtIndex index: Int) -> TurntableCell } protocol TurntableViewDelegate { func turntableView(_ turntableView: TurntableView, willDisplay cell: TurntableCell, atIndex index: Int) func turntableView(_ turntableView: TurntableView, didEndDisplaying cell: TurntableCell, atIndex index: Int) func turntableView(_ turntableView: TurntableView, sizeAtIndex index: Int) -> CGSize func turntableView(_ turntableView: TurntableView, didSelectCellAt index: Int) } enum Turntable { enum ScrollDirection { case vertical case horizontal } static let radian180 = CGFloat.pi static let radian360 = CGFloat.pi * 2 static let radian90 = CGFloat.pi / 2.0 static let radian30 = CGFloat.pi / 6.0 static let radian105 = radian30 * 3.5 // static let minContentH = RelationshipPlanet.planetH // 一屏显示半圈,也就是6个 // static let totalOffsetY = minContentH * 2 // 用于计算转动进度的偏移量(一圈12个,一屏6个,滚一屏高度就是50%进度,所以两屏高度就是刚好能滚一圈的最佳偏移量) // static let oneRoundItemCount: Int = 12 // 一圈12个,一屏显示半圈,也就是6个 // static let halfRoundItemCount: Int = oneRoundItemCount / 2 // 半圈6个 // static let singleItemRadian: CGFloat = radian360 / CGFloat(oneRoundItemCount) // 360 / 12 = 30 // static let singleItemOffsetY: CGFloat = minContentH / CGFloat(halfRoundItemCount) // 一屏显示6个 }
29.774194
112
0.716143
1cd398baebde5ce5f139105a44a5f635199ed574
3,591
// // CurveAlgorithm.swift // RALineChart // // Copyright (c) 2017-2021 RichAppz Limited (https://richappz.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import UIKit public struct CurvedSegment { public var controlPoint1: CGPoint public var controlPoint2: CGPoint } public class CurveAlgorithm { //========================================== // MARK: Singleton //========================================== public static let shared = CurveAlgorithm() //========================================== // MARK: Helpers //========================================== /** Create a curved bezier path that connects all points in the dataset */ public func createCurvedPath(_ dataPoints: [CGPoint]) -> UIBezierPath? { let path = UIBezierPath() path.move(to: dataPoints[0]) var curveSegments: [CurvedSegment] = [] curveSegments = controlPointsFrom(points: dataPoints) for i in 1..<dataPoints.count { path.addCurve(to: dataPoints[i], controlPoint1: curveSegments[i-1].controlPoint1, controlPoint2: curveSegments[i-1].controlPoint2) } return path } //========================================== // MARK: Private Helpers //========================================== private func controlPointsFrom(points: [CGPoint]) -> [CurvedSegment] { var result: [CurvedSegment] = [] let delta: CGFloat = 0.3 for i in 1..<points.count { let A = points[i-1] let B = points[i] let controlPoint1 = CGPoint(x: A.x + delta*(B.x-A.x), y: A.y + delta*(B.y - A.y)) let controlPoint2 = CGPoint(x: B.x - delta*(B.x-A.x), y: B.y - delta*(B.y - A.y)) let curvedSegment = CurvedSegment( controlPoint1: controlPoint1, controlPoint2: controlPoint2 ) result.append(curvedSegment) } for i in 1..<points.count-1 { let M = result[i-1].controlPoint2 let N = result[i].controlPoint1 let A = points[i] let MM = CGPoint(x: 2 * A.x - M.x, y: 2 * A.y - M.y) let NN = CGPoint(x: 2 * A.x - N.x, y: 2 * A.y - N.y) result[i].controlPoint1 = CGPoint(x: (MM.x + N.x)/2, y: (MM.y + N.y)/2) result[i-1].controlPoint2 = CGPoint(x: (NN.x + M.x)/2, y: (NN.y + M.y)/2) } return result } }
37.020619
142
0.567808
9b6241bad5c4f27aa760dba0d6029a55ba2ff78b
2,173
// // AppDelegate.swift // AppleTV Stream // // Created by Mark Filter on 2/19/18. // Copyright © 2018 Mark Filter. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the 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.234043
285
0.753797
2fb5c8444f9baf9c7b4f4deb5f03749546dea155
721
import UIKit import UIKit enum TWCMemberStatus { case Joined case Left } class StatusMessage: TCHMessage { var member: TCHMember! = nil var status: TWCMemberStatus! = nil var _timestamp: String = "" override var timestamp: String { get { return _timestamp } set(newTimestamp) { _timestamp = newTimestamp } } init(member: TCHMember, status: TWCMemberStatus) { super.init() self.member = member let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) as TimeZone! timestamp = dateFormatter.string(from: NSDate() as Date) self.status = status } }
21.205882
74
0.680999
9bfe6bdc752ed1bb6588f67f1dd345f350c79dd7
12,931
// Generated using Sourcery 0.17.1 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT // swiftlint:disable vertical_whitespace extension ArrayType { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "name = \(String(describing: self.name)), " string += "elementTypeName = \(String(describing: self.elementTypeName))" return string } } extension AssociatedValue { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "localName = \(String(describing: self.localName)), " string += "externalName = \(String(describing: self.externalName)), " string += "typeName = \(String(describing: self.typeName)), " string += "annotations = \(String(describing: self.annotations))" return string } } extension BytesRange { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "offset = \(String(describing: self.offset)), " string += "length = \(String(describing: self.length))" return string } } extension Class { /// :nodoc: override public var description: String { var string = super.description string += ", " string += "kind = \(String(describing: self.kind)), " string += "isFinal = \(String(describing: self.isFinal))" return string } } extension ClosureType { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "name = \(String(describing: self.name)), " string += "parameters = \(String(describing: self.parameters)), " string += "returnTypeName = \(String(describing: self.returnTypeName)), " string += "actualReturnTypeName = \(String(describing: self.actualReturnTypeName)), " string += "`throws` = \(String(describing: self.`throws`))" return string } } extension DictionaryType { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "name = \(String(describing: self.name)), " string += "valueTypeName = \(String(describing: self.valueTypeName)), " string += "keyTypeName = \(String(describing: self.keyTypeName))" return string } } extension Enum { /// :nodoc: override public var description: String { var string = super.description string += ", " string += "cases = \(String(describing: self.cases)), " string += "rawTypeName = \(String(describing: self.rawTypeName)), " string += "hasAssociatedValues = \(String(describing: self.hasAssociatedValues))" return string } } extension EnumCase { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "name = \(String(describing: self.name)), " string += "rawValue = \(String(describing: self.rawValue)), " string += "associatedValues = \(String(describing: self.associatedValues)), " string += "annotations = \(String(describing: self.annotations)), " string += "hasAssociatedValue = \(String(describing: self.hasAssociatedValue))" return string } } extension FileParserResult { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "path = \(String(describing: self.path)), " string += "module = \(String(describing: self.module)), " string += "types = \(String(describing: self.types)), " string += "typealiases = \(String(describing: self.typealiases)), " string += "inlineRanges = \(String(describing: self.inlineRanges)), " string += "inlineIndentations = \(String(describing: self.inlineIndentations)), " string += "modifiedDate = \(String(describing: self.modifiedDate)), " string += "sourceryVersion = \(String(describing: self.sourceryVersion))" return string } } extension GenericType { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "name = \(String(describing: self.name)), " string += "typeParameters = \(String(describing: self.typeParameters))" return string } } extension GenericTypeParameter { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "typeName = \(String(describing: self.typeName))" return string } } extension Method { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "name = \(String(describing: self.name)), " string += "selectorName = \(String(describing: self.selectorName)), " string += "parameters = \(String(describing: self.parameters)), " string += "returnTypeName = \(String(describing: self.returnTypeName)), " string += "`throws` = \(String(describing: self.`throws`)), " string += "`rethrows` = \(String(describing: self.`rethrows`)), " string += "accessLevel = \(String(describing: self.accessLevel)), " string += "isStatic = \(String(describing: self.isStatic)), " string += "isClass = \(String(describing: self.isClass)), " string += "isFailableInitializer = \(String(describing: self.isFailableInitializer)), " string += "annotations = \(String(describing: self.annotations)), " string += "definedInTypeName = \(String(describing: self.definedInTypeName)), " string += "attributes = \(String(describing: self.attributes))" return string } } extension MethodParameter { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "argumentLabel = \(String(describing: self.argumentLabel)), " string += "name = \(String(describing: self.name)), " string += "typeName = \(String(describing: self.typeName)), " string += "`inout` = \(String(describing: self.`inout`)), " string += "typeAttributes = \(String(describing: self.typeAttributes)), " string += "defaultValue = \(String(describing: self.defaultValue)), " string += "annotations = \(String(describing: self.annotations))" return string } } extension Protocol { /// :nodoc: override public var description: String { var string = super.description string += ", " string += "kind = \(String(describing: self.kind))" return string } } extension Struct { /// :nodoc: override public var description: String { var string = super.description string += ", " string += "kind = \(String(describing: self.kind))" return string } } extension Subscript { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "parameters = \(String(describing: self.parameters)), " string += "returnTypeName = \(String(describing: self.returnTypeName)), " string += "actualReturnTypeName = \(String(describing: self.actualReturnTypeName)), " string += "isFinal = \(String(describing: self.isFinal)), " string += "readAccess = \(String(describing: self.readAccess)), " string += "writeAccess = \(String(describing: self.writeAccess)), " string += "isMutable = \(String(describing: self.isMutable)), " string += "annotations = \(String(describing: self.annotations)), " string += "definedInTypeName = \(String(describing: self.definedInTypeName)), " string += "actualDefinedInTypeName = \(String(describing: self.actualDefinedInTypeName)), " string += "attributes = \(String(describing: self.attributes))" return string } } extension TemplateContext { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "types = \(String(describing: self.types)), " string += "argument = \(String(describing: self.argument)), " string += "stencilContext = \(String(describing: self.stencilContext))" return string } } extension TupleElement { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "name = \(String(describing: self.name)), " string += "typeName = \(String(describing: self.typeName))" return string } } extension TupleType { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "name = \(String(describing: self.name)), " string += "elements = \(String(describing: self.elements))" return string } } extension Type { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "module = \(String(describing: self.module)), " string += "typealiases = \(String(describing: self.typealiases)), " string += "isExtension = \(String(describing: self.isExtension)), " string += "kind = \(String(describing: self.kind)), " string += "accessLevel = \(String(describing: self.accessLevel)), " string += "name = \(String(describing: self.name)), " string += "isGeneric = \(String(describing: self.isGeneric)), " string += "localName = \(String(describing: self.localName)), " string += "variables = \(String(describing: self.variables)), " string += "methods = \(String(describing: self.methods)), " string += "subscripts = \(String(describing: self.subscripts)), " string += "initializers = \(String(describing: self.initializers)), " string += "annotations = \(String(describing: self.annotations)), " string += "staticVariables = \(String(describing: self.staticVariables)), " string += "staticMethods = \(String(describing: self.staticMethods)), " string += "classMethods = \(String(describing: self.classMethods)), " string += "instanceVariables = \(String(describing: self.instanceVariables)), " string += "instanceMethods = \(String(describing: self.instanceMethods)), " string += "computedVariables = \(String(describing: self.computedVariables)), " string += "storedVariables = \(String(describing: self.storedVariables)), " string += "inheritedTypes = \(String(describing: self.inheritedTypes)), " string += "containedTypes = \(String(describing: self.containedTypes)), " string += "parentName = \(String(describing: self.parentName)), " string += "parentTypes = \(String(describing: self.parentTypes)), " string += "attributes = \(String(describing: self.attributes))" return string } } extension Typealias { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "aliasName = \(String(describing: self.aliasName)), " string += "typeName = \(String(describing: self.typeName)), " string += "parentName = \(String(describing: self.parentName)), " string += "name = \(String(describing: self.name))" return string } } extension Types { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "types = \(String(describing: self.types))" return string } } extension Variable { /// :nodoc: override public var description: String { var string = "\(Swift.type(of: self)): " string += "name = \(String(describing: self.name)), " string += "typeName = \(String(describing: self.typeName)), " string += "isComputed = \(String(describing: self.isComputed)), " string += "isStatic = \(String(describing: self.isStatic)), " string += "readAccess = \(String(describing: self.readAccess)), " string += "writeAccess = \(String(describing: self.writeAccess)), " string += "isMutable = \(String(describing: self.isMutable)), " string += "defaultValue = \(String(describing: self.defaultValue)), " string += "annotations = \(String(describing: self.annotations)), " string += "attributes = \(String(describing: self.attributes)), " string += "isFinal = \(String(describing: self.isFinal)), " string += "isLazy = \(String(describing: self.isLazy)), " string += "definedInTypeName = \(String(describing: self.definedInTypeName)), " string += "actualDefinedInTypeName = \(String(describing: self.actualDefinedInTypeName))" return string } }
44.133106
99
0.611399
9c00ff409a94a4ee2702e64e1fb00b562be83770
2,420
// // SectionCell.swift // collectionViewStarter // // Created by 신용철 on 2020/01/21. // Copyright © 2020 신용철. All rights reserved. // import UIKit class SectionCell: UICollectionViewCell { private let imageView = UIImageView() private let titleLabel = UILabel() required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemeted") } override init(frame: CGRect) { super.init(frame: frame) setupViews() setupConstraints() } func setupViews(){ //imageView clipsToBounds = true //img 삐져나온것 절단 layer.cornerRadius = 20 imageView.contentMode = .scaleToFill contentView.addSubview(imageView) //label titleLabel.textAlignment = .center titleLabel.textColor = .black titleLabel.font = UIFont.preferredFont(forTextStyle: .headline) contentView.addSubview(titleLabel) } func setupConstraints(){ [imageView, titleLabel].forEach { $0.translatesAutoresizingMaskIntoConstraints = false } //isActive 매번하기 귀찮으면 NSLayoutConstraint.activate([ imageView.topAnchor.constraint(equalTo: contentView.topAnchor), imageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), imageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), titleLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor), titleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), titleLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), titleLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor), titleLabel.heightAnchor.constraint(lessThanOrEqualToConstant: 50) ]) titleLabel.setContentCompressionResistancePriority(.required, for: .vertical) //최소한 자신의 텍스트의 크기 만큼은 유지 되도록 하는 명령어 } // MARK: Configure Cell //위에서 imageView, titleLabel을 private으로 설정해놓았기 때문에 접근이 안됨. //따라서 위의 객체들에 접근을 하기 위해서는 아래 함수를 통하는 방법밖에 없음. //아래와 같이 쓰는 이유: 위에 프로퍼티가 엄청 많은 경우에 건드리지 말아야할 것을 건드릴 수도 있기 때문에 원천 봉쇄. 또한 private으로 안해놓으면 폰트값 등 설정값을 다 건드릴 수 있기 때문에 바꾸지 못하게 하기 위해서 아래와 같이 구현해놓는 것이 안전함. func configure(img: UIImage?, title: String) { imageView.image = img titleLabel.text = title } }
34.084507
153
0.657025
50cddb1ef62bd07f81f428014150d6fca168478b
332
// swift-tools-version:5.2 import PackageDescription let package = Package( name: "CIDependencies", platforms: [ .macOS(.v10_10), ], dependencies: [ .package(url: "https://github.com/JosephDuffy/xcutils.git", .branch("master")), ], targets: [ .target(name: "CIDependencies") ] )
20.75
87
0.596386
e95f1819c723c454226ae715af7453d1d1f7df90
1,404
// // ViewController.swift import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let addView = UIView(frame:CGRect(x:100, y:350, width:200, height:50)) addView.backgroundColor = UIColor.purple let tap = UITapGestureRecognizer(target: self, action:#selector(tapClick(sender:))) addView.addGestureRecognizer(tap) addView.isUserInteractionEnabled = true self.view.addSubview(addView) } @objc func tapClick(sender: UIGestureRecognizer) { // / 打开首页main FlutterBoostPlugin.open("first", urlParams:[kPageCallBackId:"MycallbackId#1"], exts: ["animated":true], onPageFinished: { (_ result:Any?) in print(String(format:"call me when page finished, and your result is:%@", result as! CVarArg)) }) { (f:Bool) in print(String(format:"page is opened")) } } @IBAction func onClickPresentFlutterPage(_ sender: UIButton, forEvent event: UIEvent) { FlutterBoostPlugin.present("second", urlParams:[kPageCallBackId:"MycallbackId#2"], exts: ["animated":true], onPageFinished: { (_ result:Any?) in print(String(format:"call me when page finished, and your result is:%@", result as! CVarArg)); }) { (f:Bool) in print(String(format:"page is presented")); } } }
36.947368
152
0.638177
4b0e9b5f7a00abd5aee95e204e6a96e449b2c468
596
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ public struct IssuanceMetadata: Codable, Equatable { public let contract: String? public let issuerDid: String? enum CodingKeys: String, CodingKey { case contract = "manifest" case issuerDid = "did" } }
35.058824
95
0.468121
d522776def3d33f7f6631bfe178ec4344e259ccf
2,123
import Foundation import simd // 结构体 表示hit事件 struct Hit_record { var t: Float // ? var p: float3 // point var normal: float3 // 法线 // 指向material颜色的指针 var material_pointer: Material init(t: Float, p: float3, normal: float3, material_pointer: Material) { self.t = t self.p = p self.normal = normal self.material_pointer = material_pointer } } // 协议 protocol Hitable { func hit(ray: Ray, tmin: Float, tmax: Float) -> Hit_record? } class Sphere: Hitable { var center: float3 = float3(x: 0, y: 0, z: 0) var radius: Float = 0.0 var material: Material init(center: float3, radius: Float, material: Material) { self.center = center self.radius = radius self.material = material } // tmin - tmax 之间的撞击 射线是否撞击到球体 func hit(ray: Ray, tmin: Float, tmax: Float) -> Hit_record? { // ??? let oc = ray.origin - center let a = dot(ray.direction, ray.direction) // 点积 let b = dot(oc, ray.direction) let c = dot(oc, oc) - radius * radius let discriminant = b * b - a * c if discriminant > 0 { var t = (-b - Float(sqrt(Double(discriminant)))) / a if t < tmin { t = (-b + Float(sqrt(Double(discriminant)))) / a } if tmin < t && t < tmax { let point = ray.point_at_parameter(t: t) let normal = (point - center) / float3(radius) return Hit_record(t: t, p: point, normal: normal, material_pointer: material) } } return nil } } // 多个目标,多个球 class Hitable_list: Hitable { var list = [Hitable]() func add(h: Hitable) { list.append(h) } func hit(ray: Ray, tmin: Float, tmax: Float) -> Hit_record? { var hit_anything: Hit_record? for item in list { if let ahit = item.hit(ray: ray, tmin: tmin, tmax: tmax) { hit_anything = ahit } } return hit_anything } }
25.578313
93
0.5252
28f94048b1f674e5ac58de9cd0ceb94c4bb6577c
2,357
// // SceneDelegate.swift // Luces Estadio // // Created by Diego Atencia on 27/03/2020. // Copyright © 2020 Diego Atencia. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.648148
147
0.714043
bfcfd52469dcc4ee5882cf8032707d5e409bd901
1,131
// // Record.swift // Scale // // Created by mani on 2020-06-08. // Copyright © 2020 mani. All rights reserved. // import Foundation extension Record { func createdAtString() -> String { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .full return dateFormatter.string(from: createdAt) } func createdAtString(dateFormat: String) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormat return dateFormatter.string(from: createdAt) } func relativeCreatedAtString() -> String? { let relativeFormatter = RelativeDateTimeFormatter() relativeFormatter.dateTimeStyle = .named return relativeFormatter.string(for: createdAt) } func isDateToday() -> Bool { return Calendar.current.isDateInToday(createdAt) } func formatWeight(for unit: UnitOfWeight) -> String { switch unit { case .pounds: return String(format: "%.1flbs", weight) case .kilograms: return String(format: "%.2fkg", weight) } } }
26.302326
59
0.627763
bfe84c1fa61ff1f5bd393105722b31fe162746bf
893
//: [Previous](@previous) //Properties Of Asymptotic Notation //General Properties /* if f(n) is O(g(n)) then a * f(n) is O(g(n)) eg: f(n) = 2n^2 + 5 is O(n^2) then 7*f(n) = 7(2n^2+5) = 14n^2 + 35 O(n^2) This is true for Ω big Omega --- lower bound and θ theta also if f(n) is Ω (g(n)) then a*f(n) is Ω(g(n)) if f(n) is θ (g(n)) then a* f(n) is θ(g(n)) */ //Reflexive Properties /* if f(n) is given then f(n) is O(f(n)) ie f(n)= n^2 then O(n^2) */ //Transitive Properties (friend of friend is friend) /* if f(n) is O(g(n)) and g(n) is O(h(n)) then f(n) = O(h(n)) eg: f(n) = n g(n)= n^2 h(n)= n^3 n is O(n^2) and n^2 is O(n^3) then n is O(n^3) */ //Symmetric Properties /* if f(n) is θ(g(n)) then g(n) is θ(f(n)) eg: f(n)= n^2 and g(n) = n^2 f(n) = θ(n^2) g(n) = θ(n^2) */
13.953125
80
0.481523
622623daa7ed91db38c30f34f8d7ea4a774c180b
3,072
// // ImageClassifierView.swift // HelloCoreML // // Created by Robin on 2019/11/16. // Copyright © 2019 RobinChao. All rights reserved. // import SwiftUI struct ImageClassifierView: View { @EnvironmentObject var classificationModel: ImageClassificationModel @State private var isPresented = false @State private var takePhoto = false fileprivate func classification() { self.classificationModel.startPredictClassification() } var body: some View { VStack { self.classificationModel.image == nil ? PlaceholdView().toAnyView() : ZStack { Image(uiImage: self.classificationModel.image!) .resizable() .aspectRatio(contentMode: .fill) .onTapGesture { self.classification() } Text(self.classificationModel.classificationResult.localizedCapitalized) .foregroundColor(.white) .font(.system(size: 22)) .shadow(color: .black, radius: 1, x: 2, y: 2) .padding() .background(Rectangle() .foregroundColor(Color.init(.systemBackground)) .opacity(0.33) .cornerRadius(10)) }.toAnyView() HStack { Button(action: { self.takePhoto = false self.classificationModel.classificationResult = "Tap to Classify" self.isPresented.toggle() }, label: { Image(systemName: "photo") }).font(.title) Spacer() .frame(width: 250, height: 44, alignment: .trailing) Button(action: { self.takePhoto = true self.classificationModel.classificationResult = "Tap to Classify" self.isPresented.toggle() }, label: { Image(systemName: "camera") }).font(.title) }.padding() .frame(maxWidth: .infinity) .background(Color.gray.opacity(0.2)).toAnyView() } .sheet(isPresented: self.$isPresented) { ShowImagePicker(image: self.$classificationModel.image, takePhoto: self.$takePhoto) } .navigationBarTitle(Text("Image Classifier"), displayMode: .inline) .onDisappear { self.classificationModel.image = nil } } } struct PlaceholdView: View { var body: some View { ZStack { Image(systemName: "photo.fill") .resizable() .aspectRatio(contentMode: .fit) .foregroundColor(Color.init(.systemRed)) .shadow(color: .secondary, radius: 5) }.padding() } } extension View { func toAnyView() -> AnyView { AnyView(self) } }
33.391304
95
0.508464
5055288fd7b1c1922c0aa7b860882ff116058c5d
1,688
// // SwitchCellController.swift // nemo // // Created by Andyy Hope on 5/8/18. // Copyright © 2018 Andyy Hope. All rights reserved. // import UIKit final class SwitchFieldCellController { // MARK: - Properties let entity: SwitchFieldCellEntity let dataSource: SwitchFieldCellDataSource weak var delegate: FormCellControllerDelegate? // MARK: - Initializer init(entity: SwitchFieldCellEntity) { self.dataSource = SwitchFieldCellDataSource(entity: entity) self.entity = entity } // MARK: - Computed Properties var model: SwitchFieldCellModel { return dataSource.model } // MARK: - Preparation func prepare(_ cell: SwitchFieldCell) { cell.label.text = model.labelText cell.switch.isOn = model.isOn cell.switch.addTarget(self, action: #selector(formElementDidUpdate(sender:)), for: .valueChanged) cell.switch.isEnabled = model.isEnabled delegate?.formDidUpdate( for: .field(property: dataSource.property, value: model.isOn)) } } extension SwitchFieldCellController: FormFieldHandling { @objc func formElementDidUpdate(sender: Any) { guard let sender = sender as? UISwitch else { return } dataSource.setFormValue(sender.isOn) delegate?.formDidUpdate( for: .field(property: dataSource.property, value: sender.isOn)) } func clearFormField() { dataSource.setFormValue(nil) } func setInteractionEnabled(_ isInteractionEnabled: Bool) { model.state = isInteractionEnabled ? .enabled : .disabled } }
25.575758
105
0.645142
266582760cae2f0c46e398aec5ae3c2cf5e5df8c
3,528
// // ScaleController.swift // LayoutCollection // // Created by mac on 2019/6/25. // Copyright © 2019年 mac. All rights reserved. // import UIKit fileprivate let topInset: CGFloat = (screenHeight >= 812.0 && UIDevice.current.model == "iPhone" ? 44 : 20) class TableScaleController: BaseViewController { let cellReuseIdentifier = "cellId" let imageHeight: CGFloat = 130 private var refresh: UIRefreshControl = { let refreshView = UIRefreshControl() refreshView.tintColor = UIColor.clear return refreshView }() private lazy var tableView: UITableView = { let tableView = UITableView(frame: .zero, style: .plain) tableView.delegate = self tableView.dataSource = self tableView.showsVerticalScrollIndicator = false tableView.showsHorizontalScrollIndicator = false tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier) //tableView.refreshControl = refresh return tableView }() private let tableHeader: UIView = { let view = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 130 + topInset)) return view }() private var config: CyclePageConfig = { let config = CyclePageConfig() config.animationType = .curlUp return config }() private lazy var cycleView: CyclePageView = { let view = CyclePageView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: imageHeight + topInset), config: config) return view }() var imageNames = ["https://github.com/shiliujiejie/adResource/raw/master/image11.png", "https://github.com/shiliujiejie/adResource/raw/master/image14.jpg","https://github.com/shiliujiejie/adResource/raw/master/image12.jpg","https://github.com/shiliujiejie/adResource/raw/master/banner4.png","https://github.com/shiliujiejie/adResource/raw/master/banner5.png"] override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white self.title = "首页" navigationController?.setNavigationBarHidden(true, animated: true) tableHeader.addSubview(cycleView) tableView.tableHeaderView = tableHeader view.addSubview(tableView) layoutTableView() tableView.contentInset = UIEdgeInsets(top: -topInset, left: 0, bottom: 0, right: 0) cycleView.setImages(imageNames) // [weak self] cycleView.pageClickAction = { (index) in print("click at Index == \(index)") } } override func didReceiveMemoryWarning() { print("didReceiveMemoryWarning") } } extension TableScaleController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) cell.textLabel?.text = "\(indexPath.row ) + bingo" cell.contentView.backgroundColor = UIColor.purple return cell } } extension TableScaleController { func layoutTableView() { tableView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } } }
36.371134
363
0.645408
093fff3ecb56bc6e21caf933ef167cab6cd81864
7,405
import Basic import Foundation import RxSwift import TuistCore import TuistSupport enum XCFrameworkBuilderError: FatalError { case nonFrameworkTarget(String) /// Error type. var type: ErrorType { switch self { case .nonFrameworkTarget: return .abort } } /// Error description. var description: String { switch self { case let .nonFrameworkTarget(name): return "Can't generate an .xcframework from the target '\(name)' because it's not a framework target" } } } public protocol XCFrameworkBuilding { /// Returns an observable build an xcframework for the given target. /// The target must have framework as product. /// /// - Parameters: /// - workspacePath: Path to the generated .xcworkspace that contains the given target. /// - target: Target whose .xcframework will be generated. /// - Returns: Path to the compiled .xcframework. func build(workspacePath: AbsolutePath, target: Target) throws -> Observable<AbsolutePath> /// Returns an observable to build an xcframework for the given target. /// The target must have framework as product. /// /// - Parameters: /// - projectPath: Path to the generated .xcodeproj that contains the given target. /// - target: Target whose .xcframework will be generated. /// - Returns: Path to the compiled .xcframework. func build(projectPath: AbsolutePath, target: Target) throws -> Observable<AbsolutePath> } public final class XCFrameworkBuilder: XCFrameworkBuilding { // MARK: - Attributes /// Xcode build controller instance to run xcodebuild commands. private let xcodeBuildController: XcodeBuildControlling // MARK: - Init /// Initializes the builder. /// - Parameter xcodeBuildController: Xcode build controller instance to run xcodebuild commands. public init(xcodeBuildController: XcodeBuildControlling) { self.xcodeBuildController = xcodeBuildController } // MARK: - XCFrameworkBuilding public func build(workspacePath: AbsolutePath, target: Target) throws -> Observable<AbsolutePath> { try build(.workspace(workspacePath), target: target) } public func build(projectPath: AbsolutePath, target: Target) throws -> Observable<AbsolutePath> { try build(.project(projectPath), target: target) } // MARK: - Fileprivate // swiftlint:disable:next function_body_length fileprivate func build(_ projectTarget: XcodeBuildTarget, target: Target) throws -> Observable<AbsolutePath> { if target.product != .framework { throw XCFrameworkBuilderError.nonFrameworkTarget(target.name) } let scheme = target.name.spm_shellEscaped() // Create temporary directories let outputDirectory = try TemporaryDirectory(removeTreeOnDeinit: false) let temporaryPath = try TemporaryDirectory(removeTreeOnDeinit: false) logger.notice("Building .xcframework for \(target.name)...", metadata: .section) // Build for the device // Without the BUILD_LIBRARY_FOR_DISTRIBUTION argument xcodebuild doesn't generate the .swiftinterface file let deviceArchivePath = temporaryPath.path.appending(component: "device.xcarchive") let deviceArchiveObservable = xcodeBuildController.archive(projectTarget, scheme: scheme, clean: true, archivePath: deviceArchivePath, arguments: [ .sdk(target.platform.xcodeDeviceSDK), .derivedDataPath(temporaryPath.path), .buildSetting("SKIP_INSTALL", "NO"), .buildSetting("BUILD_LIBRARY_FOR_DISTRIBUTION", "YES"), ]) .printFormattedOutput() .do(onSubscribed: { logger.notice("Building \(target.name) for device...", metadata: .subsection) }) // Build for the simulator var simulatorArchiveObservable: Observable<SystemEvent<XcodeBuildOutput>>? var simulatorArchivePath: AbsolutePath? if target.platform.hasSimulators { simulatorArchivePath = temporaryPath.path.appending(component: "simulator.xcarchive") simulatorArchiveObservable = xcodeBuildController.archive(projectTarget, scheme: scheme, clean: false, archivePath: simulatorArchivePath!, arguments: [ .sdk(target.platform.xcodeSimulatorSDK!), .derivedDataPath(temporaryPath.path), .buildSetting("SKIP_INSTALL", "NO"), .buildSetting("BUILD_LIBRARY_FOR_DISTRIBUTION", "YES"), ]) .printFormattedOutput() .do(onSubscribed: { logger.notice("Building \(target.name) for simulator", metadata: .subsection) }) } // Build the xcframework var frameworkpaths = [frameworkPath(fromArchivePath: deviceArchivePath, productName: target.productName)] if let simulatorArchivePath = simulatorArchivePath { frameworkpaths.append(frameworkPath(fromArchivePath: simulatorArchivePath, productName: target.productName)) } let xcframeworkPath = outputDirectory.path.appending(component: "\(target.productName).xcframework") let xcframeworkObservable = xcodeBuildController.createXCFramework(frameworks: frameworkpaths, output: xcframeworkPath) .do(onSubscribed: { logger.notice("Exporting xcframework for \(target.platform.caseValue)", metadata: .subsection) }) return deviceArchiveObservable .concat(simulatorArchiveObservable ?? Observable.empty()) .concat(xcframeworkObservable) .ignoreElements() .andThen(Observable.just(xcframeworkPath)) .do(afterCompleted: { try FileHandler.shared.delete(temporaryPath.path) }) } /// Returns the path to the framework inside the archive. /// - Parameters: /// - archivePath: Path to the .xcarchive. /// - productName: Product name. fileprivate func frameworkPath(fromArchivePath archivePath: AbsolutePath, productName: String) -> AbsolutePath { archivePath.appending(RelativePath("Products/Library/Frameworks/\(productName).framework")) } }
48.398693
129
0.574612
09eb0f08ccd7c9a3ee03b2ae22a88fe1f083383b
2,867
// // GYZConmentPhotosView.swift // baking // 上传图片view // Created by gouyz on 2017/4/3. // Copyright © 2017年 gouyz. All rights reserved. // import UIKit class GYZConmentPhotosView: UIView { var delegate: GYZConmentPhotosViewDelegate? var imageViewsArray:[UIImageView] = [] //5列,列间隔为5,距离屏幕边距左右各10 let imgWidth: CGFloat = (kScreenWidth - 40)*0.2 var selectImgs: [UIImage]?{ didSet{ if let imgArr = selectImgs { for index in imgArr.count ..< imageViewsArray.count { let imgView: UIImageView = imageViewsArray[index] imgView.isHidden = true } let perRowItemCount = 5 let margin: CGFloat = 5 for (index,item) in imgArr.enumerated() { let columnIndex = index % perRowItemCount let rowIndex = index/perRowItemCount let imgView: UIImageView = imageViewsArray[index] imgView.isHidden = false imgView.image = item imgView.frame = CGRect.init(x: CGFloat.init(columnIndex) * (imgWidth + margin), y: CGFloat.init(rowIndex) * (imgWidth + margin), width: imgWidth, height: imgWidth) } let columnIndex = imgArr.count % perRowItemCount let rowIndex = imgArr.count/perRowItemCount addImgBtn.frame = CGRect.init(x: CGFloat.init(columnIndex) * (imgWidth + margin), y: CGFloat.init(rowIndex) * (imgWidth + margin), width: imgWidth, height: imgWidth) } } } // MARK: 生命周期方法 override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI(){ for _ in 0 ..< kMaxSelectCount{ let imgView: UIImageView = UIImageView() addSubview(imgView) imageViewsArray.append(imgView) } addImgBtn.backgroundColor = kBackgroundColor addImgBtn.addOnClickListener(target: self, action: #selector(addImgOnClick)) addSubview(addImgBtn) addImgBtn.snp.makeConstraints { (make) in make.left.equalTo(self) make.top.equalTo(self) make.size.equalTo(CGSize.init(width: imgWidth, height: imgWidth)) } } /// 添加照片 lazy var addImgBtn: UIImageView = UIImageView.init(image: UIImage.init(named: "icon_conment_add")) /// 添加照片 func addImgOnClick() { delegate?.didClickAddImage() } } protocol GYZConmentPhotosViewDelegate { func didClickAddImage(); }
31.505495
183
0.55947
8fb40288f10eb1794e8220beda99db5949089cdf
1,028
// // FutureMatchers.swift // BothamNetworking // // Created by Pedro Vicente Gomez on 20/11/15. // Copyright © 2015 GoKarumi S.L. All rights reserved. // import Foundation import Nimble @testable import BothamNetworking public func beSuccess<T>() -> Predicate<T> { return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in failureMessage.postfixMessage = "be success" let result = try actualExpression.evaluate() as? Result<HTTPResponse, BothamAPIClientError> return (try? result?.get()) != nil } } public func failWithError<T>(_ expectedError: BothamAPIClientError) -> Predicate<T> { return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in failureMessage.postfixMessage = "has error" let result = try actualExpression.evaluate() as? Result<HTTPResponse, BothamAPIClientError> if case let .failure(error)? = result { return expectedError == error } else { return false } } }
31.151515
99
0.69358
89cb614a512349478286a595d105f2b24996df11
834
// // ListPresenterTests.swift // GrapeCITests // // Created by Ricardo Maqueda Martinez on 31/03/2020. // Copyright © 2020 Ricardo Maqueda Martinez. All rights reserved. // import XCTest import Combine @testable import GrapeCI class ListPresenterTests: XCTestCase { var sut: ListPresenter! var interactor: SpyFetchGitRepositoriesInteractorProtocol! private var subscriptions = Set<AnyCancellable>() override func setUpWithError() throws { try super.setUpWithError() interactor = SpyFetchGitRepositoriesInteractorProtocol() interactor.integratedRepositoriesResult = [] sut = ListPresenter(fetchGitRepositoriesInterator: interactor) } override func tearDownWithError() throws { interactor = nil sut = nil try super.tearDownWithError() } }
23.828571
70
0.715827
148773e7623a314e7b35772e6ee1ceb71201242c
152,215
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT. import Foundation import AWSSDKSwiftCore extension Inspector { public struct AddAttributesToFindingsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "attributes", required: true, type: .list), AWSShapeMember(label: "findingArns", required: true, type: .list) ] /// The array of attributes that you want to assign to specified findings. public let attributes: [Attribute] /// The ARNs that specify the findings that you want to assign attributes to. public let findingArns: [String] public init(attributes: [Attribute], findingArns: [String]) { self.attributes = attributes self.findingArns = findingArns } public func validate(name: String) throws { try self.attributes.forEach { try $0.validate(name: "\(name).attributes[]") } try validate(self.attributes, name:"attributes", parent: name, max: 10) try validate(self.attributes, name:"attributes", parent: name, min: 0) try self.findingArns.forEach { try validate($0, name: "findingArns[]", parent: name, max: 300) try validate($0, name: "findingArns[]", parent: name, min: 1) } try validate(self.findingArns, name:"findingArns", parent: name, max: 10) try validate(self.findingArns, name:"findingArns", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case attributes = "attributes" case findingArns = "findingArns" } } public struct AddAttributesToFindingsResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "failedItems", required: true, type: .map) ] /// Attribute details that cannot be described. An error code is provided for each failed item. public let failedItems: [String: FailedItemDetails] public init(failedItems: [String: FailedItemDetails]) { self.failedItems = failedItems } private enum CodingKeys: String, CodingKey { case failedItems = "failedItems" } } public struct AgentFilter: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "agentHealthCodes", required: true, type: .list), AWSShapeMember(label: "agentHealths", required: true, type: .list) ] /// The detailed health state of the agent. Values can be set to IDLE, RUNNING, SHUTDOWN, UNHEALTHY, THROTTLED, and UNKNOWN. public let agentHealthCodes: [AgentHealthCode] /// The current health state of the agent. Values can be set to HEALTHY or UNHEALTHY. public let agentHealths: [AgentHealth] public init(agentHealthCodes: [AgentHealthCode], agentHealths: [AgentHealth]) { self.agentHealthCodes = agentHealthCodes self.agentHealths = agentHealths } public func validate(name: String) throws { try validate(self.agentHealthCodes, name:"agentHealthCodes", parent: name, max: 10) try validate(self.agentHealthCodes, name:"agentHealthCodes", parent: name, min: 0) try validate(self.agentHealths, name:"agentHealths", parent: name, max: 10) try validate(self.agentHealths, name:"agentHealths", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case agentHealthCodes = "agentHealthCodes" case agentHealths = "agentHealths" } } public enum AgentHealth: String, CustomStringConvertible, Codable { case healthy = "HEALTHY" case unhealthy = "UNHEALTHY" case unknown = "UNKNOWN" public var description: String { return self.rawValue } } public enum AgentHealthCode: String, CustomStringConvertible, Codable { case idle = "IDLE" case running = "RUNNING" case shutdown = "SHUTDOWN" case unhealthy = "UNHEALTHY" case throttled = "THROTTLED" case unknown = "UNKNOWN" public var description: String { return self.rawValue } } public struct AgentPreview: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "agentHealth", required: false, type: .enum), AWSShapeMember(label: "agentId", required: true, type: .string), AWSShapeMember(label: "agentVersion", required: false, type: .string), AWSShapeMember(label: "autoScalingGroup", required: false, type: .string), AWSShapeMember(label: "hostname", required: false, type: .string), AWSShapeMember(label: "ipv4Address", required: false, type: .string), AWSShapeMember(label: "kernelVersion", required: false, type: .string), AWSShapeMember(label: "operatingSystem", required: false, type: .string) ] /// The health status of the Amazon Inspector Agent. public let agentHealth: AgentHealth? /// The ID of the EC2 instance where the agent is installed. public let agentId: String /// The version of the Amazon Inspector Agent. public let agentVersion: String? /// The Auto Scaling group for the EC2 instance where the agent is installed. public let autoScalingGroup: String? /// The hostname of the EC2 instance on which the Amazon Inspector Agent is installed. public let hostname: String? /// The IP address of the EC2 instance on which the Amazon Inspector Agent is installed. public let ipv4Address: String? /// The kernel version of the operating system running on the EC2 instance on which the Amazon Inspector Agent is installed. public let kernelVersion: String? /// The operating system running on the EC2 instance on which the Amazon Inspector Agent is installed. public let operatingSystem: String? public init(agentHealth: AgentHealth? = nil, agentId: String, agentVersion: String? = nil, autoScalingGroup: String? = nil, hostname: String? = nil, ipv4Address: String? = nil, kernelVersion: String? = nil, operatingSystem: String? = nil) { self.agentHealth = agentHealth self.agentId = agentId self.agentVersion = agentVersion self.autoScalingGroup = autoScalingGroup self.hostname = hostname self.ipv4Address = ipv4Address self.kernelVersion = kernelVersion self.operatingSystem = operatingSystem } private enum CodingKeys: String, CodingKey { case agentHealth = "agentHealth" case agentId = "agentId" case agentVersion = "agentVersion" case autoScalingGroup = "autoScalingGroup" case hostname = "hostname" case ipv4Address = "ipv4Address" case kernelVersion = "kernelVersion" case operatingSystem = "operatingSystem" } } public struct AssessmentRun: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "arn", required: true, type: .string), AWSShapeMember(label: "assessmentTemplateArn", required: true, type: .string), AWSShapeMember(label: "completedAt", required: false, type: .timestamp), AWSShapeMember(label: "createdAt", required: true, type: .timestamp), AWSShapeMember(label: "dataCollected", required: true, type: .boolean), AWSShapeMember(label: "durationInSeconds", required: true, type: .integer), AWSShapeMember(label: "findingCounts", required: true, type: .map), AWSShapeMember(label: "name", required: true, type: .string), AWSShapeMember(label: "notifications", required: true, type: .list), AWSShapeMember(label: "rulesPackageArns", required: true, type: .list), AWSShapeMember(label: "startedAt", required: false, type: .timestamp), AWSShapeMember(label: "state", required: true, type: .enum), AWSShapeMember(label: "stateChangedAt", required: true, type: .timestamp), AWSShapeMember(label: "stateChanges", required: true, type: .list), AWSShapeMember(label: "userAttributesForFindings", required: true, type: .list) ] /// The ARN of the assessment run. public let arn: String /// The ARN of the assessment template that is associated with the assessment run. public let assessmentTemplateArn: String /// The assessment run completion time that corresponds to the rules packages evaluation completion time or failure. public let completedAt: TimeStamp? /// The time when StartAssessmentRun was called. public let createdAt: TimeStamp /// A Boolean value (true or false) that specifies whether the process of collecting data from the agents is completed. public let dataCollected: Bool /// The duration of the assessment run. public let durationInSeconds: Int /// Provides a total count of generated findings per severity. public let findingCounts: [Severity: Int] /// The auto-generated name for the assessment run. public let name: String /// A list of notifications for the event subscriptions. A notification about a particular generated finding is added to this list only once. public let notifications: [AssessmentRunNotification] /// The rules packages selected for the assessment run. public let rulesPackageArns: [String] /// The time when StartAssessmentRun was called. public let startedAt: TimeStamp? /// The state of the assessment run. public let state: AssessmentRunState /// The last time when the assessment run's state changed. public let stateChangedAt: TimeStamp /// A list of the assessment run state changes. public let stateChanges: [AssessmentRunStateChange] /// The user-defined attributes that are assigned to every generated finding. public let userAttributesForFindings: [Attribute] public init(arn: String, assessmentTemplateArn: String, completedAt: TimeStamp? = nil, createdAt: TimeStamp, dataCollected: Bool, durationInSeconds: Int, findingCounts: [Severity: Int], name: String, notifications: [AssessmentRunNotification], rulesPackageArns: [String], startedAt: TimeStamp? = nil, state: AssessmentRunState, stateChangedAt: TimeStamp, stateChanges: [AssessmentRunStateChange], userAttributesForFindings: [Attribute]) { self.arn = arn self.assessmentTemplateArn = assessmentTemplateArn self.completedAt = completedAt self.createdAt = createdAt self.dataCollected = dataCollected self.durationInSeconds = durationInSeconds self.findingCounts = findingCounts self.name = name self.notifications = notifications self.rulesPackageArns = rulesPackageArns self.startedAt = startedAt self.state = state self.stateChangedAt = stateChangedAt self.stateChanges = stateChanges self.userAttributesForFindings = userAttributesForFindings } private enum CodingKeys: String, CodingKey { case arn = "arn" case assessmentTemplateArn = "assessmentTemplateArn" case completedAt = "completedAt" case createdAt = "createdAt" case dataCollected = "dataCollected" case durationInSeconds = "durationInSeconds" case findingCounts = "findingCounts" case name = "name" case notifications = "notifications" case rulesPackageArns = "rulesPackageArns" case startedAt = "startedAt" case state = "state" case stateChangedAt = "stateChangedAt" case stateChanges = "stateChanges" case userAttributesForFindings = "userAttributesForFindings" } } public struct AssessmentRunAgent: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "agentHealth", required: true, type: .enum), AWSShapeMember(label: "agentHealthCode", required: true, type: .enum), AWSShapeMember(label: "agentHealthDetails", required: false, type: .string), AWSShapeMember(label: "agentId", required: true, type: .string), AWSShapeMember(label: "assessmentRunArn", required: true, type: .string), AWSShapeMember(label: "autoScalingGroup", required: false, type: .string), AWSShapeMember(label: "telemetryMetadata", required: true, type: .list) ] /// The current health state of the agent. public let agentHealth: AgentHealth /// The detailed health state of the agent. public let agentHealthCode: AgentHealthCode /// The description for the agent health code. public let agentHealthDetails: String? /// The AWS account of the EC2 instance where the agent is installed. public let agentId: String /// The ARN of the assessment run that is associated with the agent. public let assessmentRunArn: String /// The Auto Scaling group of the EC2 instance that is specified by the agent ID. public let autoScalingGroup: String? /// The Amazon Inspector application data metrics that are collected by the agent. public let telemetryMetadata: [TelemetryMetadata] public init(agentHealth: AgentHealth, agentHealthCode: AgentHealthCode, agentHealthDetails: String? = nil, agentId: String, assessmentRunArn: String, autoScalingGroup: String? = nil, telemetryMetadata: [TelemetryMetadata]) { self.agentHealth = agentHealth self.agentHealthCode = agentHealthCode self.agentHealthDetails = agentHealthDetails self.agentId = agentId self.assessmentRunArn = assessmentRunArn self.autoScalingGroup = autoScalingGroup self.telemetryMetadata = telemetryMetadata } private enum CodingKeys: String, CodingKey { case agentHealth = "agentHealth" case agentHealthCode = "agentHealthCode" case agentHealthDetails = "agentHealthDetails" case agentId = "agentId" case assessmentRunArn = "assessmentRunArn" case autoScalingGroup = "autoScalingGroup" case telemetryMetadata = "telemetryMetadata" } } public struct AssessmentRunFilter: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "completionTimeRange", required: false, type: .structure), AWSShapeMember(label: "durationRange", required: false, type: .structure), AWSShapeMember(label: "namePattern", required: false, type: .string), AWSShapeMember(label: "rulesPackageArns", required: false, type: .list), AWSShapeMember(label: "startTimeRange", required: false, type: .structure), AWSShapeMember(label: "stateChangeTimeRange", required: false, type: .structure), AWSShapeMember(label: "states", required: false, type: .list) ] /// For a record to match a filter, the value that is specified for this data type property must inclusively match any value between the specified minimum and maximum values of the completedAt property of the AssessmentRun data type. public let completionTimeRange: TimestampRange? /// For a record to match a filter, the value that is specified for this data type property must inclusively match any value between the specified minimum and maximum values of the durationInSeconds property of the AssessmentRun data type. public let durationRange: DurationRange? /// For a record to match a filter, an explicit value or a string containing a wildcard that is specified for this data type property must match the value of the assessmentRunName property of the AssessmentRun data type. public let namePattern: String? /// For a record to match a filter, the value that is specified for this data type property must be contained in the list of values of the rulesPackages property of the AssessmentRun data type. public let rulesPackageArns: [String]? /// For a record to match a filter, the value that is specified for this data type property must inclusively match any value between the specified minimum and maximum values of the startTime property of the AssessmentRun data type. public let startTimeRange: TimestampRange? /// For a record to match a filter, the value that is specified for this data type property must match the stateChangedAt property of the AssessmentRun data type. public let stateChangeTimeRange: TimestampRange? /// For a record to match a filter, one of the values specified for this data type property must be the exact match of the value of the assessmentRunState property of the AssessmentRun data type. public let states: [AssessmentRunState]? public init(completionTimeRange: TimestampRange? = nil, durationRange: DurationRange? = nil, namePattern: String? = nil, rulesPackageArns: [String]? = nil, startTimeRange: TimestampRange? = nil, stateChangeTimeRange: TimestampRange? = nil, states: [AssessmentRunState]? = nil) { self.completionTimeRange = completionTimeRange self.durationRange = durationRange self.namePattern = namePattern self.rulesPackageArns = rulesPackageArns self.startTimeRange = startTimeRange self.stateChangeTimeRange = stateChangeTimeRange self.states = states } public func validate(name: String) throws { try self.durationRange?.validate(name: "\(name).durationRange") try validate(self.namePattern, name:"namePattern", parent: name, max: 140) try validate(self.namePattern, name:"namePattern", parent: name, min: 1) try self.rulesPackageArns?.forEach { try validate($0, name: "rulesPackageArns[]", parent: name, max: 300) try validate($0, name: "rulesPackageArns[]", parent: name, min: 1) } try validate(self.rulesPackageArns, name:"rulesPackageArns", parent: name, max: 50) try validate(self.rulesPackageArns, name:"rulesPackageArns", parent: name, min: 0) try validate(self.states, name:"states", parent: name, max: 50) try validate(self.states, name:"states", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case completionTimeRange = "completionTimeRange" case durationRange = "durationRange" case namePattern = "namePattern" case rulesPackageArns = "rulesPackageArns" case startTimeRange = "startTimeRange" case stateChangeTimeRange = "stateChangeTimeRange" case states = "states" } } public struct AssessmentRunNotification: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "date", required: true, type: .timestamp), AWSShapeMember(label: "error", required: true, type: .boolean), AWSShapeMember(label: "event", required: true, type: .enum), AWSShapeMember(label: "message", required: false, type: .string), AWSShapeMember(label: "snsPublishStatusCode", required: false, type: .enum), AWSShapeMember(label: "snsTopicArn", required: false, type: .string) ] /// The date of the notification. public let date: TimeStamp /// The Boolean value that specifies whether the notification represents an error. public let error: Bool /// The event for which a notification is sent. public let event: InspectorEvent /// The message included in the notification. public let message: String? /// The status code of the SNS notification. public let snsPublishStatusCode: AssessmentRunNotificationSnsStatusCode? /// The SNS topic to which the SNS notification is sent. public let snsTopicArn: String? public init(date: TimeStamp, error: Bool, event: InspectorEvent, message: String? = nil, snsPublishStatusCode: AssessmentRunNotificationSnsStatusCode? = nil, snsTopicArn: String? = nil) { self.date = date self.error = error self.event = event self.message = message self.snsPublishStatusCode = snsPublishStatusCode self.snsTopicArn = snsTopicArn } private enum CodingKeys: String, CodingKey { case date = "date" case error = "error" case event = "event" case message = "message" case snsPublishStatusCode = "snsPublishStatusCode" case snsTopicArn = "snsTopicArn" } } public enum AssessmentRunNotificationSnsStatusCode: String, CustomStringConvertible, Codable { case success = "SUCCESS" case topicDoesNotExist = "TOPIC_DOES_NOT_EXIST" case accessDenied = "ACCESS_DENIED" case internalError = "INTERNAL_ERROR" public var description: String { return self.rawValue } } public enum AssessmentRunState: String, CustomStringConvertible, Codable { case created = "CREATED" case startDataCollectionPending = "START_DATA_COLLECTION_PENDING" case startDataCollectionInProgress = "START_DATA_COLLECTION_IN_PROGRESS" case collectingData = "COLLECTING_DATA" case stopDataCollectionPending = "STOP_DATA_COLLECTION_PENDING" case dataCollected = "DATA_COLLECTED" case startEvaluatingRulesPending = "START_EVALUATING_RULES_PENDING" case evaluatingRules = "EVALUATING_RULES" case failed = "FAILED" case error = "ERROR" case completed = "COMPLETED" case completedWithErrors = "COMPLETED_WITH_ERRORS" case canceled = "CANCELED" public var description: String { return self.rawValue } } public struct AssessmentRunStateChange: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "state", required: true, type: .enum), AWSShapeMember(label: "stateChangedAt", required: true, type: .timestamp) ] /// The assessment run state. public let state: AssessmentRunState /// The last time the assessment run state changed. public let stateChangedAt: TimeStamp public init(state: AssessmentRunState, stateChangedAt: TimeStamp) { self.state = state self.stateChangedAt = stateChangedAt } private enum CodingKeys: String, CodingKey { case state = "state" case stateChangedAt = "stateChangedAt" } } public struct AssessmentTarget: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "arn", required: true, type: .string), AWSShapeMember(label: "createdAt", required: true, type: .timestamp), AWSShapeMember(label: "name", required: true, type: .string), AWSShapeMember(label: "resourceGroupArn", required: false, type: .string), AWSShapeMember(label: "updatedAt", required: true, type: .timestamp) ] /// The ARN that specifies the Amazon Inspector assessment target. public let arn: String /// The time at which the assessment target is created. public let createdAt: TimeStamp /// The name of the Amazon Inspector assessment target. public let name: String /// The ARN that specifies the resource group that is associated with the assessment target. public let resourceGroupArn: String? /// The time at which UpdateAssessmentTarget is called. public let updatedAt: TimeStamp public init(arn: String, createdAt: TimeStamp, name: String, resourceGroupArn: String? = nil, updatedAt: TimeStamp) { self.arn = arn self.createdAt = createdAt self.name = name self.resourceGroupArn = resourceGroupArn self.updatedAt = updatedAt } private enum CodingKeys: String, CodingKey { case arn = "arn" case createdAt = "createdAt" case name = "name" case resourceGroupArn = "resourceGroupArn" case updatedAt = "updatedAt" } } public struct AssessmentTargetFilter: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTargetNamePattern", required: false, type: .string) ] /// For a record to match a filter, an explicit value or a string that contains a wildcard that is specified for this data type property must match the value of the assessmentTargetName property of the AssessmentTarget data type. public let assessmentTargetNamePattern: String? public init(assessmentTargetNamePattern: String? = nil) { self.assessmentTargetNamePattern = assessmentTargetNamePattern } public func validate(name: String) throws { try validate(self.assessmentTargetNamePattern, name:"assessmentTargetNamePattern", parent: name, max: 140) try validate(self.assessmentTargetNamePattern, name:"assessmentTargetNamePattern", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentTargetNamePattern = "assessmentTargetNamePattern" } } public struct AssessmentTemplate: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "arn", required: true, type: .string), AWSShapeMember(label: "assessmentRunCount", required: true, type: .integer), AWSShapeMember(label: "assessmentTargetArn", required: true, type: .string), AWSShapeMember(label: "createdAt", required: true, type: .timestamp), AWSShapeMember(label: "durationInSeconds", required: true, type: .integer), AWSShapeMember(label: "lastAssessmentRunArn", required: false, type: .string), AWSShapeMember(label: "name", required: true, type: .string), AWSShapeMember(label: "rulesPackageArns", required: true, type: .list), AWSShapeMember(label: "userAttributesForFindings", required: true, type: .list) ] /// The ARN of the assessment template. public let arn: String /// The number of existing assessment runs associated with this assessment template. This value can be zero or a positive integer. public let assessmentRunCount: Int /// The ARN of the assessment target that corresponds to this assessment template. public let assessmentTargetArn: String /// The time at which the assessment template is created. public let createdAt: TimeStamp /// The duration in seconds specified for this assessment template. The default value is 3600 seconds (one hour). The maximum value is 86400 seconds (one day). public let durationInSeconds: Int /// The Amazon Resource Name (ARN) of the most recent assessment run associated with this assessment template. This value exists only when the value of assessmentRunCount is greaterpa than zero. public let lastAssessmentRunArn: String? /// The name of the assessment template. public let name: String /// The rules packages that are specified for this assessment template. public let rulesPackageArns: [String] /// The user-defined attributes that are assigned to every generated finding from the assessment run that uses this assessment template. public let userAttributesForFindings: [Attribute] public init(arn: String, assessmentRunCount: Int, assessmentTargetArn: String, createdAt: TimeStamp, durationInSeconds: Int, lastAssessmentRunArn: String? = nil, name: String, rulesPackageArns: [String], userAttributesForFindings: [Attribute]) { self.arn = arn self.assessmentRunCount = assessmentRunCount self.assessmentTargetArn = assessmentTargetArn self.createdAt = createdAt self.durationInSeconds = durationInSeconds self.lastAssessmentRunArn = lastAssessmentRunArn self.name = name self.rulesPackageArns = rulesPackageArns self.userAttributesForFindings = userAttributesForFindings } private enum CodingKeys: String, CodingKey { case arn = "arn" case assessmentRunCount = "assessmentRunCount" case assessmentTargetArn = "assessmentTargetArn" case createdAt = "createdAt" case durationInSeconds = "durationInSeconds" case lastAssessmentRunArn = "lastAssessmentRunArn" case name = "name" case rulesPackageArns = "rulesPackageArns" case userAttributesForFindings = "userAttributesForFindings" } } public struct AssessmentTemplateFilter: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "durationRange", required: false, type: .structure), AWSShapeMember(label: "namePattern", required: false, type: .string), AWSShapeMember(label: "rulesPackageArns", required: false, type: .list) ] /// For a record to match a filter, the value specified for this data type property must inclusively match any value between the specified minimum and maximum values of the durationInSeconds property of the AssessmentTemplate data type. public let durationRange: DurationRange? /// For a record to match a filter, an explicit value or a string that contains a wildcard that is specified for this data type property must match the value of the assessmentTemplateName property of the AssessmentTemplate data type. public let namePattern: String? /// For a record to match a filter, the values that are specified for this data type property must be contained in the list of values of the rulesPackageArns property of the AssessmentTemplate data type. public let rulesPackageArns: [String]? public init(durationRange: DurationRange? = nil, namePattern: String? = nil, rulesPackageArns: [String]? = nil) { self.durationRange = durationRange self.namePattern = namePattern self.rulesPackageArns = rulesPackageArns } public func validate(name: String) throws { try self.durationRange?.validate(name: "\(name).durationRange") try validate(self.namePattern, name:"namePattern", parent: name, max: 140) try validate(self.namePattern, name:"namePattern", parent: name, min: 1) try self.rulesPackageArns?.forEach { try validate($0, name: "rulesPackageArns[]", parent: name, max: 300) try validate($0, name: "rulesPackageArns[]", parent: name, min: 1) } try validate(self.rulesPackageArns, name:"rulesPackageArns", parent: name, max: 50) try validate(self.rulesPackageArns, name:"rulesPackageArns", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case durationRange = "durationRange" case namePattern = "namePattern" case rulesPackageArns = "rulesPackageArns" } } public struct AssetAttributes: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "agentId", required: false, type: .string), AWSShapeMember(label: "amiId", required: false, type: .string), AWSShapeMember(label: "autoScalingGroup", required: false, type: .string), AWSShapeMember(label: "hostname", required: false, type: .string), AWSShapeMember(label: "ipv4Addresses", required: false, type: .list), AWSShapeMember(label: "networkInterfaces", required: false, type: .list), AWSShapeMember(label: "schemaVersion", required: true, type: .integer), AWSShapeMember(label: "tags", required: false, type: .list) ] /// The ID of the agent that is installed on the EC2 instance where the finding is generated. public let agentId: String? /// The ID of the Amazon Machine Image (AMI) that is installed on the EC2 instance where the finding is generated. public let amiId: String? /// The Auto Scaling group of the EC2 instance where the finding is generated. public let autoScalingGroup: String? /// The hostname of the EC2 instance where the finding is generated. public let hostname: String? /// The list of IP v4 addresses of the EC2 instance where the finding is generated. public let ipv4Addresses: [String]? /// An array of the network interfaces interacting with the EC2 instance where the finding is generated. public let networkInterfaces: [NetworkInterface]? /// The schema version of this data type. public let schemaVersion: Int /// The tags related to the EC2 instance where the finding is generated. public let tags: [Tag]? public init(agentId: String? = nil, amiId: String? = nil, autoScalingGroup: String? = nil, hostname: String? = nil, ipv4Addresses: [String]? = nil, networkInterfaces: [NetworkInterface]? = nil, schemaVersion: Int, tags: [Tag]? = nil) { self.agentId = agentId self.amiId = amiId self.autoScalingGroup = autoScalingGroup self.hostname = hostname self.ipv4Addresses = ipv4Addresses self.networkInterfaces = networkInterfaces self.schemaVersion = schemaVersion self.tags = tags } private enum CodingKeys: String, CodingKey { case agentId = "agentId" case amiId = "amiId" case autoScalingGroup = "autoScalingGroup" case hostname = "hostname" case ipv4Addresses = "ipv4Addresses" case networkInterfaces = "networkInterfaces" case schemaVersion = "schemaVersion" case tags = "tags" } } public enum AssetType: String, CustomStringConvertible, Codable { case ec2Instance = "ec2-instance" public var description: String { return self.rawValue } } public struct Attribute: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "key", required: true, type: .string), AWSShapeMember(label: "value", required: false, type: .string) ] /// The attribute key. public let key: String /// The value assigned to the attribute key. public let value: String? public init(key: String, value: String? = nil) { self.key = key self.value = value } public func validate(name: String) throws { try validate(self.key, name:"key", parent: name, max: 128) try validate(self.key, name:"key", parent: name, min: 1) try validate(self.value, name:"value", parent: name, max: 256) try validate(self.value, name:"value", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case key = "key" case value = "value" } } public struct CreateAssessmentTargetRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTargetName", required: true, type: .string), AWSShapeMember(label: "resourceGroupArn", required: false, type: .string) ] /// The user-defined name that identifies the assessment target that you want to create. The name must be unique within the AWS account. public let assessmentTargetName: String /// The ARN that specifies the resource group that is used to create the assessment target. If resourceGroupArn is not specified, all EC2 instances in the current AWS account and region are included in the assessment target. public let resourceGroupArn: String? public init(assessmentTargetName: String, resourceGroupArn: String? = nil) { self.assessmentTargetName = assessmentTargetName self.resourceGroupArn = resourceGroupArn } public func validate(name: String) throws { try validate(self.assessmentTargetName, name:"assessmentTargetName", parent: name, max: 140) try validate(self.assessmentTargetName, name:"assessmentTargetName", parent: name, min: 1) try validate(self.resourceGroupArn, name:"resourceGroupArn", parent: name, max: 300) try validate(self.resourceGroupArn, name:"resourceGroupArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentTargetName = "assessmentTargetName" case resourceGroupArn = "resourceGroupArn" } } public struct CreateAssessmentTargetResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTargetArn", required: true, type: .string) ] /// The ARN that specifies the assessment target that is created. public let assessmentTargetArn: String public init(assessmentTargetArn: String) { self.assessmentTargetArn = assessmentTargetArn } private enum CodingKeys: String, CodingKey { case assessmentTargetArn = "assessmentTargetArn" } } public struct CreateAssessmentTemplateRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTargetArn", required: true, type: .string), AWSShapeMember(label: "assessmentTemplateName", required: true, type: .string), AWSShapeMember(label: "durationInSeconds", required: true, type: .integer), AWSShapeMember(label: "rulesPackageArns", required: true, type: .list), AWSShapeMember(label: "userAttributesForFindings", required: false, type: .list) ] /// The ARN that specifies the assessment target for which you want to create the assessment template. public let assessmentTargetArn: String /// The user-defined name that identifies the assessment template that you want to create. You can create several assessment templates for an assessment target. The names of the assessment templates that correspond to a particular assessment target must be unique. public let assessmentTemplateName: String /// The duration of the assessment run in seconds. public let durationInSeconds: Int /// The ARNs that specify the rules packages that you want to attach to the assessment template. public let rulesPackageArns: [String] /// The user-defined attributes that are assigned to every finding that is generated by the assessment run that uses this assessment template. An attribute is a key and value pair (an Attribute object). Within an assessment template, each key must be unique. public let userAttributesForFindings: [Attribute]? public init(assessmentTargetArn: String, assessmentTemplateName: String, durationInSeconds: Int, rulesPackageArns: [String], userAttributesForFindings: [Attribute]? = nil) { self.assessmentTargetArn = assessmentTargetArn self.assessmentTemplateName = assessmentTemplateName self.durationInSeconds = durationInSeconds self.rulesPackageArns = rulesPackageArns self.userAttributesForFindings = userAttributesForFindings } public func validate(name: String) throws { try validate(self.assessmentTargetArn, name:"assessmentTargetArn", parent: name, max: 300) try validate(self.assessmentTargetArn, name:"assessmentTargetArn", parent: name, min: 1) try validate(self.assessmentTemplateName, name:"assessmentTemplateName", parent: name, max: 140) try validate(self.assessmentTemplateName, name:"assessmentTemplateName", parent: name, min: 1) try validate(self.durationInSeconds, name:"durationInSeconds", parent: name, max: 86400) try validate(self.durationInSeconds, name:"durationInSeconds", parent: name, min: 180) try self.rulesPackageArns.forEach { try validate($0, name: "rulesPackageArns[]", parent: name, max: 300) try validate($0, name: "rulesPackageArns[]", parent: name, min: 1) } try validate(self.rulesPackageArns, name:"rulesPackageArns", parent: name, max: 50) try validate(self.rulesPackageArns, name:"rulesPackageArns", parent: name, min: 0) try self.userAttributesForFindings?.forEach { try $0.validate(name: "\(name).userAttributesForFindings[]") } try validate(self.userAttributesForFindings, name:"userAttributesForFindings", parent: name, max: 10) try validate(self.userAttributesForFindings, name:"userAttributesForFindings", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case assessmentTargetArn = "assessmentTargetArn" case assessmentTemplateName = "assessmentTemplateName" case durationInSeconds = "durationInSeconds" case rulesPackageArns = "rulesPackageArns" case userAttributesForFindings = "userAttributesForFindings" } } public struct CreateAssessmentTemplateResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTemplateArn", required: true, type: .string) ] /// The ARN that specifies the assessment template that is created. public let assessmentTemplateArn: String public init(assessmentTemplateArn: String) { self.assessmentTemplateArn = assessmentTemplateArn } private enum CodingKeys: String, CodingKey { case assessmentTemplateArn = "assessmentTemplateArn" } } public struct CreateExclusionsPreviewRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTemplateArn", required: true, type: .string) ] /// The ARN that specifies the assessment template for which you want to create an exclusions preview. public let assessmentTemplateArn: String public init(assessmentTemplateArn: String) { self.assessmentTemplateArn = assessmentTemplateArn } public func validate(name: String) throws { try validate(self.assessmentTemplateArn, name:"assessmentTemplateArn", parent: name, max: 300) try validate(self.assessmentTemplateArn, name:"assessmentTemplateArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentTemplateArn = "assessmentTemplateArn" } } public struct CreateExclusionsPreviewResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "previewToken", required: true, type: .string) ] /// Specifies the unique identifier of the requested exclusions preview. You can use the unique identifier to retrieve the exclusions preview when running the GetExclusionsPreview API. public let previewToken: String public init(previewToken: String) { self.previewToken = previewToken } private enum CodingKeys: String, CodingKey { case previewToken = "previewToken" } } public struct CreateResourceGroupRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "resourceGroupTags", required: true, type: .list) ] /// A collection of keys and an array of possible values, '[{"key":"key1","values":["Value1","Value2"]},{"key":"Key2","values":["Value3"]}]'. For example,'[{"key":"Name","values":["TestEC2Instance"]}]'. public let resourceGroupTags: [ResourceGroupTag] public init(resourceGroupTags: [ResourceGroupTag]) { self.resourceGroupTags = resourceGroupTags } public func validate(name: String) throws { try self.resourceGroupTags.forEach { try $0.validate(name: "\(name).resourceGroupTags[]") } try validate(self.resourceGroupTags, name:"resourceGroupTags", parent: name, max: 10) try validate(self.resourceGroupTags, name:"resourceGroupTags", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case resourceGroupTags = "resourceGroupTags" } } public struct CreateResourceGroupResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "resourceGroupArn", required: true, type: .string) ] /// The ARN that specifies the resource group that is created. public let resourceGroupArn: String public init(resourceGroupArn: String) { self.resourceGroupArn = resourceGroupArn } private enum CodingKeys: String, CodingKey { case resourceGroupArn = "resourceGroupArn" } } public struct DeleteAssessmentRunRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentRunArn", required: true, type: .string) ] /// The ARN that specifies the assessment run that you want to delete. public let assessmentRunArn: String public init(assessmentRunArn: String) { self.assessmentRunArn = assessmentRunArn } public func validate(name: String) throws { try validate(self.assessmentRunArn, name:"assessmentRunArn", parent: name, max: 300) try validate(self.assessmentRunArn, name:"assessmentRunArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentRunArn = "assessmentRunArn" } } public struct DeleteAssessmentTargetRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTargetArn", required: true, type: .string) ] /// The ARN that specifies the assessment target that you want to delete. public let assessmentTargetArn: String public init(assessmentTargetArn: String) { self.assessmentTargetArn = assessmentTargetArn } public func validate(name: String) throws { try validate(self.assessmentTargetArn, name:"assessmentTargetArn", parent: name, max: 300) try validate(self.assessmentTargetArn, name:"assessmentTargetArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentTargetArn = "assessmentTargetArn" } } public struct DeleteAssessmentTemplateRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTemplateArn", required: true, type: .string) ] /// The ARN that specifies the assessment template that you want to delete. public let assessmentTemplateArn: String public init(assessmentTemplateArn: String) { self.assessmentTemplateArn = assessmentTemplateArn } public func validate(name: String) throws { try validate(self.assessmentTemplateArn, name:"assessmentTemplateArn", parent: name, max: 300) try validate(self.assessmentTemplateArn, name:"assessmentTemplateArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentTemplateArn = "assessmentTemplateArn" } } public struct DescribeAssessmentRunsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentRunArns", required: true, type: .list) ] /// The ARN that specifies the assessment run that you want to describe. public let assessmentRunArns: [String] public init(assessmentRunArns: [String]) { self.assessmentRunArns = assessmentRunArns } public func validate(name: String) throws { try self.assessmentRunArns.forEach { try validate($0, name: "assessmentRunArns[]", parent: name, max: 300) try validate($0, name: "assessmentRunArns[]", parent: name, min: 1) } try validate(self.assessmentRunArns, name:"assessmentRunArns", parent: name, max: 10) try validate(self.assessmentRunArns, name:"assessmentRunArns", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentRunArns = "assessmentRunArns" } } public struct DescribeAssessmentRunsResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentRuns", required: true, type: .list), AWSShapeMember(label: "failedItems", required: true, type: .map) ] /// Information about the assessment run. public let assessmentRuns: [AssessmentRun] /// Assessment run details that cannot be described. An error code is provided for each failed item. public let failedItems: [String: FailedItemDetails] public init(assessmentRuns: [AssessmentRun], failedItems: [String: FailedItemDetails]) { self.assessmentRuns = assessmentRuns self.failedItems = failedItems } private enum CodingKeys: String, CodingKey { case assessmentRuns = "assessmentRuns" case failedItems = "failedItems" } } public struct DescribeAssessmentTargetsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTargetArns", required: true, type: .list) ] /// The ARNs that specifies the assessment targets that you want to describe. public let assessmentTargetArns: [String] public init(assessmentTargetArns: [String]) { self.assessmentTargetArns = assessmentTargetArns } public func validate(name: String) throws { try self.assessmentTargetArns.forEach { try validate($0, name: "assessmentTargetArns[]", parent: name, max: 300) try validate($0, name: "assessmentTargetArns[]", parent: name, min: 1) } try validate(self.assessmentTargetArns, name:"assessmentTargetArns", parent: name, max: 10) try validate(self.assessmentTargetArns, name:"assessmentTargetArns", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentTargetArns = "assessmentTargetArns" } } public struct DescribeAssessmentTargetsResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTargets", required: true, type: .list), AWSShapeMember(label: "failedItems", required: true, type: .map) ] /// Information about the assessment targets. public let assessmentTargets: [AssessmentTarget] /// Assessment target details that cannot be described. An error code is provided for each failed item. public let failedItems: [String: FailedItemDetails] public init(assessmentTargets: [AssessmentTarget], failedItems: [String: FailedItemDetails]) { self.assessmentTargets = assessmentTargets self.failedItems = failedItems } private enum CodingKeys: String, CodingKey { case assessmentTargets = "assessmentTargets" case failedItems = "failedItems" } } public struct DescribeAssessmentTemplatesRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTemplateArns", required: true, type: .list) ] public let assessmentTemplateArns: [String] public init(assessmentTemplateArns: [String]) { self.assessmentTemplateArns = assessmentTemplateArns } public func validate(name: String) throws { try self.assessmentTemplateArns.forEach { try validate($0, name: "assessmentTemplateArns[]", parent: name, max: 300) try validate($0, name: "assessmentTemplateArns[]", parent: name, min: 1) } try validate(self.assessmentTemplateArns, name:"assessmentTemplateArns", parent: name, max: 10) try validate(self.assessmentTemplateArns, name:"assessmentTemplateArns", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentTemplateArns = "assessmentTemplateArns" } } public struct DescribeAssessmentTemplatesResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTemplates", required: true, type: .list), AWSShapeMember(label: "failedItems", required: true, type: .map) ] /// Information about the assessment templates. public let assessmentTemplates: [AssessmentTemplate] /// Assessment template details that cannot be described. An error code is provided for each failed item. public let failedItems: [String: FailedItemDetails] public init(assessmentTemplates: [AssessmentTemplate], failedItems: [String: FailedItemDetails]) { self.assessmentTemplates = assessmentTemplates self.failedItems = failedItems } private enum CodingKeys: String, CodingKey { case assessmentTemplates = "assessmentTemplates" case failedItems = "failedItems" } } public struct DescribeCrossAccountAccessRoleResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "registeredAt", required: true, type: .timestamp), AWSShapeMember(label: "roleArn", required: true, type: .string), AWSShapeMember(label: "valid", required: true, type: .boolean) ] /// The date when the cross-account access role was registered. public let registeredAt: TimeStamp /// The ARN that specifies the IAM role that Amazon Inspector uses to access your AWS account. public let roleArn: String /// A Boolean value that specifies whether the IAM role has the necessary policies attached to enable Amazon Inspector to access your AWS account. public let valid: Bool public init(registeredAt: TimeStamp, roleArn: String, valid: Bool) { self.registeredAt = registeredAt self.roleArn = roleArn self.valid = valid } private enum CodingKeys: String, CodingKey { case registeredAt = "registeredAt" case roleArn = "roleArn" case valid = "valid" } } public struct DescribeExclusionsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "exclusionArns", required: true, type: .list), AWSShapeMember(label: "locale", required: false, type: .enum) ] /// The list of ARNs that specify the exclusions that you want to describe. public let exclusionArns: [String] /// The locale into which you want to translate the exclusion's title, description, and recommendation. public let locale: Locale? public init(exclusionArns: [String], locale: Locale? = nil) { self.exclusionArns = exclusionArns self.locale = locale } public func validate(name: String) throws { try self.exclusionArns.forEach { try validate($0, name: "exclusionArns[]", parent: name, max: 300) try validate($0, name: "exclusionArns[]", parent: name, min: 1) } try validate(self.exclusionArns, name:"exclusionArns", parent: name, max: 100) try validate(self.exclusionArns, name:"exclusionArns", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case exclusionArns = "exclusionArns" case locale = "locale" } } public struct DescribeExclusionsResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "exclusions", required: true, type: .map), AWSShapeMember(label: "failedItems", required: true, type: .map) ] /// Information about the exclusions. public let exclusions: [String: Exclusion] /// Exclusion details that cannot be described. An error code is provided for each failed item. public let failedItems: [String: FailedItemDetails] public init(exclusions: [String: Exclusion], failedItems: [String: FailedItemDetails]) { self.exclusions = exclusions self.failedItems = failedItems } private enum CodingKeys: String, CodingKey { case exclusions = "exclusions" case failedItems = "failedItems" } } public struct DescribeFindingsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "findingArns", required: true, type: .list), AWSShapeMember(label: "locale", required: false, type: .enum) ] /// The ARN that specifies the finding that you want to describe. public let findingArns: [String] /// The locale into which you want to translate a finding description, recommendation, and the short description that identifies the finding. public let locale: Locale? public init(findingArns: [String], locale: Locale? = nil) { self.findingArns = findingArns self.locale = locale } public func validate(name: String) throws { try self.findingArns.forEach { try validate($0, name: "findingArns[]", parent: name, max: 300) try validate($0, name: "findingArns[]", parent: name, min: 1) } try validate(self.findingArns, name:"findingArns", parent: name, max: 10) try validate(self.findingArns, name:"findingArns", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case findingArns = "findingArns" case locale = "locale" } } public struct DescribeFindingsResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "failedItems", required: true, type: .map), AWSShapeMember(label: "findings", required: true, type: .list) ] /// Finding details that cannot be described. An error code is provided for each failed item. public let failedItems: [String: FailedItemDetails] /// Information about the finding. public let findings: [Finding] public init(failedItems: [String: FailedItemDetails], findings: [Finding]) { self.failedItems = failedItems self.findings = findings } private enum CodingKeys: String, CodingKey { case failedItems = "failedItems" case findings = "findings" } } public struct DescribeResourceGroupsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "resourceGroupArns", required: true, type: .list) ] /// The ARN that specifies the resource group that you want to describe. public let resourceGroupArns: [String] public init(resourceGroupArns: [String]) { self.resourceGroupArns = resourceGroupArns } public func validate(name: String) throws { try self.resourceGroupArns.forEach { try validate($0, name: "resourceGroupArns[]", parent: name, max: 300) try validate($0, name: "resourceGroupArns[]", parent: name, min: 1) } try validate(self.resourceGroupArns, name:"resourceGroupArns", parent: name, max: 10) try validate(self.resourceGroupArns, name:"resourceGroupArns", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case resourceGroupArns = "resourceGroupArns" } } public struct DescribeResourceGroupsResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "failedItems", required: true, type: .map), AWSShapeMember(label: "resourceGroups", required: true, type: .list) ] /// Resource group details that cannot be described. An error code is provided for each failed item. public let failedItems: [String: FailedItemDetails] /// Information about a resource group. public let resourceGroups: [ResourceGroup] public init(failedItems: [String: FailedItemDetails], resourceGroups: [ResourceGroup]) { self.failedItems = failedItems self.resourceGroups = resourceGroups } private enum CodingKeys: String, CodingKey { case failedItems = "failedItems" case resourceGroups = "resourceGroups" } } public struct DescribeRulesPackagesRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "locale", required: false, type: .enum), AWSShapeMember(label: "rulesPackageArns", required: true, type: .list) ] /// The locale that you want to translate a rules package description into. public let locale: Locale? /// The ARN that specifies the rules package that you want to describe. public let rulesPackageArns: [String] public init(locale: Locale? = nil, rulesPackageArns: [String]) { self.locale = locale self.rulesPackageArns = rulesPackageArns } public func validate(name: String) throws { try self.rulesPackageArns.forEach { try validate($0, name: "rulesPackageArns[]", parent: name, max: 300) try validate($0, name: "rulesPackageArns[]", parent: name, min: 1) } try validate(self.rulesPackageArns, name:"rulesPackageArns", parent: name, max: 10) try validate(self.rulesPackageArns, name:"rulesPackageArns", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case locale = "locale" case rulesPackageArns = "rulesPackageArns" } } public struct DescribeRulesPackagesResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "failedItems", required: true, type: .map), AWSShapeMember(label: "rulesPackages", required: true, type: .list) ] /// Rules package details that cannot be described. An error code is provided for each failed item. public let failedItems: [String: FailedItemDetails] /// Information about the rules package. public let rulesPackages: [RulesPackage] public init(failedItems: [String: FailedItemDetails], rulesPackages: [RulesPackage]) { self.failedItems = failedItems self.rulesPackages = rulesPackages } private enum CodingKeys: String, CodingKey { case failedItems = "failedItems" case rulesPackages = "rulesPackages" } } public struct DurationRange: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "maxSeconds", required: false, type: .integer), AWSShapeMember(label: "minSeconds", required: false, type: .integer) ] /// The maximum value of the duration range. Must be less than or equal to 604800 seconds (1 week). public let maxSeconds: Int? /// The minimum value of the duration range. Must be greater than zero. public let minSeconds: Int? public init(maxSeconds: Int? = nil, minSeconds: Int? = nil) { self.maxSeconds = maxSeconds self.minSeconds = minSeconds } public func validate(name: String) throws { try validate(self.maxSeconds, name:"maxSeconds", parent: name, max: 86400) try validate(self.maxSeconds, name:"maxSeconds", parent: name, min: 180) try validate(self.minSeconds, name:"minSeconds", parent: name, max: 86400) try validate(self.minSeconds, name:"minSeconds", parent: name, min: 180) } private enum CodingKeys: String, CodingKey { case maxSeconds = "maxSeconds" case minSeconds = "minSeconds" } } public struct EventSubscription: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "event", required: true, type: .enum), AWSShapeMember(label: "subscribedAt", required: true, type: .timestamp) ] /// The event for which Amazon Simple Notification Service (SNS) notifications are sent. public let event: InspectorEvent /// The time at which SubscribeToEvent is called. public let subscribedAt: TimeStamp public init(event: InspectorEvent, subscribedAt: TimeStamp) { self.event = event self.subscribedAt = subscribedAt } private enum CodingKeys: String, CodingKey { case event = "event" case subscribedAt = "subscribedAt" } } public struct Exclusion: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "arn", required: true, type: .string), AWSShapeMember(label: "attributes", required: false, type: .list), AWSShapeMember(label: "description", required: true, type: .string), AWSShapeMember(label: "recommendation", required: true, type: .string), AWSShapeMember(label: "scopes", required: true, type: .list), AWSShapeMember(label: "title", required: true, type: .string) ] /// The ARN that specifies the exclusion. public let arn: String /// The system-defined attributes for the exclusion. public let attributes: [Attribute]? /// The description of the exclusion. public let description: String /// The recommendation for the exclusion. public let recommendation: String /// The AWS resources for which the exclusion pertains. public let scopes: [Scope] /// The name of the exclusion. public let title: String public init(arn: String, attributes: [Attribute]? = nil, description: String, recommendation: String, scopes: [Scope], title: String) { self.arn = arn self.attributes = attributes self.description = description self.recommendation = recommendation self.scopes = scopes self.title = title } private enum CodingKeys: String, CodingKey { case arn = "arn" case attributes = "attributes" case description = "description" case recommendation = "recommendation" case scopes = "scopes" case title = "title" } } public struct ExclusionPreview: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "attributes", required: false, type: .list), AWSShapeMember(label: "description", required: true, type: .string), AWSShapeMember(label: "recommendation", required: true, type: .string), AWSShapeMember(label: "scopes", required: true, type: .list), AWSShapeMember(label: "title", required: true, type: .string) ] /// The system-defined attributes for the exclusion preview. public let attributes: [Attribute]? /// The description of the exclusion preview. public let description: String /// The recommendation for the exclusion preview. public let recommendation: String /// The AWS resources for which the exclusion preview pertains. public let scopes: [Scope] /// The name of the exclusion preview. public let title: String public init(attributes: [Attribute]? = nil, description: String, recommendation: String, scopes: [Scope], title: String) { self.attributes = attributes self.description = description self.recommendation = recommendation self.scopes = scopes self.title = title } private enum CodingKeys: String, CodingKey { case attributes = "attributes" case description = "description" case recommendation = "recommendation" case scopes = "scopes" case title = "title" } } public struct FailedItemDetails: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "failureCode", required: true, type: .enum), AWSShapeMember(label: "retryable", required: true, type: .boolean) ] /// The status code of a failed item. public let failureCode: FailedItemErrorCode /// Indicates whether you can immediately retry a request for this item for a specified resource. public let retryable: Bool public init(failureCode: FailedItemErrorCode, retryable: Bool) { self.failureCode = failureCode self.retryable = retryable } private enum CodingKeys: String, CodingKey { case failureCode = "failureCode" case retryable = "retryable" } } public enum FailedItemErrorCode: String, CustomStringConvertible, Codable { case invalidArn = "INVALID_ARN" case duplicateArn = "DUPLICATE_ARN" case itemDoesNotExist = "ITEM_DOES_NOT_EXIST" case accessDenied = "ACCESS_DENIED" case limitExceeded = "LIMIT_EXCEEDED" case internalError = "INTERNAL_ERROR" public var description: String { return self.rawValue } } public struct Finding: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "arn", required: true, type: .string), AWSShapeMember(label: "assetAttributes", required: false, type: .structure), AWSShapeMember(label: "assetType", required: false, type: .enum), AWSShapeMember(label: "attributes", required: true, type: .list), AWSShapeMember(label: "confidence", required: false, type: .integer), AWSShapeMember(label: "createdAt", required: true, type: .timestamp), AWSShapeMember(label: "description", required: false, type: .string), AWSShapeMember(label: "id", required: false, type: .string), AWSShapeMember(label: "indicatorOfCompromise", required: false, type: .boolean), AWSShapeMember(label: "numericSeverity", required: false, type: .double), AWSShapeMember(label: "recommendation", required: false, type: .string), AWSShapeMember(label: "schemaVersion", required: false, type: .integer), AWSShapeMember(label: "service", required: false, type: .string), AWSShapeMember(label: "serviceAttributes", required: false, type: .structure), AWSShapeMember(label: "severity", required: false, type: .enum), AWSShapeMember(label: "title", required: false, type: .string), AWSShapeMember(label: "updatedAt", required: true, type: .timestamp), AWSShapeMember(label: "userAttributes", required: true, type: .list) ] /// The ARN that specifies the finding. public let arn: String /// A collection of attributes of the host from which the finding is generated. public let assetAttributes: AssetAttributes? /// The type of the host from which the finding is generated. public let assetType: AssetType? /// The system-defined attributes for the finding. public let attributes: [Attribute] /// This data element is currently not used. public let confidence: Int? /// The time when the finding was generated. public let createdAt: TimeStamp /// The description of the finding. public let description: String? /// The ID of the finding. public let id: String? /// This data element is currently not used. public let indicatorOfCompromise: Bool? /// The numeric value of the finding severity. public let numericSeverity: Double? /// The recommendation for the finding. public let recommendation: String? /// The schema version of this data type. public let schemaVersion: Int? /// The data element is set to "Inspector". public let service: String? /// This data type is used in the Finding data type. public let serviceAttributes: InspectorServiceAttributes? /// The finding severity. Values can be set to High, Medium, Low, and Informational. public let severity: Severity? /// The name of the finding. public let title: String? /// The time when AddAttributesToFindings is called. public let updatedAt: TimeStamp /// The user-defined attributes that are assigned to the finding. public let userAttributes: [Attribute] public init(arn: String, assetAttributes: AssetAttributes? = nil, assetType: AssetType? = nil, attributes: [Attribute], confidence: Int? = nil, createdAt: TimeStamp, description: String? = nil, id: String? = nil, indicatorOfCompromise: Bool? = nil, numericSeverity: Double? = nil, recommendation: String? = nil, schemaVersion: Int? = nil, service: String? = nil, serviceAttributes: InspectorServiceAttributes? = nil, severity: Severity? = nil, title: String? = nil, updatedAt: TimeStamp, userAttributes: [Attribute]) { self.arn = arn self.assetAttributes = assetAttributes self.assetType = assetType self.attributes = attributes self.confidence = confidence self.createdAt = createdAt self.description = description self.id = id self.indicatorOfCompromise = indicatorOfCompromise self.numericSeverity = numericSeverity self.recommendation = recommendation self.schemaVersion = schemaVersion self.service = service self.serviceAttributes = serviceAttributes self.severity = severity self.title = title self.updatedAt = updatedAt self.userAttributes = userAttributes } private enum CodingKeys: String, CodingKey { case arn = "arn" case assetAttributes = "assetAttributes" case assetType = "assetType" case attributes = "attributes" case confidence = "confidence" case createdAt = "createdAt" case description = "description" case id = "id" case indicatorOfCompromise = "indicatorOfCompromise" case numericSeverity = "numericSeverity" case recommendation = "recommendation" case schemaVersion = "schemaVersion" case service = "service" case serviceAttributes = "serviceAttributes" case severity = "severity" case title = "title" case updatedAt = "updatedAt" case userAttributes = "userAttributes" } } public struct FindingFilter: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "agentIds", required: false, type: .list), AWSShapeMember(label: "attributes", required: false, type: .list), AWSShapeMember(label: "autoScalingGroups", required: false, type: .list), AWSShapeMember(label: "creationTimeRange", required: false, type: .structure), AWSShapeMember(label: "ruleNames", required: false, type: .list), AWSShapeMember(label: "rulesPackageArns", required: false, type: .list), AWSShapeMember(label: "severities", required: false, type: .list), AWSShapeMember(label: "userAttributes", required: false, type: .list) ] /// For a record to match a filter, one of the values that is specified for this data type property must be the exact match of the value of the agentId property of the Finding data type. public let agentIds: [String]? /// For a record to match a filter, the list of values that are specified for this data type property must be contained in the list of values of the attributes property of the Finding data type. public let attributes: [Attribute]? /// For a record to match a filter, one of the values that is specified for this data type property must be the exact match of the value of the autoScalingGroup property of the Finding data type. public let autoScalingGroups: [String]? /// The time range during which the finding is generated. public let creationTimeRange: TimestampRange? /// For a record to match a filter, one of the values that is specified for this data type property must be the exact match of the value of the ruleName property of the Finding data type. public let ruleNames: [String]? /// For a record to match a filter, one of the values that is specified for this data type property must be the exact match of the value of the rulesPackageArn property of the Finding data type. public let rulesPackageArns: [String]? /// For a record to match a filter, one of the values that is specified for this data type property must be the exact match of the value of the severity property of the Finding data type. public let severities: [Severity]? /// For a record to match a filter, the value that is specified for this data type property must be contained in the list of values of the userAttributes property of the Finding data type. public let userAttributes: [Attribute]? public init(agentIds: [String]? = nil, attributes: [Attribute]? = nil, autoScalingGroups: [String]? = nil, creationTimeRange: TimestampRange? = nil, ruleNames: [String]? = nil, rulesPackageArns: [String]? = nil, severities: [Severity]? = nil, userAttributes: [Attribute]? = nil) { self.agentIds = agentIds self.attributes = attributes self.autoScalingGroups = autoScalingGroups self.creationTimeRange = creationTimeRange self.ruleNames = ruleNames self.rulesPackageArns = rulesPackageArns self.severities = severities self.userAttributes = userAttributes } public func validate(name: String) throws { try self.agentIds?.forEach { try validate($0, name: "agentIds[]", parent: name, max: 128) try validate($0, name: "agentIds[]", parent: name, min: 1) } try validate(self.agentIds, name:"agentIds", parent: name, max: 99) try validate(self.agentIds, name:"agentIds", parent: name, min: 0) try self.attributes?.forEach { try $0.validate(name: "\(name).attributes[]") } try validate(self.attributes, name:"attributes", parent: name, max: 50) try validate(self.attributes, name:"attributes", parent: name, min: 0) try self.autoScalingGroups?.forEach { try validate($0, name: "autoScalingGroups[]", parent: name, max: 256) try validate($0, name: "autoScalingGroups[]", parent: name, min: 1) } try validate(self.autoScalingGroups, name:"autoScalingGroups", parent: name, max: 20) try validate(self.autoScalingGroups, name:"autoScalingGroups", parent: name, min: 0) try self.ruleNames?.forEach { try validate($0, name: "ruleNames[]", parent: name, max: 1000) } try validate(self.ruleNames, name:"ruleNames", parent: name, max: 50) try validate(self.ruleNames, name:"ruleNames", parent: name, min: 0) try self.rulesPackageArns?.forEach { try validate($0, name: "rulesPackageArns[]", parent: name, max: 300) try validate($0, name: "rulesPackageArns[]", parent: name, min: 1) } try validate(self.rulesPackageArns, name:"rulesPackageArns", parent: name, max: 50) try validate(self.rulesPackageArns, name:"rulesPackageArns", parent: name, min: 0) try validate(self.severities, name:"severities", parent: name, max: 50) try validate(self.severities, name:"severities", parent: name, min: 0) try self.userAttributes?.forEach { try $0.validate(name: "\(name).userAttributes[]") } try validate(self.userAttributes, name:"userAttributes", parent: name, max: 50) try validate(self.userAttributes, name:"userAttributes", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case agentIds = "agentIds" case attributes = "attributes" case autoScalingGroups = "autoScalingGroups" case creationTimeRange = "creationTimeRange" case ruleNames = "ruleNames" case rulesPackageArns = "rulesPackageArns" case severities = "severities" case userAttributes = "userAttributes" } } public struct GetAssessmentReportRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentRunArn", required: true, type: .string), AWSShapeMember(label: "reportFileFormat", required: true, type: .enum), AWSShapeMember(label: "reportType", required: true, type: .enum) ] /// The ARN that specifies the assessment run for which you want to generate a report. public let assessmentRunArn: String /// Specifies the file format (html or pdf) of the assessment report that you want to generate. public let reportFileFormat: ReportFileFormat /// Specifies the type of the assessment report that you want to generate. There are two types of assessment reports: a finding report and a full report. For more information, see Assessment Reports. public let reportType: ReportType public init(assessmentRunArn: String, reportFileFormat: ReportFileFormat, reportType: ReportType) { self.assessmentRunArn = assessmentRunArn self.reportFileFormat = reportFileFormat self.reportType = reportType } public func validate(name: String) throws { try validate(self.assessmentRunArn, name:"assessmentRunArn", parent: name, max: 300) try validate(self.assessmentRunArn, name:"assessmentRunArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentRunArn = "assessmentRunArn" case reportFileFormat = "reportFileFormat" case reportType = "reportType" } } public struct GetAssessmentReportResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "status", required: true, type: .enum), AWSShapeMember(label: "url", required: false, type: .string) ] /// Specifies the status of the request to generate an assessment report. public let status: ReportStatus /// Specifies the URL where you can find the generated assessment report. This parameter is only returned if the report is successfully generated. public let url: String? public init(status: ReportStatus, url: String? = nil) { self.status = status self.url = url } private enum CodingKeys: String, CodingKey { case status = "status" case url = "url" } } public struct GetExclusionsPreviewRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTemplateArn", required: true, type: .string), AWSShapeMember(label: "locale", required: false, type: .enum), AWSShapeMember(label: "maxResults", required: false, type: .integer), AWSShapeMember(label: "nextToken", required: false, type: .string), AWSShapeMember(label: "previewToken", required: true, type: .string) ] /// The ARN that specifies the assessment template for which the exclusions preview was requested. public let assessmentTemplateArn: String /// The locale into which you want to translate the exclusion's title, description, and recommendation. public let locale: Locale? /// You can use this parameter to indicate the maximum number of items you want in the response. The default value is 100. The maximum value is 500. public let maxResults: Int? /// You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the GetExclusionsPreviewRequest action. Subsequent calls to the action fill nextToken in the request with the value of nextToken from the previous response to continue listing data. public let nextToken: String? /// The unique identifier associated of the exclusions preview. public let previewToken: String public init(assessmentTemplateArn: String, locale: Locale? = nil, maxResults: Int? = nil, nextToken: String? = nil, previewToken: String) { self.assessmentTemplateArn = assessmentTemplateArn self.locale = locale self.maxResults = maxResults self.nextToken = nextToken self.previewToken = previewToken } public func validate(name: String) throws { try validate(self.assessmentTemplateArn, name:"assessmentTemplateArn", parent: name, max: 300) try validate(self.assessmentTemplateArn, name:"assessmentTemplateArn", parent: name, min: 1) try validate(self.nextToken, name:"nextToken", parent: name, max: 300) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) try validate(self.previewToken, name:"previewToken", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") } private enum CodingKeys: String, CodingKey { case assessmentTemplateArn = "assessmentTemplateArn" case locale = "locale" case maxResults = "maxResults" case nextToken = "nextToken" case previewToken = "previewToken" } } public struct GetExclusionsPreviewResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "exclusionPreviews", required: false, type: .list), AWSShapeMember(label: "nextToken", required: false, type: .string), AWSShapeMember(label: "previewStatus", required: true, type: .enum) ] /// Information about the exclusions included in the preview. public let exclusionPreviews: [ExclusionPreview]? /// When a response is generated, if there is more data to be listed, this parameters is present in the response and contains the value to use for the nextToken parameter in a subsequent pagination request. If there is no more data to be listed, this parameter is set to null. public let nextToken: String? /// Specifies the status of the request to generate an exclusions preview. public let previewStatus: PreviewStatus public init(exclusionPreviews: [ExclusionPreview]? = nil, nextToken: String? = nil, previewStatus: PreviewStatus) { self.exclusionPreviews = exclusionPreviews self.nextToken = nextToken self.previewStatus = previewStatus } private enum CodingKeys: String, CodingKey { case exclusionPreviews = "exclusionPreviews" case nextToken = "nextToken" case previewStatus = "previewStatus" } } public struct GetTelemetryMetadataRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentRunArn", required: true, type: .string) ] /// The ARN that specifies the assessment run that has the telemetry data that you want to obtain. public let assessmentRunArn: String public init(assessmentRunArn: String) { self.assessmentRunArn = assessmentRunArn } public func validate(name: String) throws { try validate(self.assessmentRunArn, name:"assessmentRunArn", parent: name, max: 300) try validate(self.assessmentRunArn, name:"assessmentRunArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentRunArn = "assessmentRunArn" } } public struct GetTelemetryMetadataResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "telemetryMetadata", required: true, type: .list) ] /// Telemetry details. public let telemetryMetadata: [TelemetryMetadata] public init(telemetryMetadata: [TelemetryMetadata]) { self.telemetryMetadata = telemetryMetadata } private enum CodingKeys: String, CodingKey { case telemetryMetadata = "telemetryMetadata" } } public enum InspectorEvent: String, CustomStringConvertible, Codable { case assessmentRunStarted = "ASSESSMENT_RUN_STARTED" case assessmentRunCompleted = "ASSESSMENT_RUN_COMPLETED" case assessmentRunStateChanged = "ASSESSMENT_RUN_STATE_CHANGED" case findingReported = "FINDING_REPORTED" case other = "OTHER" public var description: String { return self.rawValue } } public struct InspectorServiceAttributes: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentRunArn", required: false, type: .string), AWSShapeMember(label: "rulesPackageArn", required: false, type: .string), AWSShapeMember(label: "schemaVersion", required: true, type: .integer) ] /// The ARN of the assessment run during which the finding is generated. public let assessmentRunArn: String? /// The ARN of the rules package that is used to generate the finding. public let rulesPackageArn: String? /// The schema version of this data type. public let schemaVersion: Int public init(assessmentRunArn: String? = nil, rulesPackageArn: String? = nil, schemaVersion: Int) { self.assessmentRunArn = assessmentRunArn self.rulesPackageArn = rulesPackageArn self.schemaVersion = schemaVersion } private enum CodingKeys: String, CodingKey { case assessmentRunArn = "assessmentRunArn" case rulesPackageArn = "rulesPackageArn" case schemaVersion = "schemaVersion" } } public struct ListAssessmentRunAgentsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentRunArn", required: true, type: .string), AWSShapeMember(label: "filter", required: false, type: .structure), AWSShapeMember(label: "maxResults", required: false, type: .integer), AWSShapeMember(label: "nextToken", required: false, type: .string) ] /// The ARN that specifies the assessment run whose agents you want to list. public let assessmentRunArn: String /// You can use this parameter to specify a subset of data to be included in the action's response. For a record to match a filter, all specified filter attributes must match. When multiple values are specified for a filter attribute, any of the values can match. public let filter: AgentFilter? /// You can use this parameter to indicate the maximum number of items that you want in the response. The default value is 10. The maximum value is 500. public let maxResults: Int? /// You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the ListAssessmentRunAgents action. Subsequent calls to the action fill nextToken in the request with the value of NextToken from the previous response to continue listing data. public let nextToken: String? public init(assessmentRunArn: String, filter: AgentFilter? = nil, maxResults: Int? = nil, nextToken: String? = nil) { self.assessmentRunArn = assessmentRunArn self.filter = filter self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try validate(self.assessmentRunArn, name:"assessmentRunArn", parent: name, max: 300) try validate(self.assessmentRunArn, name:"assessmentRunArn", parent: name, min: 1) try self.filter?.validate(name: "\(name).filter") try validate(self.nextToken, name:"nextToken", parent: name, max: 300) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentRunArn = "assessmentRunArn" case filter = "filter" case maxResults = "maxResults" case nextToken = "nextToken" } } public struct ListAssessmentRunAgentsResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentRunAgents", required: true, type: .list), AWSShapeMember(label: "nextToken", required: false, type: .string) ] /// A list of ARNs that specifies the agents returned by the action. public let assessmentRunAgents: [AssessmentRunAgent] /// When a response is generated, if there is more data to be listed, this parameter is present in the response and contains the value to use for the nextToken parameter in a subsequent pagination request. If there is no more data to be listed, this parameter is set to null. public let nextToken: String? public init(assessmentRunAgents: [AssessmentRunAgent], nextToken: String? = nil) { self.assessmentRunAgents = assessmentRunAgents self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case assessmentRunAgents = "assessmentRunAgents" case nextToken = "nextToken" } } public struct ListAssessmentRunsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTemplateArns", required: false, type: .list), AWSShapeMember(label: "filter", required: false, type: .structure), AWSShapeMember(label: "maxResults", required: false, type: .integer), AWSShapeMember(label: "nextToken", required: false, type: .string) ] /// The ARNs that specify the assessment templates whose assessment runs you want to list. public let assessmentTemplateArns: [String]? /// You can use this parameter to specify a subset of data to be included in the action's response. For a record to match a filter, all specified filter attributes must match. When multiple values are specified for a filter attribute, any of the values can match. public let filter: AssessmentRunFilter? /// You can use this parameter to indicate the maximum number of items that you want in the response. The default value is 10. The maximum value is 500. public let maxResults: Int? /// You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the ListAssessmentRuns action. Subsequent calls to the action fill nextToken in the request with the value of NextToken from the previous response to continue listing data. public let nextToken: String? public init(assessmentTemplateArns: [String]? = nil, filter: AssessmentRunFilter? = nil, maxResults: Int? = nil, nextToken: String? = nil) { self.assessmentTemplateArns = assessmentTemplateArns self.filter = filter self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.assessmentTemplateArns?.forEach { try validate($0, name: "assessmentTemplateArns[]", parent: name, max: 300) try validate($0, name: "assessmentTemplateArns[]", parent: name, min: 1) } try validate(self.assessmentTemplateArns, name:"assessmentTemplateArns", parent: name, max: 50) try validate(self.assessmentTemplateArns, name:"assessmentTemplateArns", parent: name, min: 0) try self.filter?.validate(name: "\(name).filter") try validate(self.nextToken, name:"nextToken", parent: name, max: 300) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentTemplateArns = "assessmentTemplateArns" case filter = "filter" case maxResults = "maxResults" case nextToken = "nextToken" } } public struct ListAssessmentRunsResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentRunArns", required: true, type: .list), AWSShapeMember(label: "nextToken", required: false, type: .string) ] /// A list of ARNs that specifies the assessment runs that are returned by the action. public let assessmentRunArns: [String] /// When a response is generated, if there is more data to be listed, this parameter is present in the response and contains the value to use for the nextToken parameter in a subsequent pagination request. If there is no more data to be listed, this parameter is set to null. public let nextToken: String? public init(assessmentRunArns: [String], nextToken: String? = nil) { self.assessmentRunArns = assessmentRunArns self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case assessmentRunArns = "assessmentRunArns" case nextToken = "nextToken" } } public struct ListAssessmentTargetsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "filter", required: false, type: .structure), AWSShapeMember(label: "maxResults", required: false, type: .integer), AWSShapeMember(label: "nextToken", required: false, type: .string) ] /// You can use this parameter to specify a subset of data to be included in the action's response. For a record to match a filter, all specified filter attributes must match. When multiple values are specified for a filter attribute, any of the values can match. public let filter: AssessmentTargetFilter? /// You can use this parameter to indicate the maximum number of items you want in the response. The default value is 10. The maximum value is 500. public let maxResults: Int? /// You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the ListAssessmentTargets action. Subsequent calls to the action fill nextToken in the request with the value of NextToken from the previous response to continue listing data. public let nextToken: String? public init(filter: AssessmentTargetFilter? = nil, maxResults: Int? = nil, nextToken: String? = nil) { self.filter = filter self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.filter?.validate(name: "\(name).filter") try validate(self.nextToken, name:"nextToken", parent: name, max: 300) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case filter = "filter" case maxResults = "maxResults" case nextToken = "nextToken" } } public struct ListAssessmentTargetsResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTargetArns", required: true, type: .list), AWSShapeMember(label: "nextToken", required: false, type: .string) ] /// A list of ARNs that specifies the assessment targets that are returned by the action. public let assessmentTargetArns: [String] /// When a response is generated, if there is more data to be listed, this parameter is present in the response and contains the value to use for the nextToken parameter in a subsequent pagination request. If there is no more data to be listed, this parameter is set to null. public let nextToken: String? public init(assessmentTargetArns: [String], nextToken: String? = nil) { self.assessmentTargetArns = assessmentTargetArns self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case assessmentTargetArns = "assessmentTargetArns" case nextToken = "nextToken" } } public struct ListAssessmentTemplatesRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTargetArns", required: false, type: .list), AWSShapeMember(label: "filter", required: false, type: .structure), AWSShapeMember(label: "maxResults", required: false, type: .integer), AWSShapeMember(label: "nextToken", required: false, type: .string) ] /// A list of ARNs that specifies the assessment targets whose assessment templates you want to list. public let assessmentTargetArns: [String]? /// You can use this parameter to specify a subset of data to be included in the action's response. For a record to match a filter, all specified filter attributes must match. When multiple values are specified for a filter attribute, any of the values can match. public let filter: AssessmentTemplateFilter? /// You can use this parameter to indicate the maximum number of items you want in the response. The default value is 10. The maximum value is 500. public let maxResults: Int? /// You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the ListAssessmentTemplates action. Subsequent calls to the action fill nextToken in the request with the value of NextToken from the previous response to continue listing data. public let nextToken: String? public init(assessmentTargetArns: [String]? = nil, filter: AssessmentTemplateFilter? = nil, maxResults: Int? = nil, nextToken: String? = nil) { self.assessmentTargetArns = assessmentTargetArns self.filter = filter self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.assessmentTargetArns?.forEach { try validate($0, name: "assessmentTargetArns[]", parent: name, max: 300) try validate($0, name: "assessmentTargetArns[]", parent: name, min: 1) } try validate(self.assessmentTargetArns, name:"assessmentTargetArns", parent: name, max: 50) try validate(self.assessmentTargetArns, name:"assessmentTargetArns", parent: name, min: 0) try self.filter?.validate(name: "\(name).filter") try validate(self.nextToken, name:"nextToken", parent: name, max: 300) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentTargetArns = "assessmentTargetArns" case filter = "filter" case maxResults = "maxResults" case nextToken = "nextToken" } } public struct ListAssessmentTemplatesResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTemplateArns", required: true, type: .list), AWSShapeMember(label: "nextToken", required: false, type: .string) ] /// A list of ARNs that specifies the assessment templates returned by the action. public let assessmentTemplateArns: [String] /// When a response is generated, if there is more data to be listed, this parameter is present in the response and contains the value to use for the nextToken parameter in a subsequent pagination request. If there is no more data to be listed, this parameter is set to null. public let nextToken: String? public init(assessmentTemplateArns: [String], nextToken: String? = nil) { self.assessmentTemplateArns = assessmentTemplateArns self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case assessmentTemplateArns = "assessmentTemplateArns" case nextToken = "nextToken" } } public struct ListEventSubscriptionsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "maxResults", required: false, type: .integer), AWSShapeMember(label: "nextToken", required: false, type: .string), AWSShapeMember(label: "resourceArn", required: false, type: .string) ] /// You can use this parameter to indicate the maximum number of items you want in the response. The default value is 10. The maximum value is 500. public let maxResults: Int? /// You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the ListEventSubscriptions action. Subsequent calls to the action fill nextToken in the request with the value of NextToken from the previous response to continue listing data. public let nextToken: String? /// The ARN of the assessment template for which you want to list the existing event subscriptions. public let resourceArn: String? public init(maxResults: Int? = nil, nextToken: String? = nil, resourceArn: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken self.resourceArn = resourceArn } public func validate(name: String) throws { try validate(self.nextToken, name:"nextToken", parent: name, max: 300) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) try validate(self.resourceArn, name:"resourceArn", parent: name, max: 300) try validate(self.resourceArn, name:"resourceArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case maxResults = "maxResults" case nextToken = "nextToken" case resourceArn = "resourceArn" } } public struct ListEventSubscriptionsResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "nextToken", required: false, type: .string), AWSShapeMember(label: "subscriptions", required: true, type: .list) ] /// When a response is generated, if there is more data to be listed, this parameter is present in the response and contains the value to use for the nextToken parameter in a subsequent pagination request. If there is no more data to be listed, this parameter is set to null. public let nextToken: String? /// Details of the returned event subscriptions. public let subscriptions: [Subscription] public init(nextToken: String? = nil, subscriptions: [Subscription]) { self.nextToken = nextToken self.subscriptions = subscriptions } private enum CodingKeys: String, CodingKey { case nextToken = "nextToken" case subscriptions = "subscriptions" } } public struct ListExclusionsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentRunArn", required: true, type: .string), AWSShapeMember(label: "maxResults", required: false, type: .integer), AWSShapeMember(label: "nextToken", required: false, type: .string) ] /// The ARN of the assessment run that generated the exclusions that you want to list. public let assessmentRunArn: String /// You can use this parameter to indicate the maximum number of items you want in the response. The default value is 100. The maximum value is 500. public let maxResults: Int? /// You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the ListExclusionsRequest action. Subsequent calls to the action fill nextToken in the request with the value of nextToken from the previous response to continue listing data. public let nextToken: String? public init(assessmentRunArn: String, maxResults: Int? = nil, nextToken: String? = nil) { self.assessmentRunArn = assessmentRunArn self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try validate(self.assessmentRunArn, name:"assessmentRunArn", parent: name, max: 300) try validate(self.assessmentRunArn, name:"assessmentRunArn", parent: name, min: 1) try validate(self.nextToken, name:"nextToken", parent: name, max: 300) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentRunArn = "assessmentRunArn" case maxResults = "maxResults" case nextToken = "nextToken" } } public struct ListExclusionsResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "exclusionArns", required: true, type: .list), AWSShapeMember(label: "nextToken", required: false, type: .string) ] /// A list of exclusions' ARNs returned by the action. public let exclusionArns: [String] /// When a response is generated, if there is more data to be listed, this parameters is present in the response and contains the value to use for the nextToken parameter in a subsequent pagination request. If there is no more data to be listed, this parameter is set to null. public let nextToken: String? public init(exclusionArns: [String], nextToken: String? = nil) { self.exclusionArns = exclusionArns self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case exclusionArns = "exclusionArns" case nextToken = "nextToken" } } public struct ListFindingsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentRunArns", required: false, type: .list), AWSShapeMember(label: "filter", required: false, type: .structure), AWSShapeMember(label: "maxResults", required: false, type: .integer), AWSShapeMember(label: "nextToken", required: false, type: .string) ] /// The ARNs of the assessment runs that generate the findings that you want to list. public let assessmentRunArns: [String]? /// You can use this parameter to specify a subset of data to be included in the action's response. For a record to match a filter, all specified filter attributes must match. When multiple values are specified for a filter attribute, any of the values can match. public let filter: FindingFilter? /// You can use this parameter to indicate the maximum number of items you want in the response. The default value is 10. The maximum value is 500. public let maxResults: Int? /// You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the ListFindings action. Subsequent calls to the action fill nextToken in the request with the value of NextToken from the previous response to continue listing data. public let nextToken: String? public init(assessmentRunArns: [String]? = nil, filter: FindingFilter? = nil, maxResults: Int? = nil, nextToken: String? = nil) { self.assessmentRunArns = assessmentRunArns self.filter = filter self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.assessmentRunArns?.forEach { try validate($0, name: "assessmentRunArns[]", parent: name, max: 300) try validate($0, name: "assessmentRunArns[]", parent: name, min: 1) } try validate(self.assessmentRunArns, name:"assessmentRunArns", parent: name, max: 50) try validate(self.assessmentRunArns, name:"assessmentRunArns", parent: name, min: 0) try self.filter?.validate(name: "\(name).filter") try validate(self.nextToken, name:"nextToken", parent: name, max: 300) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentRunArns = "assessmentRunArns" case filter = "filter" case maxResults = "maxResults" case nextToken = "nextToken" } } public struct ListFindingsResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "findingArns", required: true, type: .list), AWSShapeMember(label: "nextToken", required: false, type: .string) ] /// A list of ARNs that specifies the findings returned by the action. public let findingArns: [String] /// When a response is generated, if there is more data to be listed, this parameter is present in the response and contains the value to use for the nextToken parameter in a subsequent pagination request. If there is no more data to be listed, this parameter is set to null. public let nextToken: String? public init(findingArns: [String], nextToken: String? = nil) { self.findingArns = findingArns self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case findingArns = "findingArns" case nextToken = "nextToken" } } public struct ListRulesPackagesRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "maxResults", required: false, type: .integer), AWSShapeMember(label: "nextToken", required: false, type: .string) ] /// You can use this parameter to indicate the maximum number of items you want in the response. The default value is 10. The maximum value is 500. public let maxResults: Int? /// You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the ListRulesPackages action. Subsequent calls to the action fill nextToken in the request with the value of NextToken from the previous response to continue listing data. public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try validate(self.nextToken, name:"nextToken", parent: name, max: 300) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case maxResults = "maxResults" case nextToken = "nextToken" } } public struct ListRulesPackagesResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "nextToken", required: false, type: .string), AWSShapeMember(label: "rulesPackageArns", required: true, type: .list) ] /// When a response is generated, if there is more data to be listed, this parameter is present in the response and contains the value to use for the nextToken parameter in a subsequent pagination request. If there is no more data to be listed, this parameter is set to null. public let nextToken: String? /// The list of ARNs that specifies the rules packages returned by the action. public let rulesPackageArns: [String] public init(nextToken: String? = nil, rulesPackageArns: [String]) { self.nextToken = nextToken self.rulesPackageArns = rulesPackageArns } private enum CodingKeys: String, CodingKey { case nextToken = "nextToken" case rulesPackageArns = "rulesPackageArns" } } public struct ListTagsForResourceRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "resourceArn", required: true, type: .string) ] /// The ARN that specifies the assessment template whose tags you want to list. public let resourceArn: String public init(resourceArn: String) { self.resourceArn = resourceArn } public func validate(name: String) throws { try validate(self.resourceArn, name:"resourceArn", parent: name, max: 300) try validate(self.resourceArn, name:"resourceArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case resourceArn = "resourceArn" } } public struct ListTagsForResourceResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "tags", required: true, type: .list) ] /// A collection of key and value pairs. public let tags: [Tag] public init(tags: [Tag]) { self.tags = tags } private enum CodingKeys: String, CodingKey { case tags = "tags" } } public enum Locale: String, CustomStringConvertible, Codable { case enUs = "EN_US" public var description: String { return self.rawValue } } public struct NetworkInterface: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ipv6Addresses", required: false, type: .list), AWSShapeMember(label: "networkInterfaceId", required: false, type: .string), AWSShapeMember(label: "privateDnsName", required: false, type: .string), AWSShapeMember(label: "privateIpAddress", required: false, type: .string), AWSShapeMember(label: "privateIpAddresses", required: false, type: .list), AWSShapeMember(label: "publicDnsName", required: false, type: .string), AWSShapeMember(label: "publicIp", required: false, type: .string), AWSShapeMember(label: "securityGroups", required: false, type: .list), AWSShapeMember(label: "subnetId", required: false, type: .string), AWSShapeMember(label: "vpcId", required: false, type: .string) ] /// The IP addresses associated with the network interface. public let ipv6Addresses: [String]? /// The ID of the network interface. public let networkInterfaceId: String? /// The name of a private DNS associated with the network interface. public let privateDnsName: String? /// The private IP address associated with the network interface. public let privateIpAddress: String? /// A list of the private IP addresses associated with the network interface. Includes the privateDnsName and privateIpAddress. public let privateIpAddresses: [PrivateIp]? /// The name of a public DNS associated with the network interface. public let publicDnsName: String? /// The public IP address from which the network interface is reachable. public let publicIp: String? /// A list of the security groups associated with the network interface. Includes the groupId and groupName. public let securityGroups: [SecurityGroup]? /// The ID of a subnet associated with the network interface. public let subnetId: String? /// The ID of a VPC associated with the network interface. public let vpcId: String? public init(ipv6Addresses: [String]? = nil, networkInterfaceId: String? = nil, privateDnsName: String? = nil, privateIpAddress: String? = nil, privateIpAddresses: [PrivateIp]? = nil, publicDnsName: String? = nil, publicIp: String? = nil, securityGroups: [SecurityGroup]? = nil, subnetId: String? = nil, vpcId: String? = nil) { self.ipv6Addresses = ipv6Addresses self.networkInterfaceId = networkInterfaceId self.privateDnsName = privateDnsName self.privateIpAddress = privateIpAddress self.privateIpAddresses = privateIpAddresses self.publicDnsName = publicDnsName self.publicIp = publicIp self.securityGroups = securityGroups self.subnetId = subnetId self.vpcId = vpcId } private enum CodingKeys: String, CodingKey { case ipv6Addresses = "ipv6Addresses" case networkInterfaceId = "networkInterfaceId" case privateDnsName = "privateDnsName" case privateIpAddress = "privateIpAddress" case privateIpAddresses = "privateIpAddresses" case publicDnsName = "publicDnsName" case publicIp = "publicIp" case securityGroups = "securityGroups" case subnetId = "subnetId" case vpcId = "vpcId" } } public struct PreviewAgentsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "maxResults", required: false, type: .integer), AWSShapeMember(label: "nextToken", required: false, type: .string), AWSShapeMember(label: "previewAgentsArn", required: true, type: .string) ] /// You can use this parameter to indicate the maximum number of items you want in the response. The default value is 10. The maximum value is 500. public let maxResults: Int? /// You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the PreviewAgents action. Subsequent calls to the action fill nextToken in the request with the value of NextToken from the previous response to continue listing data. public let nextToken: String? /// The ARN of the assessment target whose agents you want to preview. public let previewAgentsArn: String public init(maxResults: Int? = nil, nextToken: String? = nil, previewAgentsArn: String) { self.maxResults = maxResults self.nextToken = nextToken self.previewAgentsArn = previewAgentsArn } public func validate(name: String) throws { try validate(self.nextToken, name:"nextToken", parent: name, max: 300) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) try validate(self.previewAgentsArn, name:"previewAgentsArn", parent: name, max: 300) try validate(self.previewAgentsArn, name:"previewAgentsArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case maxResults = "maxResults" case nextToken = "nextToken" case previewAgentsArn = "previewAgentsArn" } } public struct PreviewAgentsResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "agentPreviews", required: true, type: .list), AWSShapeMember(label: "nextToken", required: false, type: .string) ] /// The resulting list of agents. public let agentPreviews: [AgentPreview] /// When a response is generated, if there is more data to be listed, this parameter is present in the response and contains the value to use for the nextToken parameter in a subsequent pagination request. If there is no more data to be listed, this parameter is set to null. public let nextToken: String? public init(agentPreviews: [AgentPreview], nextToken: String? = nil) { self.agentPreviews = agentPreviews self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case agentPreviews = "agentPreviews" case nextToken = "nextToken" } } public enum PreviewStatus: String, CustomStringConvertible, Codable { case workInProgress = "WORK_IN_PROGRESS" case completed = "COMPLETED" public var description: String { return self.rawValue } } public struct PrivateIp: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "privateDnsName", required: false, type: .string), AWSShapeMember(label: "privateIpAddress", required: false, type: .string) ] /// The DNS name of the private IP address. public let privateDnsName: String? /// The full IP address of the network inteface. public let privateIpAddress: String? public init(privateDnsName: String? = nil, privateIpAddress: String? = nil) { self.privateDnsName = privateDnsName self.privateIpAddress = privateIpAddress } private enum CodingKeys: String, CodingKey { case privateDnsName = "privateDnsName" case privateIpAddress = "privateIpAddress" } } public struct RegisterCrossAccountAccessRoleRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "roleArn", required: true, type: .string) ] /// The ARN of the IAM role that grants Amazon Inspector access to AWS Services needed to perform security assessments. public let roleArn: String public init(roleArn: String) { self.roleArn = roleArn } public func validate(name: String) throws { try validate(self.roleArn, name:"roleArn", parent: name, max: 300) try validate(self.roleArn, name:"roleArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case roleArn = "roleArn" } } public struct RemoveAttributesFromFindingsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "attributeKeys", required: true, type: .list), AWSShapeMember(label: "findingArns", required: true, type: .list) ] /// The array of attribute keys that you want to remove from specified findings. public let attributeKeys: [String] /// The ARNs that specify the findings that you want to remove attributes from. public let findingArns: [String] public init(attributeKeys: [String], findingArns: [String]) { self.attributeKeys = attributeKeys self.findingArns = findingArns } public func validate(name: String) throws { try self.attributeKeys.forEach { try validate($0, name: "attributeKeys[]", parent: name, max: 128) try validate($0, name: "attributeKeys[]", parent: name, min: 1) } try validate(self.attributeKeys, name:"attributeKeys", parent: name, max: 10) try validate(self.attributeKeys, name:"attributeKeys", parent: name, min: 0) try self.findingArns.forEach { try validate($0, name: "findingArns[]", parent: name, max: 300) try validate($0, name: "findingArns[]", parent: name, min: 1) } try validate(self.findingArns, name:"findingArns", parent: name, max: 10) try validate(self.findingArns, name:"findingArns", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case attributeKeys = "attributeKeys" case findingArns = "findingArns" } } public struct RemoveAttributesFromFindingsResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "failedItems", required: true, type: .map) ] /// Attributes details that cannot be described. An error code is provided for each failed item. public let failedItems: [String: FailedItemDetails] public init(failedItems: [String: FailedItemDetails]) { self.failedItems = failedItems } private enum CodingKeys: String, CodingKey { case failedItems = "failedItems" } } public enum ReportFileFormat: String, CustomStringConvertible, Codable { case html = "HTML" case pdf = "PDF" public var description: String { return self.rawValue } } public enum ReportStatus: String, CustomStringConvertible, Codable { case workInProgress = "WORK_IN_PROGRESS" case failed = "FAILED" case completed = "COMPLETED" public var description: String { return self.rawValue } } public enum ReportType: String, CustomStringConvertible, Codable { case finding = "FINDING" case full = "FULL" public var description: String { return self.rawValue } } public struct ResourceGroup: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "arn", required: true, type: .string), AWSShapeMember(label: "createdAt", required: true, type: .timestamp), AWSShapeMember(label: "tags", required: true, type: .list) ] /// The ARN of the resource group. public let arn: String /// The time at which resource group is created. public let createdAt: TimeStamp /// The tags (key and value pairs) of the resource group. This data type property is used in the CreateResourceGroup action. public let tags: [ResourceGroupTag] public init(arn: String, createdAt: TimeStamp, tags: [ResourceGroupTag]) { self.arn = arn self.createdAt = createdAt self.tags = tags } private enum CodingKeys: String, CodingKey { case arn = "arn" case createdAt = "createdAt" case tags = "tags" } } public struct ResourceGroupTag: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "key", required: true, type: .string), AWSShapeMember(label: "value", required: false, type: .string) ] /// A tag key. public let key: String /// The value assigned to a tag key. public let value: String? public init(key: String, value: String? = nil) { self.key = key self.value = value } public func validate(name: String) throws { try validate(self.key, name:"key", parent: name, max: 128) try validate(self.key, name:"key", parent: name, min: 1) try validate(self.value, name:"value", parent: name, max: 256) try validate(self.value, name:"value", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case key = "key" case value = "value" } } public struct RulesPackage: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "arn", required: true, type: .string), AWSShapeMember(label: "description", required: false, type: .string), AWSShapeMember(label: "name", required: true, type: .string), AWSShapeMember(label: "provider", required: true, type: .string), AWSShapeMember(label: "version", required: true, type: .string) ] /// The ARN of the rules package. public let arn: String /// The description of the rules package. public let description: String? /// The name of the rules package. public let name: String /// The provider of the rules package. public let provider: String /// The version ID of the rules package. public let version: String public init(arn: String, description: String? = nil, name: String, provider: String, version: String) { self.arn = arn self.description = description self.name = name self.provider = provider self.version = version } private enum CodingKeys: String, CodingKey { case arn = "arn" case description = "description" case name = "name" case provider = "provider" case version = "version" } } public struct Scope: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "key", required: false, type: .enum), AWSShapeMember(label: "value", required: false, type: .string) ] /// The type of the scope. public let key: ScopeType? /// The resource identifier for the specified scope type. public let value: String? public init(key: ScopeType? = nil, value: String? = nil) { self.key = key self.value = value } private enum CodingKeys: String, CodingKey { case key = "key" case value = "value" } } public enum ScopeType: String, CustomStringConvertible, Codable { case instanceId = "INSTANCE_ID" case rulesPackageArn = "RULES_PACKAGE_ARN" public var description: String { return self.rawValue } } public struct SecurityGroup: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "groupId", required: false, type: .string), AWSShapeMember(label: "groupName", required: false, type: .string) ] /// The ID of the security group. public let groupId: String? /// The name of the security group. public let groupName: String? public init(groupId: String? = nil, groupName: String? = nil) { self.groupId = groupId self.groupName = groupName } private enum CodingKeys: String, CodingKey { case groupId = "groupId" case groupName = "groupName" } } public struct SetTagsForResourceRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "resourceArn", required: true, type: .string), AWSShapeMember(label: "tags", required: false, type: .list) ] /// The ARN of the assessment template that you want to set tags to. public let resourceArn: String /// A collection of key and value pairs that you want to set to the assessment template. public let tags: [Tag]? public init(resourceArn: String, tags: [Tag]? = nil) { self.resourceArn = resourceArn self.tags = tags } public func validate(name: String) throws { try validate(self.resourceArn, name:"resourceArn", parent: name, max: 300) try validate(self.resourceArn, name:"resourceArn", parent: name, min: 1) try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try validate(self.tags, name:"tags", parent: name, max: 10) try validate(self.tags, name:"tags", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case resourceArn = "resourceArn" case tags = "tags" } } public enum Severity: String, CustomStringConvertible, Codable { case low = "Low" case medium = "Medium" case high = "High" case informational = "Informational" case undefined = "Undefined" public var description: String { return self.rawValue } } public struct StartAssessmentRunRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentRunName", required: false, type: .string), AWSShapeMember(label: "assessmentTemplateArn", required: true, type: .string) ] /// You can specify the name for the assessment run. The name must be unique for the assessment template whose ARN is used to start the assessment run. public let assessmentRunName: String? /// The ARN of the assessment template of the assessment run that you want to start. public let assessmentTemplateArn: String public init(assessmentRunName: String? = nil, assessmentTemplateArn: String) { self.assessmentRunName = assessmentRunName self.assessmentTemplateArn = assessmentTemplateArn } public func validate(name: String) throws { try validate(self.assessmentRunName, name:"assessmentRunName", parent: name, max: 140) try validate(self.assessmentRunName, name:"assessmentRunName", parent: name, min: 1) try validate(self.assessmentTemplateArn, name:"assessmentTemplateArn", parent: name, max: 300) try validate(self.assessmentTemplateArn, name:"assessmentTemplateArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentRunName = "assessmentRunName" case assessmentTemplateArn = "assessmentTemplateArn" } } public struct StartAssessmentRunResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentRunArn", required: true, type: .string) ] /// The ARN of the assessment run that has been started. public let assessmentRunArn: String public init(assessmentRunArn: String) { self.assessmentRunArn = assessmentRunArn } private enum CodingKeys: String, CodingKey { case assessmentRunArn = "assessmentRunArn" } } public enum StopAction: String, CustomStringConvertible, Codable { case startEvaluation = "START_EVALUATION" case skipEvaluation = "SKIP_EVALUATION" public var description: String { return self.rawValue } } public struct StopAssessmentRunRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentRunArn", required: true, type: .string), AWSShapeMember(label: "stopAction", required: false, type: .enum) ] /// The ARN of the assessment run that you want to stop. public let assessmentRunArn: String /// An input option that can be set to either START_EVALUATION or SKIP_EVALUATION. START_EVALUATION (the default value), stops the AWS agent from collecting data and begins the results evaluation and the findings generation process. SKIP_EVALUATION cancels the assessment run immediately, after which no findings are generated. public let stopAction: StopAction? public init(assessmentRunArn: String, stopAction: StopAction? = nil) { self.assessmentRunArn = assessmentRunArn self.stopAction = stopAction } public func validate(name: String) throws { try validate(self.assessmentRunArn, name:"assessmentRunArn", parent: name, max: 300) try validate(self.assessmentRunArn, name:"assessmentRunArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentRunArn = "assessmentRunArn" case stopAction = "stopAction" } } public struct SubscribeToEventRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "event", required: true, type: .enum), AWSShapeMember(label: "resourceArn", required: true, type: .string), AWSShapeMember(label: "topicArn", required: true, type: .string) ] /// The event for which you want to receive SNS notifications. public let event: InspectorEvent /// The ARN of the assessment template that is used during the event for which you want to receive SNS notifications. public let resourceArn: String /// The ARN of the SNS topic to which the SNS notifications are sent. public let topicArn: String public init(event: InspectorEvent, resourceArn: String, topicArn: String) { self.event = event self.resourceArn = resourceArn self.topicArn = topicArn } public func validate(name: String) throws { try validate(self.resourceArn, name:"resourceArn", parent: name, max: 300) try validate(self.resourceArn, name:"resourceArn", parent: name, min: 1) try validate(self.topicArn, name:"topicArn", parent: name, max: 300) try validate(self.topicArn, name:"topicArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case event = "event" case resourceArn = "resourceArn" case topicArn = "topicArn" } } public struct Subscription: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "eventSubscriptions", required: true, type: .list), AWSShapeMember(label: "resourceArn", required: true, type: .string), AWSShapeMember(label: "topicArn", required: true, type: .string) ] /// The list of existing event subscriptions. public let eventSubscriptions: [EventSubscription] /// The ARN of the assessment template that is used during the event for which the SNS notification is sent. public let resourceArn: String /// The ARN of the Amazon Simple Notification Service (SNS) topic to which the SNS notifications are sent. public let topicArn: String public init(eventSubscriptions: [EventSubscription], resourceArn: String, topicArn: String) { self.eventSubscriptions = eventSubscriptions self.resourceArn = resourceArn self.topicArn = topicArn } private enum CodingKeys: String, CodingKey { case eventSubscriptions = "eventSubscriptions" case resourceArn = "resourceArn" case topicArn = "topicArn" } } public struct Tag: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "key", required: true, type: .string), AWSShapeMember(label: "value", required: false, type: .string) ] /// A tag key. public let key: String /// A value assigned to a tag key. public let value: String? public init(key: String, value: String? = nil) { self.key = key self.value = value } public func validate(name: String) throws { try validate(self.key, name:"key", parent: name, max: 128) try validate(self.key, name:"key", parent: name, min: 1) try validate(self.value, name:"value", parent: name, max: 256) try validate(self.value, name:"value", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case key = "key" case value = "value" } } public struct TelemetryMetadata: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "count", required: true, type: .long), AWSShapeMember(label: "dataSize", required: false, type: .long), AWSShapeMember(label: "messageType", required: true, type: .string) ] /// The count of messages that the agent sends to the Amazon Inspector service. public let count: Int64 /// The data size of messages that the agent sends to the Amazon Inspector service. public let dataSize: Int64? /// A specific type of behavioral data that is collected by the agent. public let messageType: String public init(count: Int64, dataSize: Int64? = nil, messageType: String) { self.count = count self.dataSize = dataSize self.messageType = messageType } private enum CodingKeys: String, CodingKey { case count = "count" case dataSize = "dataSize" case messageType = "messageType" } } public struct TimestampRange: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "beginDate", required: false, type: .timestamp), AWSShapeMember(label: "endDate", required: false, type: .timestamp) ] /// The minimum value of the timestamp range. public let beginDate: TimeStamp? /// The maximum value of the timestamp range. public let endDate: TimeStamp? public init(beginDate: TimeStamp? = nil, endDate: TimeStamp? = nil) { self.beginDate = beginDate self.endDate = endDate } private enum CodingKeys: String, CodingKey { case beginDate = "beginDate" case endDate = "endDate" } } public struct UnsubscribeFromEventRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "event", required: true, type: .enum), AWSShapeMember(label: "resourceArn", required: true, type: .string), AWSShapeMember(label: "topicArn", required: true, type: .string) ] /// The event for which you want to stop receiving SNS notifications. public let event: InspectorEvent /// The ARN of the assessment template that is used during the event for which you want to stop receiving SNS notifications. public let resourceArn: String /// The ARN of the SNS topic to which SNS notifications are sent. public let topicArn: String public init(event: InspectorEvent, resourceArn: String, topicArn: String) { self.event = event self.resourceArn = resourceArn self.topicArn = topicArn } public func validate(name: String) throws { try validate(self.resourceArn, name:"resourceArn", parent: name, max: 300) try validate(self.resourceArn, name:"resourceArn", parent: name, min: 1) try validate(self.topicArn, name:"topicArn", parent: name, max: 300) try validate(self.topicArn, name:"topicArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case event = "event" case resourceArn = "resourceArn" case topicArn = "topicArn" } } public struct UpdateAssessmentTargetRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "assessmentTargetArn", required: true, type: .string), AWSShapeMember(label: "assessmentTargetName", required: true, type: .string), AWSShapeMember(label: "resourceGroupArn", required: false, type: .string) ] /// The ARN of the assessment target that you want to update. public let assessmentTargetArn: String /// The name of the assessment target that you want to update. public let assessmentTargetName: String /// The ARN of the resource group that is used to specify the new resource group to associate with the assessment target. public let resourceGroupArn: String? public init(assessmentTargetArn: String, assessmentTargetName: String, resourceGroupArn: String? = nil) { self.assessmentTargetArn = assessmentTargetArn self.assessmentTargetName = assessmentTargetName self.resourceGroupArn = resourceGroupArn } public func validate(name: String) throws { try validate(self.assessmentTargetArn, name:"assessmentTargetArn", parent: name, max: 300) try validate(self.assessmentTargetArn, name:"assessmentTargetArn", parent: name, min: 1) try validate(self.assessmentTargetName, name:"assessmentTargetName", parent: name, max: 140) try validate(self.assessmentTargetName, name:"assessmentTargetName", parent: name, min: 1) try validate(self.resourceGroupArn, name:"resourceGroupArn", parent: name, max: 300) try validate(self.resourceGroupArn, name:"resourceGroupArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case assessmentTargetArn = "assessmentTargetArn" case assessmentTargetName = "assessmentTargetName" case resourceGroupArn = "resourceGroupArn" } } }
48.849487
526
0.647919
714c2f283b7438c645929b75006b5445378d5dff
4,466
// // MinimedPumpManager+UI.swift // Loop // // Copyright © 2018 LoopKit Authors. All rights reserved. // import UIKit import LoopKit import LoopKitUI import MinimedKit extension MinimedPumpManager: PumpManagerUI { static public func setupViewController() -> (UIViewController & PumpManagerSetupViewController & CompletionNotifying) { return MinimedPumpManagerSetupViewController.instantiateFromStoryboard() } public func settingsViewController() -> (UIViewController & CompletionNotifying) { let settings = MinimedPumpSettingsViewController(pumpManager: self) let nav = SettingsNavigationViewController(rootViewController: settings) return nav } public var smallImage: UIImage? { return state.smallPumpImage } public func hudProvider() -> HUDProvider? { return MinimedHUDProvider(pumpManager: self) } public static func createHUDViews(rawValue: HUDProvider.HUDViewsRawState) -> [BaseHUDView] { return MinimedHUDProvider.createHUDViews(rawValue: rawValue) } } // MARK: - DeliveryLimitSettingsTableViewControllerSyncSource extension MinimedPumpManager { public func syncDeliveryLimitSettings(for viewController: DeliveryLimitSettingsTableViewController, completion: @escaping (DeliveryLimitSettingsResult) -> Void) { pumpOps.runSession(withName: "Save Settings", using: rileyLinkDeviceProvider.firstConnectedDevice) { (session) in guard let session = session else { completion(.failure(PumpManagerError.connection(MinimedPumpManagerError.noRileyLink))) return } do { if let maxBasalRate = viewController.maximumBasalRatePerHour { try session.setMaxBasalRate(unitsPerHour: maxBasalRate) } if let maxBolus = viewController.maximumBolus { try session.setMaxBolus(units: maxBolus) } let settings = try session.getSettings() completion(.success(maximumBasalRatePerHour: settings.maxBasal, maximumBolus: settings.maxBolus)) } catch let error { self.log.error("Save delivery limit settings failed: %{public}@", String(describing: error)) completion(.failure(error)) } } } public func syncButtonTitle(for viewController: DeliveryLimitSettingsTableViewController) -> String { return LocalizedString("Save to Pump…", comment: "Title of button to save delivery limit settings to pump") } public func syncButtonDetailText(for viewController: DeliveryLimitSettingsTableViewController) -> String? { return nil } public func deliveryLimitSettingsTableViewControllerIsReadOnly(_ viewController: DeliveryLimitSettingsTableViewController) -> Bool { return false } } // MARK: - BasalScheduleTableViewControllerSyncSource extension MinimedPumpManager { public func syncScheduleValues(for viewController: BasalScheduleTableViewController, completion: @escaping (SyncBasalScheduleResult<Double>) -> Void) { pumpOps.runSession(withName: "Save Basal Profile", using: rileyLinkDeviceProvider.firstConnectedDevice) { (session) in guard let session = session else { completion(.failure(PumpManagerError.connection(MinimedPumpManagerError.noRileyLink))) return } do { let newSchedule = BasalSchedule(repeatingScheduleValues: viewController.scheduleItems) try session.setBasalSchedule(newSchedule, for: .standard) completion(.success(scheduleItems: viewController.scheduleItems, timeZone: session.pump.timeZone)) } catch let error { self.log.error("Save basal profile failed: %{public}@", String(describing: error)) completion(.failure(error)) } } } public func syncButtonTitle(for viewController: BasalScheduleTableViewController) -> String { return LocalizedString("Save to Pump…", comment: "Title of button to save basal profile to pump") } public func syncButtonDetailText(for viewController: BasalScheduleTableViewController) -> String? { return nil } public func basalScheduleTableViewControllerIsReadOnly(_ viewController: BasalScheduleTableViewController) -> Bool { return false } }
39.522124
166
0.692566
7a64c9407d0699863a66b13dae51bdae899f1927
4,003
import ComposableArchitecture import HomeFeature import MediaFeature import FavoritesFeature import AboutFeature import SettingFeature import SwiftUI import Model import Styleguide import Component public struct AppTabScreen: View { @State var selection: Int = .zero public let store: Store<AppTabState, AppTabAction> public init(store: Store<AppTabState, AppTabAction>) { self.store = store UITabBar.appearance().configureWithDefaultStyle() UINavigationBar.appearance().configureWithDefaultStyle() } struct ViewState: Equatable { var isShowingSheet: Bool init(state: AppTabState) { isShowingSheet = state.isShowingSheet } } public enum ViewAction { case reload } public var body: some View { WithViewStore(store.scope(state: ViewState.init(state:))) { viewStore in TabView( selection: $selection, content: { ForEach(Array(AppTab.allCases.enumerated()), id: \.offset) { (offset, tab) in tab.view(store) .tabItem { tab.image.renderingMode(.template) Text(tab.title) } .tag(offset) } } ) .onReceive( NotificationCenter .default .publisher(for: UIApplication.willEnterForegroundNotification) ) { _ in viewStore.send(.reload) } .sheet( isPresented: viewStore.binding( get: \.isShowingSheet, send: .hideSheet ), content: { IfLetStore(store.scope(state: \.isSheetPresented)) { store in WithViewStore(store) { viewStore in switch viewStore.state { case .url(let url): WebView(url: url) case .setting: SettingScreen(isDarkModeOn: true, isLanguageOn: true) } } } } ) } } } private extension AppTab { var title: String { switch self { case .home: return L10n.HomeScreen.title case .media: return L10n.MediaScreen.title case .favorites: return L10n.FavoriteScreen.title case .about: return L10n.AboutScreen.title } } var image: SwiftUI.Image { switch self { case .home: return AssetImage.iconHome.image case .media: return AssetImage.iconBlog.image case .favorites: return AssetImage.iconStar.image case .about: return AssetImage.iconAbout.image } } } private extension AppTabState { var isShowingSheet: Bool { isSheetPresented != nil } } #if DEBUG public struct AppTabScreen_Previews: PreviewProvider { public static var previews: some View { ForEach(ColorScheme.allCases, id: \.self) { colorScheme in AppTabScreen( store: .init( initialState: .init( feedContents: [ .blogMock(), .blogMock(), .blogMock(), .blogMock(), .blogMock(), .blogMock() ] ), reducer: .empty, environment: {} ) ) .previewDevice(.init(rawValue: "iPhone 12")) .environment(\.colorScheme, colorScheme) } } } #endif
29.218978
97
0.477142
2641116d71d801589b612277642dcd6013adf531
404
// // // // Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages sent in a private chat public class PrivateFilter: TGFilter { public var name: String = "private" override public func filter(message: TGMessage) -> Bool { return message.chat.type == .private } } public extension TGFilter { static var `private`: PrivateFilter { PrivateFilter() } }
17.565217
59
0.665842
260c0db825a67a7fff995009f0daddf4f684565c
2,932
// // ImagePickerCell.swift // Model2App // // Created by Karol Kulesza on 7/12/18. // Copyright © 2018 Q Mobile { http://Q-Mobile.IT } // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation struct ImagePickerConstants { static let accessoryViewVerticalInset: CGFloat = 5.0 } /** * Property cell for displaying and picking the image value for a property */ open class ImagePickerCell : PropertyCell<Data> { // MARK: - // MARK: BaseCell Methods override open func didSelect() { super.didSelect() objectVC?.handleImageSelection() } override open func setup() { super.setup() selectionStyle = .default } override open func update() { super.update() if let image = ImageUtilities.getThumbnailForNameData(nameData: value) { let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: frame.height - 2 * ImagePickerConstants.accessoryViewVerticalInset, height: frame.height - 2 * ImagePickerConstants.accessoryViewVerticalInset)) imageView.contentMode = .scaleAspectFill imageView.image = image imageView.clipsToBounds = true accessoryView = imageView editingAccessoryView = accessoryView if M2A.config.objectPropertyDefaultShouldRoundImages { accessoryView?.layer.cornerRadius = (frame.height - 2 * ImagePickerConstants.accessoryViewVerticalInset) / 2 } } else { accessoryView = nil editingAccessoryView = nil } } override open var canBecomeFirstResponder: Bool { return true } open override func resignFirstResponder() -> Bool { let resign = super.resignFirstResponder() if resign { objectVC?.deselectRow(for: self) } return resign } }
34.904762
217
0.678718
fb5fd2fb922455e63b090827753483102fb14391
1,773
// // LocalJSONParser.swift // ModelSynchro // // Created by Jonathan Samudio on 2/12/18. // Copyright © 2018 Jonathan Samudio. All rights reserved. // import Foundation open class LocalJSONParser { // MARK: - Private Properties private let config: ConfigurationFile private let jsonParser: JsonParser fileprivate let jsonFileExtension = ".json" // MARK: - Initialization public init(config: ConfigurationFile, jsonParser: JsonParser) { self.config = config self.jsonParser = jsonParser } // MARK: - Public Functions public func parseLocalJSON() { guard let localJSONDirectory = config.directoryInfo.localJSONDirectory else { return } for dir in localJSONDirectory { loadJSON(at: config.localPath(directory: dir.inputDirectory)) jsonParser.writeModelsToFile(directory: dir) jsonParser.clearDataSource() } } } // MARK: - Private Functions private extension LocalJSONParser { func loadJSON(at inputPath: String) { let fileNames = FileRetriever.retrieveFilenames(at: inputPath, fileExtension: jsonFileExtension) for file in fileNames { let fileToParse = inputPath + file do { let content = try String(contentsOfFile: fileToParse, encoding: String.Encoding.utf8) let fileName = file.removeTrailing(startWith: jsonFileExtension) let data = content.data(using: .utf8) jsonParser.parse(data: data, name: fileName) } catch { print("Error caught with message: \(error.localizedDescription)") } } } }
28.142857
101
0.614213
f54ad28eab13f04ef9df0c87314b1fa09ac4ead3
2,170
// // AppDelegate.swift // LimitInputText // // Created by kuroky on 2019/2/14. // Copyright © 2019 Emucoo. 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.170213
285
0.7553
201c026cddc16f6ae72f8d0f1ffbb0cb3b81b15d
1,000
// // LoggingFrameWorkTests.swift // LoggingFrameWorkTests // // Created by apple on 16/03/18. // Copyright © 2018 Letsmobility. All rights reserved. // import XCTest @testable import LoggingFrameWork class LoggingFrameWorkTests: 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.027027
111
0.645
f526a0cee8ed8519c1a8485e1a987f0c5d085fd8
1,260
// // InterfaceController.swift // Spin the Watch WatchKit Extension // // Created by Rob Vargas on 2/21/15. // Copyright (c) 2015 Robert Vargas. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { @IBOutlet var nameLabel: WKInterfaceLabel! @IBAction func buttonPressed() { var randomNumber = arc4random_uniform(2) if randomNumber == 0 { nameLabel.setText("heads") } else { nameLabel.setText("tails") } println(randomNumber) //nameLabel.setText("My app is working!") } override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) println("My app is working!") } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() NSLog("%@ will activate", self) } override func didDeactivate() { // This method is called when watch view controller is no longer visible NSLog("%@ did deactivate", self) super.didDeactivate() } }
22.5
90
0.590476
5b6b8228d667c187dfade36d96e91f4d018e0a35
1,643
// // Created by Jérôme Alves on 11/12/2019. // Copyright © 2019 TwentyLayout. All rights reserved. // import Foundation import UIKit /// label.anchors.edges == otherLabel.anchors.margins ~ .xxx public func == < LHSBase, LHSTop, LHSBottom, LHSLeft, LHSRight, RHS: ConstraintOperand >( lhs: EdgesAnchor<LHSBase, LHSTop, LHSBottom, LHSLeft, LHSRight>, rhs: RHS? ) where RHS.Value: Constrainable { guard let rhs = rhs else { return } lhs.top == rhs.constraintValue ~ rhs lhs.bottom == rhs.constraintValue ~ rhs lhs.left == rhs.constraintValue ~ rhs lhs.right == rhs.constraintValue ~ rhs } /// label.anchors.edges <= otherLabel.anchors.margins ~ .xxx public func <= < LHSBase, LHSTop, LHSBottom, LHSLeft, LHSRight, RHS: ConstraintOperand >( lhs: EdgesAnchor<LHSBase, LHSTop, LHSBottom, LHSLeft, LHSRight>, rhs: RHS? ) where RHS.Value: Constrainable { guard let rhs = rhs else { return } lhs.top >= rhs.constraintValue ~ rhs lhs.bottom <= rhs.constraintValue ~ rhs lhs.left >= rhs.constraintValue ~ rhs lhs.right <= rhs.constraintValue ~ rhs } /// label.anchors.edges >= otherLabel.anchors.margin ~ .xxx public func >= < LHSBase, LHSTop, LHSBottom, LHSLeft, LHSRight, RHS: ConstraintOperand >( lhs: EdgesAnchor<LHSBase, LHSTop, LHSBottom, LHSLeft, LHSRight>, rhs: RHS? ) where RHS.Value: Constrainable { guard let rhs = rhs else { return } lhs.top <= rhs.constraintValue ~ rhs lhs.bottom >= rhs.constraintValue ~ rhs lhs.left <= rhs.constraintValue ~ rhs lhs.right >= rhs.constraintValue ~ rhs }
26.079365
68
0.665855
20816272d06f8c6d54934beaa041b8ff51af4336
2,147
// // Copyright (c) 2015 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import Firebase /** * PatternTabBarController exists as a subclass of UITabBarConttroller that * supports a 'share' action. This will trigger a custom event to Analytics and * display a dialog. */ @objc(PatternTabBarController) // match the ObjC symbol name inside Storyboard class PatternTabBarController: UITabBarController { override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if getUserFavoriteFood() == nil { askForFavoriteFood() } } @IBAction func didTapShare(_ sender: AnyObject) { let name = "Pattern~\(self.selectedViewController!.title!)", text = "I'd love you to hear about\(name)" // [START custom_event_swift] Analytics.logEvent("share_image", parameters: [ "name": name as NSObject, "full_text": text as NSObject ]) // [END custom_event_swift] let title = "Share: \(self.selectedViewController!.title!)", message = "Share event sent to Analytics; actual share not implemented in this quickstart", alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) present(alert, animated: true, completion: nil) } @IBAction func unwindToHome(_ segue: UIStoryboardSegue?) { } func getUserFavoriteFood() -> String? { return UserDefaults.standard.string(forKey: "favorite_food") } func askForFavoriteFood() { performSegue(withIdentifier: "pickFavoriteFood", sender: self) } }
32.530303
99
0.715883
de8e40cb1019b5210ca4ee0634141aff360822a4
627
// // KittenParent.swift // Pods // // Created by Spring Wong on 27/2/2017. // // import Foundation public protocol KittenParent : KittenBuild{ //prepare the parent which will added our item to @discardableResult func from(_ parent : UIView) -> KittenParentMethods //create a empty UIView() @discardableResult func from() -> KittenParentMethods //default align topLayoutGuide and bottomLayoutGuide @discardableResult func from(_ parent : UIViewController) -> KittenParentMethods //attach a view to UIScrollView @discardableResult func from(_ parent : UIScrollView) -> KittenParentMethods }
29.857143
84
0.735247
4abad3dbc1ce2e2ba9045961c9cd5b01de775c0a
1,282
// // AppDelegate.swift // EmulateAppSwitcher // // Created by Don Mag on 2/7/21. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
34.648649
176
0.786271
188183987753b3fb8363082b8c263221cdfa1459
2,917
import Foundation enum ChangeType { case Address, Port } public class IPMutablePacket { // Support only IPv4 for now let version: IPVersion let proto: TransportType let IPHeaderLength: Int var sourceAddress: IPv4Address { get { return IPv4Address(fromBytesInNetworkOrder: payload.bytes.advancedBy(12)) } set { setIPv4Address(sourceAddress, newAddress: newValue, at: 12) } } var destinationAddress: IPv4Address { get { return IPv4Address(fromBytesInNetworkOrder: payload.bytes.advancedBy(16)) } set { setIPv4Address(destinationAddress, newAddress: newValue, at: 16) } } let payload: NSMutableData public init(payload: NSData) { let vl = UnsafePointer<UInt8>(payload.bytes).memory version = IPVersion(rawValue: vl >> 4)! IPHeaderLength = Int(vl & 0x0F) * 4 let p = UnsafePointer<UInt8>(payload.bytes.advancedBy(9)).memory proto = TransportType(rawValue: p)! self.payload = NSMutableData(data: payload) } func updateChecksum(oldValue: UInt16, newValue: UInt16, type: ChangeType) { if type == .Address { updateChecksum(oldValue, newValue: newValue, at: 10) } } // swiftlint:disable:next variable_name internal func updateChecksum(oldValue: UInt16, newValue: UInt16, at: Int) { let oldChecksum = UnsafePointer<UInt16>(payload.bytes.advancedBy(at)).memory let oc32 = UInt32(~oldChecksum) let ov32 = UInt32(~oldValue) let nv32 = UInt32(newValue) var newChecksum32 = oc32 &+ ov32 &+ nv32 newChecksum32 = (newChecksum32 & 0xFFFF) + (newChecksum32 >> 16) newChecksum32 = (newChecksum32 & 0xFFFF) &+ (newChecksum32 >> 16) var newChecksum = ~UInt16(newChecksum32) payload.replaceBytesInRange(NSRange(location: at, length: 2), withBytes: &newChecksum, length: 2) } // swiftlint:disable:next variable_name private func foldChecksum(checksum: UInt32) -> UInt32 { var checksum = checksum while checksum > 0xFFFF { checksum = (checksum & 0xFFFF) + (checksum >> 16) } return checksum } // swiftlint:disable:next variable_name private func setIPv4Address(oldAddress: IPv4Address, newAddress: IPv4Address, at: Int) { payload.replaceBytesInRange(NSRange(location: at, length: 4), withBytes: newAddress.bytesInNetworkOrder, length: 4) updateChecksum(UnsafePointer<UInt16>(oldAddress.bytesInNetworkOrder).memory, newValue: UnsafePointer<UInt16>(newAddress.bytesInNetworkOrder).memory, type: .Address) updateChecksum(UnsafePointer<UInt16>(oldAddress.bytesInNetworkOrder).advancedBy(1).memory, newValue: UnsafePointer<UInt16>(newAddress.bytesInNetworkOrder).advancedBy(1).memory, type: .Address) } }
37.883117
204
0.664038
f89e3ab5a16fcf8561d5b8a2bbc3e1f3b4d50460
1,448
// // The MIT License // // Copyright (c) 2014- High-Mobility GmbH (https://high-mobility.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // // UInt8Collection+Extensions.swift // HMCryptoKit // // Created by Mikk Rätsep on 06/03/2018. // import Foundation extension Array where Element == UInt8 { init(zeroFilledTo size: Int) { self.init(repeating: 0x00, count: size) } }
36.2
81
0.731354
c1bf8a5dd1925e5b01864488a191822abf8db07b
1,819
import Foundation /** The `Predicate` protocol is used to define the structre that must be implemented by concrete predicates. */ public protocol Predicate: AsyncPredicate { /** A type that provides information about what kind of values the predicate can be evaluated with. */ associatedtype InputType /** Returns a `Boolean` value that indicates whether a given input matches the conditions specified by the receiver. - parameter input: The input against which to evaluate the receiver. - returns: `true` if input matches the conditions specified by the receiver, `false` otherwise. */ func evaluate(with input: InputType) -> Bool } extension Predicate { private var workQueue: DispatchQueue { return DispatchQueue(label: "com.nsagora.validation-toolkit.predicate", attributes: .concurrent) } /** Asynchronous evaluates whether a given input matches the conditions specified by the receiver, then calls a handler upon completion. - parameter input: The input against which to evaluate the receiver. - parameter queue: The queue on which the completion handler is executed. If not specified, it uses `DispatchQueue.main`. - parameter completionHandler: The completion handler to call when the evaluation is complete. It takes a `Bool` parameter: - parameter matches: `true` if input matches the conditions specified by the receiver, `false` otherwise. */ public func evaluate(with input: InputType, queue: DispatchQueue = .main, completionHandler: @escaping (_ matches: Bool) -> Void) { workQueue.async { let result = self.evaluate(with: input) queue.async { completionHandler(result) } } } }
38.702128
137
0.686641
6af614154baa7f436a1ce631d506d60259eb19d9
1,940
// // GymConstants.swift // Las Playas // // Created by Stan Shockley on 3/9/22. // import Foundation struct g { static let registerSegue = "RegisterToHome" static let loginSegue = "LoginToHome" static let cellIdentifier = "UserChoiceCell" static let homeNibName = "HomeCollectionViewCell" static let surveySegue = "SurveyOptions" static let constructionSegue = "UnderConstruction" static let constructionSegue2 = "UnderConstruction2" static let surveyNibName = "SurveyOptionsCollectionViewCell" static let surveyCellIdentifier = "SurveyChoiceCell" static let gymCellIdentifier = "GymViewCell" static let gymNibName = "GymTableViewCell" static let gymSegue = "GymSurvey" static let gymRateCellIdentifier = "GymRatingViewCell" static let gymRateNibName = "GymRatingTableViewCell" static let backToSurveyHome = "BackToHome" static let hometoDelete = "HomeToDelete" static let deleteTableViewCell = "DeleteTableViewCell" static let deleteNibName = "DeleteTableViewCell" static let backToFeedbackHome = "BackToFeedbackHome" static let feedbackSegue = "OverAllFeedback" static let gQuestions = [ " 1. How satisfied are you with the courtesy of our staff?", " 2. Are you happy with the equipment available in our fitness center?", " 3. How satisfied are you with the accessibility of our fitness center?", " 4. Are you happy with the service you received from our staff?", " 5. How satisfied are you with the activities made available during your stay?", " 6. How would you rate our live entertainment shows?", " 7. How satisfied are you with your spa experience?", " 8. How would you rate the level of comfort of our resort?", " 9. How satisfied are you with the all inclusive options offered?", "10. How likely are you to return for another vacation?" ] }
41.276596
89
0.708763
878fa14e7ed2931275bb4dec4ce8b23b799790a6
1,958
// // Deferred.swift // deferred // // Created by Arthur Borisow on 3/21/15. // Copyright (c) 2015 Arthur Borisow. All rights reserved. // import Foundation public class Deferred: Promise { public private(set) var state: State = .Pending private var arg: AnyObject? let qState = dispatch_queue_create("edu.self.deferred.q.state", DISPATCH_QUEUE_CONCURRENT) let qCallbacks = dispatch_queue_create("edu.self.deferred.q.callbacks", DISPATCH_QUEUE_CONCURRENT) private var callbacks: [State : [CallbackInvoker]] = [State : [CallbackInvoker]]() public init() { callbacks[.Rejected] = [] callbacks[.Resolved] = [] } public func promise() -> Promise { return PromiseImplementation(deferred: self) } // MARK: helpers func addOrRunCallback(callback: Callback, to: State, on queue: dispatch_queue_t = dispatch_get_main_queue()) { dispatch_async(qState) { switch (self.state, to) { case (.Pending, _): dispatch_barrier_async(self.qCallbacks) { let _ = self.callbacks[to]?.append(CallbackInvoker(callback: callback, q: queue)) } case (.Resolved, .Resolved), (.Rejected, .Rejected): CallbackInvoker(callback: callback, q: queue).invoke(self.arg) default: break } } } func setState(state: State, andRunCallbacksWithArg arg: AnyObject?) { dispatch_barrier_async(qState) { switch self.state { case .Pending: self.state = state self.arg = arg dispatch_async(self.qCallbacks) { for callbackInvoker in self.callbacks[state]! { callbackInvoker.invoke(self.arg) } } default: break } } } }
32.098361
114
0.564351
11bd96b5ac1311e917465ef044ca2e653c8c419c
2,221
// // EventData+CoreDataProperties.swift // Chula Expo 2017 // // Created by NOT on 1/8/2560 BE. // Copyright © 2560 Chula Computer Engineering Batch#41. All rights reserved. // import Foundation import CoreData extension EventData { @nonobjc public class func fetchRequest() -> NSFetchRequest<EventData> { return NSFetchRequest<EventData>(entityName: "EventData"); } @NSManaged public var activityId: String? @NSManaged public var name: String? @NSManaged public var thumbnail: String? @NSManaged public var startTime: Date? @NSManaged public var endTime: Date? @NSManaged public var longDesc: String? @NSManaged public var shortDesc: String? @NSManaged public var facity: String? @NSManaged public var locationDesc: String? @NSManaged public var canReserve: Bool @NSManaged public var isReserve: Bool @NSManaged public var isFavorite: Bool @NSManaged public var numOfSeat: Int16 var dateSection: String { get { if self.startTime!.isToday() { return "TODAY" } else if self.startTime!.isTomorrow() { return "TOMORROW" } else if self.startTime!.isYesterday() { return "YESTERDAY" } else { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM dd, EEE H m" return dateFormatter.string(from: startTime! as Date) } } } var dateText: String { get { if self.startTime!.isToday() { return "Today" } else if self.startTime!.isTomorrow() { return "Tomorrow" } else if self.startTime!.isYesterday() { return "Yesterday" } else { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM dd, EEE" return dateFormatter.string(from: startTime! as Date) } } } }
26.129412
78
0.539847
eb16cfd2ad53a12e6bff098fac34b918113a5120
3,811
// // LoginVC.swift // NewsApp // // Created by macosx on 22.07.17. // Copyright © 2017 macosx. All rights reserved. // import UIKit import FBSDKCoreKit import FBSDKLoginKit import SDWebImage class LoginVC: UIViewController { @IBOutlet fileprivate weak var holder: UIView! @IBOutlet fileprivate weak var avatar: UIImageView! @IBOutlet fileprivate weak var name: UILabel! @IBOutlet fileprivate weak var loginBtn: FBSDKLoginButton! override func viewDidLoad() { super.viewDidLoad() loginBtn.readPermissions = ["public_profile", "email", "user_friends", "user_photos"] configUI() getUserInformation() // Do any additional setup after loading the view. } @IBAction func signUpBtnTapped(_ sender: UIButton) { let signUpVC = storyboard?.instantiateViewController(withIdentifier: "qqRegistrationpp") as! RegistrationVC; self.navigationController?.pushViewController(signUpVC, animated: true) } // MARK: - Create Avatar As Circle fileprivate func configUI () { // fix scale avatar.contentMode = .scaleAspectFill avatar.clipsToBounds = true // set circle avatar.layer.cornerRadius = avatar.frame.size.width/2 avatar.layer.masksToBounds = true // set borders avatar.layer.borderColor = UIColor.blue.cgColor avatar.layer.borderWidth = 0.8 } // MARK: - Determine User Status private func userIsLoggedIn () -> Bool { return FBSDKAccessToken.current() != nil } // MARK: - Download Informatio fileprivate func getUserInformation () { if userIsLoggedIn() { let params = ["fields":"id,name,picture.type(large),email"] FBSDKGraphRequest(graphPath: "me", parameters: params).start(completionHandler: { [weak self] (connection, result, error) -> Void in if error == nil && result != nil { self?.generateUserObjectUsingGraphResponse(with: result!) } }) } else { print("Not Logged In!") } } // MARK: - Construct User Object private func generateUserObjectUsingGraphResponse (with result: Any) { let object = User() if let rep = result as? [String: Any] { object.name = rep["name"] as! String object.avatar = self.getUserAvatarUrl(with: rep["picture"] as! [String: Any]) self.userInterfaceConfiguration(with: object) } } // MARK: - Assign Information fileprivate func userInterfaceConfiguration (with object: User) { holder.isHidden = false name.text = object.name avatar.sd_setImage(with: object.avatar) } // MARK: - Parse Profile Picture private func getUserAvatarUrl (with value: [String: Any]) -> URL? { if let value1 = value["data"] as? [String: Any] { if let value2 = value1["url"] as? String { return URL(string: value2) } } return nil } } // MARK: - FBSDKLoginButtonDelegatec extension LoginVC : FBSDKLoginButtonDelegate { func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { if error == nil { getUserInformation() let vc = storyboard?.instantiateViewController(withIdentifier: "qqTabBarpp") as! TabBarControllerVC; self.navigationController?.pushViewController(vc, animated: true) } else { print(error.localizedDescription) } } func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) { holder.isHidden = true print("User Logged Out!") } }
32.853448
188
0.620572
64ef5f1a2c874ede18d0f5b1229e9629428391e8
642
// // QueryResponseData.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public class QueryResponseData: Codable { /** Interval with start and end represented as ISO-8601 string. i.e: yyyy-MM-dd&#39;T&#39;HH:mm:ss.SSS&#39;Z&#39;/yyyy-MM-dd&#39;T&#39;HH:mm:ss.SSS&#39;Z&#39; */ public var interval: String? /** A list of aggregated metrics */ public var metrics: [QueryResponseMetric]? public init(interval: String?, metrics: [QueryResponseMetric]?) { self.interval = interval self.metrics = metrics } }
21.4
165
0.640187
9188d2b9c61c950baf85c5e02a65d81f1ebf145c
3,245
// // String+Validators.swift // Swift-Demo // // Created by Zhishen Wen on 2018/4/10. // Copyright © 2018 0xa6a. All rights reserved. // import Foundation extension String { /// 验证身份证号码 func validateIDCardNumber() -> Bool { struct Static { fileprivate static let predicate: NSPredicate = { let regex = "(^\\d{15}$)|(^\\d{17}([0-9]|X)$)" let predicate = NSPredicate(format: "SELF MATCHES %@", argumentArray: [regex]) return predicate }() fileprivate static let provinceCodes = [ "11", "12", "13", "14", "15", "21", "22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64", "65", "71", "81", "82", "91"] } // 初步验证 guard Static.predicate.evaluate(with: self) else { return false } // 验证省份代码。如果需要更精确的话,可以把前六位行政区划代码都列举出来比较。 let provinceCode = String(self.prefix(2)) guard Static.provinceCodes.contains(provinceCode) else { return false } if self.count == 15 { return self.validate15DigitsIDCardNumber() } else { return self.validate18DigitsIDCardNumber() } } /// 15位身份证号码验证。 // 6位行政区划代码 + 6位出生日期码(yyMMdd) + 3位顺序码 private func validate15DigitsIDCardNumber() -> Bool { let birthdate = "19\(self.substring(from: 6, to: 11)!)" return birthdate.validateBirthDate() } /// 18位身份证号码验证。 // 6位行政区划代码 + 8位出生日期码(yyyyMMdd) + 3位顺序码 + 1位校验码 private func validate18DigitsIDCardNumber() -> Bool { let birthdate = self.substring(from: 6, to: 13)! guard birthdate.validateBirthDate() else { return false } struct Static { static let weights = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2] static let validationCodes = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"] } // 验证校验位 let digits = self.substring(from: 0, to: 16)!.map { Int("\($0)")! } var sum = 0 for i in 0..<Static.weights.count { sum += Static.weights[i] * digits[i] } let mod11 = sum % 11 let validationCode = Static.validationCodes[mod11] return hasSuffix(validationCode) } private func validateBirthDate() -> Bool { struct Static { static let dateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyyMMdd" return dateFormatter }() } if let _ = Static.dateFormatter.date(from: self) { return true } else { return false } } private func substring(from: Int, to: Int) -> String? { guard to >= from && from >= 0 && to < count else { return nil } let startIdx = self.index(startIndex, offsetBy: from) let endIdx = self.index(startIndex, offsetBy: to) return String(self[startIdx...endIdx]) } }
32.777778
96
0.511556
fffdb6b1f2d71a3bc4a743aa3bf7f3de33e50c85
4,493
// // LocationServiceCore.swift // ZamzamLocation // // Created by Basem Emara on 2019-08-25. // Copyright © 2019 Zamzam Inc. All rights reserved. // import CoreLocation import ZamzamCore public class LocationServiceCore: NSObject, LocationService { private let desiredAccuracy: CLLocationAccuracy? private let distanceFilter: Double? private let activityType: CLActivityType? public weak var delegate: LocationServiceDelegate? /// Internal Core Location manager private lazy var manager = CLLocationManager().apply { $0.delegate = self $0.desiredAccuracy ?= self.desiredAccuracy $0.distanceFilter ?= self.distanceFilter #if os(iOS) $0.activityType ?= self.activityType #endif } public required init( desiredAccuracy: CLLocationAccuracy? = nil, distanceFilter: Double? = nil, activityType: CLActivityType? = nil ) { self.desiredAccuracy = desiredAccuracy self.distanceFilter = distanceFilter self.activityType = activityType super.init() } } // MARK: - Authorization public extension LocationServiceCore { var isAuthorized: Bool { manager.isAuthorized } func isAuthorized(for type: LocationAPI.AuthorizationType) -> Bool { guard CLLocationManager.locationServicesEnabled() else { return false } #if os(macOS) return type == .always && manager.authorizationStatus == .authorizedAlways #else return (type == .whenInUse && manager.authorizationStatus == .authorizedWhenInUse) || (type == .always && manager.authorizationStatus == .authorizedAlways) #endif } var canRequestAuthorization: Bool { manager.authorizationStatus == .notDetermined } func requestAuthorization(for type: LocationAPI.AuthorizationType) { #if os(macOS) if #available(OSX 10.15, *) { manager.requestAlwaysAuthorization() } #elseif os(tvOS) manager.requestWhenInUseAuthorization() #else switch type { case .whenInUse: manager.requestWhenInUseAuthorization() case .always: manager.requestAlwaysAuthorization() } #endif } } // MARK: - Coordinate public extension LocationServiceCore { var location: CLLocation? { manager.location } func startUpdatingLocation(enableBackground: Bool, pauseAutomatically: Bool?) { #if os(iOS) manager.allowsBackgroundLocationUpdates = enableBackground manager.pausesLocationUpdatesAutomatically ?= pauseAutomatically #endif #if !os(tvOS) manager.startUpdatingLocation() #endif } func stopUpdatingLocation() { #if os(iOS) manager.allowsBackgroundLocationUpdates = false manager.pausesLocationUpdatesAutomatically = true #endif manager.stopUpdatingLocation() } } #if os(iOS) public extension LocationServiceCore { func startMonitoringSignificantLocationChanges() { manager.startMonitoringSignificantLocationChanges() } func stopMonitoringSignificantLocationChanges() { manager.stopMonitoringSignificantLocationChanges() } } // MARK: - Heading public extension LocationServiceCore { var heading: CLHeading? { manager.heading } func startUpdatingHeading() { manager.startUpdatingHeading() } func stopUpdatingHeading() { manager.stopUpdatingHeading() } func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { delegate?.locationService(didUpdateHeading: newHeading) } } #endif // MARK: - Delegates extension LocationServiceCore: CLLocationManagerDelegate { public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { guard status != .notDetermined else { return } delegate?.locationService(didChangeAuthorization: isAuthorized) } public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.last else { return } delegate?.locationService(didUpdateLocation: location) } public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { guard let error = error as? CLError else { return } delegate?.locationService(didFailWithError: error) } }
28.801282
117
0.685733
bf9382b6f5f4b6eb88145113c78ddd22b3e0501d
665
import Foundation import CoreGraphics /** Defines 2d cell with `Int` coordinates.*/ public struct Cell { public var x = 0 public var y = 0 public var point: CGPoint { return CGPoint(x: x, y: y) } public init(x: Int, y: Int) { self.x = x self.y = y } public init() {} } extension Cell: CustomStringConvertible { public var description: String { return "(\(x), \(y))" } } extension Cell: Hashable { public var hashValue: Int { return x ^ y } } // MARK: Operators public func == (lhs: Cell, rhs: Cell) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y }
15.113636
47
0.547368
bb867f1e57e6052fbb819c4fa70fae3791f92086
82
import XCTest @testable import Steering final class SteeringTests: XCTestCase {}
16.4
40
0.817073
f73097018b8c3d4dccc4add538de180c79c198af
884
// // DetailTableViewCell.swift // Metal Archives // // Created by Thanh-Nhon Nguyen on 16/03/2019. // Copyright © 2019 Thanh-Nhon Nguyen. All rights reserved. // import UIKit final class DetailTableViewCell: BaseTableViewCell, RegisterableCell { @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var detailLabel: UILabel! override func initAppearance() { super.initAppearance() self.titleLabel.textColor = Settings.currentTheme.secondaryTitleColor self.titleLabel.font = Settings.currentFontSize.secondaryTitleFont self.detailLabel.textColor = Settings.currentTheme.bodyTextColor self.detailLabel.font = Settings.currentFontSize.bodyTextFont } func fill(withTitle title: String, detail: String) { self.titleLabel.text = title self.detailLabel.text = detail } }
30.482759
77
0.716063
d6f9fb4a7bd403c3f2edfc2ac7eb6d9e866969d9
1,645
// // NewsEntity.swift // // Create by 万杰 王 on 12/7/2017 // Copyright © 2017. All rights reserved. // import Foundation import HandyJSON struct NewsEntity: HandyJSON { var errorCode: Int? var reason: String? var result: NewsEntityResult? mutating func mapping(mapper: HelpingMapper) { mapper <<< self.errorCode <-- "error_code" mapper <<< self.reason <-- "reason" mapper <<< self.result <-- "result" } } struct NewsEntityResult: HandyJSON { var data: [NewsEntityData]? var stat: String? mutating func mapping(mapper: HelpingMapper) { mapper <<< self.data <-- "data" mapper <<< self.stat <-- "stat" } } struct NewsEntityData: HandyJSON { var authorName: String? var category: String? var date: String? var thumbnailPicS: String? var thumbnailPicS02: String? var thumbnailPicS03: String? var title: String? var uniquekey: String? var url: String? mutating func mapping(mapper: HelpingMapper) { mapper <<< self.authorName <-- "author_name" mapper <<< self.category <-- "category" mapper <<< self.date <-- "date" mapper <<< self.thumbnailPicS <-- "thumbnail_pic_s" mapper <<< self.thumbnailPicS02 <-- "thumbnail_pic_s02" mapper <<< self.thumbnailPicS03 <-- "thumbnail_pic_s03" mapper <<< self.title <-- "title" mapper <<< self.uniquekey <-- "uniquekey" mapper <<< self.url <-- "url" } }
22.534247
56
0.557447
28d41430209d684713a13597106dee5cb431e25c
32,887
/* * Copyright 2020, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import Logging import NIO import NIOConcurrencyHelpers import NIOHTTP2 internal final class ConnectionManager { internal enum Reconnect { case none case after(TimeInterval) } internal struct ConnectingState { var backoffIterator: ConnectionBackoffIterator? var reconnect: Reconnect var candidate: EventLoopFuture<Channel> var readyChannelMuxPromise: EventLoopPromise<HTTP2StreamMultiplexer> var candidateMuxPromise: EventLoopPromise<HTTP2StreamMultiplexer> } internal struct ConnectedState { var backoffIterator: ConnectionBackoffIterator? var reconnect: Reconnect var candidate: Channel var readyChannelMuxPromise: EventLoopPromise<HTTP2StreamMultiplexer> var multiplexer: HTTP2StreamMultiplexer var error: Error? init(from state: ConnectingState, candidate: Channel, multiplexer: HTTP2StreamMultiplexer) { self.backoffIterator = state.backoffIterator self.reconnect = state.reconnect self.candidate = candidate self.readyChannelMuxPromise = state.readyChannelMuxPromise self.multiplexer = multiplexer } } internal struct ReadyState { var channel: Channel var multiplexer: HTTP2StreamMultiplexer var error: Error? init(from state: ConnectedState) { self.channel = state.candidate self.multiplexer = state.multiplexer } } internal struct TransientFailureState { var backoffIterator: ConnectionBackoffIterator? var readyChannelMuxPromise: EventLoopPromise<HTTP2StreamMultiplexer> var scheduled: Scheduled<Void> var reason: Error? init(from state: ConnectingState, scheduled: Scheduled<Void>, reason: Error) { self.backoffIterator = state.backoffIterator self.readyChannelMuxPromise = state.readyChannelMuxPromise self.scheduled = scheduled self.reason = reason } init(from state: ConnectedState, scheduled: Scheduled<Void>) { self.backoffIterator = state.backoffIterator self.readyChannelMuxPromise = state.readyChannelMuxPromise self.scheduled = scheduled self.reason = state.error } init( from state: ReadyState, scheduled: Scheduled<Void>, backoffIterator: ConnectionBackoffIterator? ) { self.backoffIterator = backoffIterator self.readyChannelMuxPromise = state.channel.eventLoop.makePromise() self.scheduled = scheduled self.reason = state.error } } internal struct ShutdownState { var closeFuture: EventLoopFuture<Void> /// The reason we are shutdown. Any requests for a `Channel` in this state will be failed with /// this error. var reason: Error init(closeFuture: EventLoopFuture<Void>, reason: Error) { self.closeFuture = closeFuture self.reason = reason } static func shutdownByUser(closeFuture: EventLoopFuture<Void>) -> ShutdownState { return ShutdownState( closeFuture: closeFuture, reason: GRPCStatus(code: .unavailable, message: "Connection was shutdown by the user") ) } } internal enum State { /// No `Channel` is required. /// /// Valid next states: /// - `connecting` /// - `shutdown` case idle /// We're actively trying to establish a connection. /// /// Valid next states: /// - `active` /// - `transientFailure` (if our attempt fails and we're going to try again) /// - `shutdown` case connecting(ConnectingState) /// We've established a `Channel`, it might not be suitable (TLS handshake may fail, etc.). /// Our signal to be 'ready' is the initial HTTP/2 SETTINGS frame. /// /// Valid next states: /// - `ready` /// - `transientFailure` (if we our handshake fails or other error happens and we can attempt /// to re-establish the connection) /// - `shutdown` case active(ConnectedState) /// We have an active `Channel` which has seen the initial HTTP/2 SETTINGS frame. We can use /// the channel for making RPCs. /// /// Valid next states: /// - `idle` (we're not serving any RPCs, we can drop the connection for now) /// - `transientFailure` (we encountered an error and will re-establish the connection) /// - `shutdown` case ready(ReadyState) /// A `Channel` is desired, we'll attempt to create one in the future. /// /// Valid next states: /// - `connecting` /// - `shutdown` case transientFailure(TransientFailureState) /// We never want another `Channel`: this state is terminal. case shutdown(ShutdownState) fileprivate var label: String { switch self { case .idle: return "idle" case .connecting: return "connecting" case .active: return "active" case .ready: return "ready" case .transientFailure: return "transientFailure" case .shutdown: return "shutdown" } } } /// The last 'external' state we are in, a subset of the internal state. private var externalState: ConnectivityState = .idle /// Update the external state, potentially notifying a delegate about the change. private func updateExternalState(to nextState: ConnectivityState) { if self.externalState != nextState { let oldState = self.externalState self.externalState = nextState self.connectivityDelegate?.connectionStateDidChange(self, from: oldState, to: nextState) } } /// Our current state. private var state: State { didSet { switch self.state { case .idle: self.updateExternalState(to: .idle) self.updateConnectionID() case .connecting: self.updateExternalState(to: .connecting) // This is an internal state. case .active: () case .ready: self.updateExternalState(to: .ready) case .transientFailure: self.updateExternalState(to: .transientFailure) self.updateConnectionID() case .shutdown: self.updateExternalState(to: .shutdown) } } } /// Returns whether the state is 'idle'. private var isIdle: Bool { self.eventLoop.assertInEventLoop() switch self.state { case .idle: return true case .connecting, .transientFailure, .active, .ready, .shutdown: return false } } /// Returns the `HTTP2StreamMultiplexer` from the 'ready' state or `nil` if it is not available. private var multiplexer: HTTP2StreamMultiplexer? { self.eventLoop.assertInEventLoop() switch self.state { case let .ready(state): return state.multiplexer case .idle, .connecting, .transientFailure, .active, .shutdown: return nil } } /// The `EventLoop` that the managed connection will run on. internal let eventLoop: EventLoop /// A delegate for connectivity changes. Executed on the `EventLoop`. private var connectivityDelegate: ConnectionManagerConnectivityDelegate? /// A delegate for HTTP/2 connection changes. Executed on the `EventLoop`. private var http2Delegate: ConnectionManagerHTTP2Delegate? /// An `EventLoopFuture<Channel>` provider. private let channelProvider: ConnectionManagerChannelProvider /// The behavior for starting a call, i.e. how patient is the caller when asking for a /// multiplexer. private let callStartBehavior: CallStartBehavior.Behavior /// The configuration to use when backing off between connection attempts, if reconnection /// attempts should be made at all. private let connectionBackoff: ConnectionBackoff? /// A logger. internal var logger: Logger private let connectionID: String private var channelNumber: UInt64 private var channelNumberLock = Lock() private var _connectionIDAndNumber: String { return "\(self.connectionID)/\(self.channelNumber)" } private var connectionIDAndNumber: String { return self.channelNumberLock.withLock { return self._connectionIDAndNumber } } private func updateConnectionID() { self.channelNumberLock.withLockVoid { self.channelNumber &+= 1 self.logger[metadataKey: MetadataKey.connectionID] = "\(self._connectionIDAndNumber)" } } internal func appendMetadata(to logger: inout Logger) { logger[metadataKey: MetadataKey.connectionID] = "\(self.connectionIDAndNumber)" } internal convenience init( configuration: ClientConnection.Configuration, channelProvider: ConnectionManagerChannelProvider? = nil, connectivityDelegate: ConnectionManagerConnectivityDelegate?, logger: Logger ) { self.init( eventLoop: configuration.eventLoopGroup.next(), channelProvider: channelProvider ?? DefaultChannelProvider(configuration: configuration), callStartBehavior: configuration.callStartBehavior.wrapped, connectionBackoff: configuration.connectionBackoff, connectivityDelegate: connectivityDelegate, http2Delegate: nil, logger: logger ) } internal init( eventLoop: EventLoop, channelProvider: ConnectionManagerChannelProvider, callStartBehavior: CallStartBehavior.Behavior, connectionBackoff: ConnectionBackoff?, connectivityDelegate: ConnectionManagerConnectivityDelegate?, http2Delegate: ConnectionManagerHTTP2Delegate?, logger: Logger ) { // Setup the logger. var logger = logger let connectionID = UUID().uuidString let channelNumber: UInt64 = 0 logger[metadataKey: MetadataKey.connectionID] = "\(connectionID)/\(channelNumber)" self.eventLoop = eventLoop self.state = .idle self.channelProvider = channelProvider self.callStartBehavior = callStartBehavior self.connectionBackoff = connectionBackoff self.connectivityDelegate = connectivityDelegate self.http2Delegate = http2Delegate self.connectionID = connectionID self.channelNumber = channelNumber self.logger = logger } /// Get the multiplexer from the underlying channel handling gRPC calls. /// if the `ConnectionManager` was configured to be `fastFailure` this will have /// one chance to connect - if not reconnections are managed here. internal func getHTTP2Multiplexer() -> EventLoopFuture<HTTP2StreamMultiplexer> { func getHTTP2Multiplexer0() -> EventLoopFuture<HTTP2StreamMultiplexer> { switch self.callStartBehavior { case .waitsForConnectivity: return self.getHTTP2MultiplexerPatient() case .fastFailure: return self.getHTTP2MultiplexerOptimistic() } } if self.eventLoop.inEventLoop { return getHTTP2Multiplexer0() } else { return self.eventLoop.flatSubmit { getHTTP2Multiplexer0() } } } /// Returns a future for the multiplexer which succeeded when the channel is connected. /// Reconnects are handled if necessary. private func getHTTP2MultiplexerPatient() -> EventLoopFuture<HTTP2StreamMultiplexer> { let multiplexer: EventLoopFuture<HTTP2StreamMultiplexer> switch self.state { case .idle: self.startConnecting() // We started connecting so we must transition to the `connecting` state. guard case let .connecting(connecting) = self.state else { self.invalidState() } multiplexer = connecting.readyChannelMuxPromise.futureResult case let .connecting(state): multiplexer = state.readyChannelMuxPromise.futureResult case let .active(state): multiplexer = state.readyChannelMuxPromise.futureResult case let .ready(state): multiplexer = self.eventLoop.makeSucceededFuture(state.multiplexer) case let .transientFailure(state): multiplexer = state.readyChannelMuxPromise.futureResult case let .shutdown(state): multiplexer = self.eventLoop.makeFailedFuture(state.reason) } self.logger.debug("vending multiplexer future", metadata: [ "connectivity_state": "\(self.state.label)", ]) return multiplexer } /// Returns a future for the current HTTP/2 stream multiplexer, or future HTTP/2 stream multiplexer from the current connection /// attempt, or if the state is 'idle' returns the future for the next connection attempt. /// /// Note: if the state is 'transientFailure' or 'shutdown' then a failed future will be returned. private func getHTTP2MultiplexerOptimistic() -> EventLoopFuture<HTTP2StreamMultiplexer> { // `getHTTP2Multiplexer` makes sure we're on the event loop but let's just be sure. self.eventLoop.preconditionInEventLoop() let muxFuture: EventLoopFuture<HTTP2StreamMultiplexer> = { () in switch self.state { case .idle: self.startConnecting() // We started connecting so we must transition to the `connecting` state. guard case let .connecting(connecting) = self.state else { self.invalidState() } return connecting.candidateMuxPromise.futureResult case let .connecting(state): return state.candidateMuxPromise.futureResult case let .active(active): return self.eventLoop.makeSucceededFuture(active.multiplexer) case let .ready(ready): return self.eventLoop.makeSucceededFuture(ready.multiplexer) case let .transientFailure(state): // Provide the reason we failed transiently, if we can. let error = state.reason ?? GRPCStatus( code: .unavailable, message: "Connection multiplexer requested while backing off" ) return self.eventLoop.makeFailedFuture(error) case let .shutdown(state): return self.eventLoop.makeFailedFuture(state.reason) } }() self.logger.debug("vending fast-failing multiplexer future", metadata: [ "connectivity_state": "\(self.state.label)", ]) return muxFuture } /// Shutdown any connection which exists. This is a request from the application. internal func shutdown() -> EventLoopFuture<Void> { if self.eventLoop.inEventLoop { return self._shutdown() } else { return self.eventLoop.flatSubmit { return self._shutdown() } } } private func _shutdown() -> EventLoopFuture<Void> { self.logger.debug("shutting down connection", metadata: [ "connectivity_state": "\(self.state.label)", ]) let shutdown: ShutdownState switch self.state { // We don't have a channel and we don't want one, easy! case .idle: shutdown = .shutdownByUser(closeFuture: self.eventLoop.makeSucceededFuture(())) self.state = .shutdown(shutdown) // We're mid-connection: the application doesn't have any 'ready' channels so we'll succeed // the shutdown future and deal with any fallout from the connecting channel without the // application knowing. case let .connecting(state): shutdown = .shutdownByUser(closeFuture: self.eventLoop.makeSucceededFuture(())) self.state = .shutdown(shutdown) // Fail the ready channel mux promise: we're shutting down so even if we manage to successfully // connect the application shouldn't have access to the channel or multiplexer. state.readyChannelMuxPromise.fail(GRPCStatus(code: .unavailable, message: nil)) state.candidateMuxPromise.fail(GRPCStatus(code: .unavailable, message: nil)) // In case we do successfully connect, close immediately. state.candidate.whenSuccess { $0.close(mode: .all, promise: nil) } // We have an active channel but the application doesn't know about it yet. We'll do the same // as for `.connecting`. case let .active(state): shutdown = .shutdownByUser(closeFuture: self.eventLoop.makeSucceededFuture(())) self.state = .shutdown(shutdown) // Fail the ready channel mux promise: we're shutting down so even if we manage to successfully // connect the application shouldn't have access to the channel or multiplexer. state.readyChannelMuxPromise.fail(GRPCStatus(code: .unavailable, message: nil)) // We have a channel, close it. state.candidate.close(mode: .all, promise: nil) // The channel is up and running: the application could be using it. We can close it and // return the `closeFuture`. case let .ready(state): shutdown = .shutdownByUser(closeFuture: state.channel.closeFuture) self.state = .shutdown(shutdown) // We have a channel, close it. state.channel.close(mode: .all, promise: nil) // Like `.connecting` and `.active` the application does not have a `.ready` channel. We'll // do the same but also cancel any scheduled connection attempts and deal with any fallout // if we cancelled too late. case let .transientFailure(state): shutdown = .shutdownByUser(closeFuture: self.eventLoop.makeSucceededFuture(())) self.state = .shutdown(shutdown) // Stop the creation of a new channel, if we can. If we can't then the task to // `startConnecting()` will see our new `shutdown` state and ignore the request to connect. state.scheduled.cancel() // Fail the ready channel mux promise: we're shutting down so even if we manage to successfully // connect the application shouldn't should have access to the channel. state.readyChannelMuxPromise.fail(shutdown.reason) // We're already shutdown; nothing to do. case let .shutdown(state): shutdown = state } return shutdown.closeFuture } // MARK: - State changes from the channel handler. /// The channel caught an error. Hold on to it until the channel becomes inactive, it may provide /// some context. internal func channelError(_ error: Error) { self.eventLoop.preconditionInEventLoop() switch self.state { // Hitting an error in idle is a surprise, but not really something we do anything about. Either the // error is channel fatal, in which case we'll see channelInactive soon (acceptable), or it's not, // and future I/O will either fail fast or work. In either case, all we do is log this and move on. case .idle: self.logger.warning("ignoring unexpected error in idle", metadata: [ MetadataKey.error: "\(error)", ]) case .connecting: self.invalidState() case var .active(state): state.error = error self.state = .active(state) case var .ready(state): state.error = error self.state = .ready(state) // If we've already in one of these states, then additional errors aren't helpful to us. case .transientFailure, .shutdown: () } } /// The connecting channel became `active`. Must be called on the `EventLoop`. internal func channelActive(channel: Channel, multiplexer: HTTP2StreamMultiplexer) { self.eventLoop.preconditionInEventLoop() self.logger.debug("activating connection", metadata: [ "connectivity_state": "\(self.state.label)", ]) switch self.state { case let .connecting(connecting): let connected = ConnectedState(from: connecting, candidate: channel, multiplexer: multiplexer) self.state = .active(connected) // Optimistic connections are happy this this level of setup. connecting.candidateMuxPromise.succeed(multiplexer) // Application called shutdown before the channel become active; we should close it. case .shutdown: channel.close(mode: .all, promise: nil) // These cases are purposefully separated: some crash reporting services provide stack traces // which don't include the precondition failure message (which contain the invalid state we were // in). Keeping the cases separate allows us work out the state from the line number. case .idle: self.invalidState() case .active: self.invalidState() case .ready: self.invalidState() case .transientFailure: self.invalidState() } } /// An established channel (i.e. `active` or `ready`) has become inactive: should we reconnect? /// Must be called on the `EventLoop`. internal func channelInactive() { self.eventLoop.preconditionInEventLoop() self.logger.debug("deactivating connection", metadata: [ "connectivity_state": "\(self.state.label)", ]) switch self.state { // The channel is `active` but not `ready`. Should we try again? case let .active(active): let error = GRPCStatus( code: .unavailable, message: "The connection was dropped and connection re-establishment is disabled" ) switch active.reconnect { // No, shutdown instead. case .none: self.logger.debug("shutting down connection") let shutdownState = ShutdownState( closeFuture: self.eventLoop.makeSucceededFuture(()), reason: error ) self.state = .shutdown(shutdownState) active.readyChannelMuxPromise.fail(error) // Yes, after some time. case let .after(delay): let scheduled = self.eventLoop.scheduleTask(in: .seconds(timeInterval: delay)) { self.startConnecting() } self.logger.debug("scheduling connection attempt", metadata: ["delay_secs": "\(delay)"]) self.state = .transientFailure(TransientFailureState(from: active, scheduled: scheduled)) } // The channel was ready and working fine but something went wrong. Should we try to replace // the channel? case let .ready(ready): // No, no backoff is configured. if self.connectionBackoff == nil { self.logger.debug("shutting down connection, no reconnect configured/remaining") self.state = .shutdown( ShutdownState( closeFuture: ready.channel.closeFuture, reason: GRPCStatus( code: .unavailable, message: "The connection was dropped and a reconnect was not configured" ) ) ) } else { // Yes, start connecting now. We should go via `transientFailure`, however. let scheduled = self.eventLoop.scheduleTask(in: .nanoseconds(0)) { self.startConnecting() } self.logger.debug("scheduling connection attempt", metadata: ["delay": "0"]) let backoffIterator = self.connectionBackoff?.makeIterator() self.state = .transientFailure(TransientFailureState( from: ready, scheduled: scheduled, backoffIterator: backoffIterator )) } // This is fine: we expect the channel to become inactive after becoming idle. case .idle: () // We're already shutdown, that's fine. case .shutdown: () // These cases are purposefully separated: some crash reporting services provide stack traces // which don't include the precondition failure message (which contain the invalid state we were // in). Keeping the cases separate allows us work out the state from the line number. case .connecting: self.invalidState() case .transientFailure: self.invalidState() } } /// The channel has become ready, that is, it has seen the initial HTTP/2 SETTINGS frame. Must be /// called on the `EventLoop`. internal func ready() { self.eventLoop.preconditionInEventLoop() self.logger.debug("connection ready", metadata: [ "connectivity_state": "\(self.state.label)", ]) switch self.state { case let .active(connected): self.state = .ready(ReadyState(from: connected)) connected.readyChannelMuxPromise.succeed(connected.multiplexer) case .shutdown: () // These cases are purposefully separated: some crash reporting services provide stack traces // which don't include the precondition failure message (which contain the invalid state we were // in). Keeping the cases separate allows us work out the state from the line number. case .idle: self.invalidState() case .transientFailure: self.invalidState() case .connecting: self.invalidState() case .ready: self.invalidState() } } /// No active RPCs are happening on 'ready' channel: close the channel for now. Must be called on /// the `EventLoop`. internal func idle() { self.eventLoop.preconditionInEventLoop() self.logger.debug("idling connection", metadata: [ "connectivity_state": "\(self.state.label)", ]) switch self.state { case let .active(state): // This state is reachable if the keepalive timer fires before we reach the ready state. self.state = .idle state.readyChannelMuxPromise .fail(GRPCStatus(code: .unavailable, message: "Idled before reaching ready state")) case .ready: self.state = .idle case .shutdown: // This is expected when the connection is closed by the user: when the channel becomes // inactive and there are no outstanding RPCs, 'idle()' will be called instead of // 'channelInactive()'. () // These cases are purposefully separated: some crash reporting services provide stack traces // which don't include the precondition failure message (which contain the invalid state we were // in). Keeping the cases separate allows us work out the state from the line number. case .idle: self.invalidState() case .connecting: self.invalidState() case .transientFailure: self.invalidState() } } internal func streamClosed() { self.eventLoop.assertInEventLoop() self.http2Delegate?.streamClosed(self) } internal func maxConcurrentStreamsChanged(_ maxConcurrentStreams: Int) { self.eventLoop.assertInEventLoop() self.http2Delegate?.receivedSettingsMaxConcurrentStreams( self, maxConcurrentStreams: maxConcurrentStreams ) } /// The connection has started quiescing: notify the connectivity monitor of this. internal func beginQuiescing() { self.eventLoop.assertInEventLoop() self.connectivityDelegate?.connectionIsQuiescing(self) } } extension ConnectionManager { // A connection attempt failed; we never established a connection. private func connectionFailed(withError error: Error) { self.eventLoop.preconditionInEventLoop() switch self.state { case let .connecting(connecting): // Should we reconnect? switch connecting.reconnect { // No, shutdown. case .none: self.logger.debug("shutting down connection, no reconnect configured/remaining") self.state = .shutdown( ShutdownState(closeFuture: self.eventLoop.makeSucceededFuture(()), reason: error) ) connecting.readyChannelMuxPromise.fail(error) connecting.candidateMuxPromise.fail(error) // Yes, after a delay. case let .after(delay): self.logger.debug("scheduling connection attempt", metadata: ["delay": "\(delay)"]) let scheduled = self.eventLoop.scheduleTask(in: .seconds(timeInterval: delay)) { self.startConnecting() } self.state = .transientFailure( TransientFailureState(from: connecting, scheduled: scheduled, reason: error) ) // Candidate mux users are not willing to wait. connecting.candidateMuxPromise.fail(error) } // The application must have called shutdown while we were trying to establish a connection // which was doomed to fail anyway. That's fine, we can ignore this. case .shutdown: () // We can't fail to connect if we aren't trying. // // These cases are purposefully separated: some crash reporting services provide stack traces // which don't include the precondition failure message (which contain the invalid state we were // in). Keeping the cases separate allows us work out the state from the line number. case .idle: self.invalidState() case .active: self.invalidState() case .ready: self.invalidState() case .transientFailure: self.invalidState() } } } extension ConnectionManager { // Start establishing a connection: we can only do this from the `idle` and `transientFailure` // states. Must be called on the `EventLoop`. private func startConnecting() { self.eventLoop.assertInEventLoop() switch self.state { case .idle: let iterator = self.connectionBackoff?.makeIterator() self.startConnecting( backoffIterator: iterator, muxPromise: self.eventLoop.makePromise() ) case let .transientFailure(pending): self.startConnecting( backoffIterator: pending.backoffIterator, muxPromise: pending.readyChannelMuxPromise ) // We shutdown before a scheduled connection attempt had started. case .shutdown: () // These cases are purposefully separated: some crash reporting services provide stack traces // which don't include the precondition failure message (which contain the invalid state we were // in). Keeping the cases separate allows us work out the state from the line number. case .connecting: self.invalidState() case .active: self.invalidState() case .ready: self.invalidState() } } private func startConnecting( backoffIterator: ConnectionBackoffIterator?, muxPromise: EventLoopPromise<HTTP2StreamMultiplexer> ) { let timeoutAndBackoff = backoffIterator?.next() // We're already on the event loop: submit the connect so it starts after we've made the // state change to `.connecting`. self.eventLoop.assertInEventLoop() let candidate: EventLoopFuture<Channel> = self.eventLoop.flatSubmit { let channel: EventLoopFuture<Channel> = self.channelProvider.makeChannel( managedBy: self, onEventLoop: self.eventLoop, connectTimeout: timeoutAndBackoff.map { .seconds(timeInterval: $0.timeout) }, logger: self.logger ) channel.whenFailure { error in self.connectionFailed(withError: error) } return channel } // Should we reconnect if the candidate channel fails? let reconnect: Reconnect = timeoutAndBackoff.map { .after($0.backoff) } ?? .none let connecting = ConnectingState( backoffIterator: backoffIterator, reconnect: reconnect, candidate: candidate, readyChannelMuxPromise: muxPromise, candidateMuxPromise: self.eventLoop.makePromise() ) self.state = .connecting(connecting) } } extension ConnectionManager { /// Returns a synchronous view of the connection manager; each operation requires the caller to be /// executing on the same `EventLoop` as the connection manager. internal var sync: Sync { return Sync(self) } internal struct Sync { private let manager: ConnectionManager fileprivate init(_ manager: ConnectionManager) { self.manager = manager } /// A delegate for connectivity changes. internal var connectivityDelegate: ConnectionManagerConnectivityDelegate? { get { self.manager.eventLoop.assertInEventLoop() return self.manager.connectivityDelegate } nonmutating set { self.manager.eventLoop.assertInEventLoop() self.manager.connectivityDelegate = newValue } } /// A delegate for HTTP/2 connection changes. internal var http2Delegate: ConnectionManagerHTTP2Delegate? { get { self.manager.eventLoop.assertInEventLoop() return self.manager.http2Delegate } nonmutating set { self.manager.eventLoop.assertInEventLoop() self.manager.http2Delegate = newValue } } /// Returns `true` if the connection is in the idle state. internal var isIdle: Bool { return self.manager.isIdle } /// Returns the `multiplexer` from a connection in the `ready` state or `nil` if it is any /// other state. internal var multiplexer: HTTP2StreamMultiplexer? { return self.manager.multiplexer } // Start establishing a connection. Must only be called when `isIdle` is `true`. internal func startConnecting() { self.manager.startConnecting() } } } extension ConnectionManager { private func invalidState( function: StaticString = #function, file: StaticString = #file, line: UInt = #line ) -> Never { preconditionFailure("Invalid state \(self.state) for \(function)", file: file, line: line) } }
34.293014
129
0.690455
0a56625836a8d6e4974c9dfdc340c210f1e53af6
501
// // HomeTableViewCell.swift // MAP_Final // // Created by RahulKumar Gaddam on 12/8/15. // Copyright © 2015 RahulKumar Gaddam. All rights reserved. // import UIKit class HomeTableViewCell: UITableViewCell { 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 } }
20.04
63
0.674651
f4365e5e8ecae57f392cdb3405d671447b7a6a6f
1,828
// // RequestHandler.swift // TemplateProject // // Created by Benoit PASQUIER on 13/01/2018. // Copyright © 2018 Benoit PASQUIER. All rights reserved. // import Foundation class RequestHandler { func networkResult<T: Parceable>(completion: @escaping ((Result<[T], ErrorResult>) -> Void)) -> ((Result<Data, ErrorResult>) -> Void) { return { dataResult in DispatchQueue.global(qos: .background).async(execute: { switch dataResult { case .success(let data) : ParserHelper.parse(data: data, completion: completion) break case .failure(let error) : print("Network error \(error)") completion(.failure(.network(string: "Network error " + error.localizedDescription))) break } }) } } func networkResult<T: Parceable>(completion: @escaping ((Result<T, ErrorResult>) -> Void)) -> ((Result<Data, ErrorResult>) -> Void) { return { dataResult in DispatchQueue.global(qos: .background).async(execute: { switch dataResult { case .success(let data) : ParserHelper.parse(data: data, completion: completion) break case .failure(let error) : print("Network error \(error)") completion(.failure(.network(string: "Network error " + error.localizedDescription))) break } }) } } }
33.236364
109
0.463895
eb0d69468816949c53c67bda5dd6738dbb9a468f
509
// // ViewController.swift // PrettyMesh // // Created by Cannon Biggs on 10/12/16. // Copyright © 2016 Cannon Biggs. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.576923
80
0.669941
62cbc5f592b14011b8b8f31a21a34a2efa85a550
1,183
// // // Copyright © 2020 Karhoo. All rights reserved. // import Foundation final class KarhooPasswordResetInteractor: PasswordResetInteractor { private var email: String? private let requestSender: RequestSender init(requestSender: RequestSender = KarhooRequestSender(httpClient: JsonHttpClient.shared)) { self.requestSender = requestSender } func set(email: String) { self.email = email } func execute<T: KarhooCodableModel>(callback: @escaping CallbackClosure<T>) { guard let email = self.email else { return } requestSender.request(payload: PasswordResetRequestPayload(email: email), endpoint: .passwordReset, callback: { result in guard result.successValue(orErrorCallback: callback) != nil, let success = KarhooVoid() as? T else { return } callback(.success(result: success)) }) } func cancel() { requestSender.cancelNetworkRequest() } }
28.853659
97
0.557904
21b672be7a69b9b72c9cc01f110fc575bc8671f0
633
import SpriteKit var bombArray = Array<SKTexture>(); class Powerup: Sprite { init(x: CGFloat, y: CGFloat) { super.init(named: "powerup1", x: x, y: y) self.name = "powerup" self.setScale(1.5) self.alpha = 0 fire() } func fire() { for index in 1 ... 15 { bombArray.append(SKTexture(imageNamed: "powerup\(index)")) } let animateAction = SKAction.animate(with: bombArray, timePerFrame: 0.10); self.run(SKAction.repeatForever(animateAction)) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
24.346154
82
0.582938
f5c7b1ee92f14a24a63da47897a7112c1260f945
813
// swift-tools-version:4.0 import PackageDescription let package = Package( name: "microposter", dependencies: [ // 💧 A server-side Swift web framework. .package(url: "https://github.com/vapor/vapor.git", from: "3.0.0-rc"), // 🔵 Swift ORM (queries, models, relations, etc) built on SQLite 3. .package(url: "https://github.com/vapor/fluent-sqlite.git", from: "3.0.0-rc"), .package(url: "https://github.com/vapor/leaf.git", from: "3.0.0-rc.1"), .package(url: "https://github.com/vapor/auth.git", from: "2.0.0-rc") ], targets: [ .target(name: "App", dependencies: ["FluentSQLite", "Vapor", "Leaf", "Authentication"]), .target(name: "Run", dependencies: ["App"]), .testTarget(name: "AppTests", dependencies: ["App"]), ] )
36.954545
96
0.595326
cc795966c6b4ede48923b629f140c65c86629a45
1,973
/// Copyright (c) 2019 Razeware LLC /// /// 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. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import SwiftUI enum WeeklyWeatherBuilder{ static func makeCurrentWeatherView( withCity city: String, weatherFetcher:WeatherFetchable)-> some View{ let viewModel=CurrentWeatherViewModel(city: city, weatherFetcher: weatherFetcher) return CurrentWeatherView(viewModel:viewModel) } }
50.589744
83
0.75925
5b73a86a66b10abfec3f663d8a3985363ce1dff3
3,163
import Foundation import LocalAuthentication @objc(Fingerprint) class Fingerprint : CDVPlugin { @objc(isAvailable:) func isAvailable(_ command: CDVInvokedUrlCommand){ let authenticationContext = LAContext(); var biometryType = "finger"; var error:NSError?; let policy:LAPolicy = .deviceOwnerAuthenticationWithBiometrics; let available = authenticationContext.canEvaluatePolicy(policy, error: &error); if(error != nil){ biometryType = "none"; } var pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: "\(String(describing: error?.localizedDescription))"); if available == true { if #available(iOS 11.0, *) { switch(authenticationContext.biometryType) { case .none: biometryType = "none"; case .touchID: biometryType = "finger"; case .faceID: biometryType = "face" } } pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: biometryType); } commandDelegate.send(pluginResult, callbackId:command.callbackId); } @objc(authenticate:) func authenticate(_ command: CDVInvokedUrlCommand){ let authenticationContext = LAContext(); var pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: "Something went wrong"); var reason = "Authentication"; var policy:LAPolicy = .deviceOwnerAuthentication; let data = command.arguments[0] as AnyObject?; if let disableBackup = data?["disableBackup"] as! Bool? { if disableBackup { authenticationContext.localizedFallbackTitle = ""; policy = .deviceOwnerAuthenticationWithBiometrics; } else { if let localizedFallbackTitle = data?["localizedFallbackTitle"] as! String? { authenticationContext.localizedFallbackTitle = localizedFallbackTitle; } } } // Localized reason if let localizedReason = data?["localizedReason"] as! String? { reason = localizedReason; }else if let clientId = data?["clientId"] as! String? { reason = clientId; } authenticationContext.evaluatePolicy( policy, localizedReason: reason, reply: { [unowned self] (success, error) -> Void in if( success ) { pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: "Success"); }else { // Check if there is an error if error != nil { pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: "Error: \(String(describing: error?.localizedDescription))") } } self.commandDelegate.send(pluginResult, callbackId:command.callbackId); }); } override func pluginInitialize() { super.pluginInitialize() } }
36.77907
158
0.588049
e4810c8b1f8d5bc60386fbbaa1979f1ec20b6af6
211
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct B<T where g: T var d = 0 let h = B
26.375
87
0.739336
e2f2b7b3fc685535b983577c28226051ecf010f9
1,646
// // Copyright Amazon.com Inc. or its affiliates. // All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import XCTest import Speech import Amplify @testable import CoreMLPredictionsPlugin class CoreMLSpeechAdapterTests: XCTestCase { var coreMLSpeechAdapter: MockCoreMLSpeechAdapter! override func setUp() { coreMLSpeechAdapter = MockCoreMLSpeechAdapter() } func testTranscriptionResponseNil() { let testBundle = Bundle(for: type(of: self)) guard let url = testBundle.url(forResource: "audio", withExtension: "wav") else { return } coreMLSpeechAdapter.setResponse(result: nil) let callbackExpectation = expectation(description: "callback reached") coreMLSpeechAdapter.getTranscription(url) { result in XCTAssertNil(result) callbackExpectation.fulfill() } waitForExpectations(timeout: 180) } func testTranscriptionResponse() { let testBundle = Bundle(for: type(of: self)) guard let url = testBundle.url(forResource: "audio", withExtension: "wav") else { return } let mockResult = SpeechToTextResult(transcription: "This is a test") coreMLSpeechAdapter.setResponse(result: mockResult) let callbackExpectation = expectation(description: "callback reached") coreMLSpeechAdapter.getTranscription(url) { result in XCTAssertNotNil(result) XCTAssertEqual(result?.transcription, mockResult.transcription) callbackExpectation.fulfill() } waitForExpectations(timeout: 180) } }
31.056604
89
0.67497
abc0aa99acd44c3a04bbc540dffe906b2c7c8d4e
1,453
/** * Copyright IBM Corporation 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 /** KeywordResult. */ public struct KeywordResult: Decodable { /** A specified keyword normalized to the spoken phrase that matched in the audio input. */ public var normalizedText: String /** The start time in seconds of the keyword match. */ public var startTime: Double /** The end time in seconds of the keyword match. */ public var endTime: Double /** A confidence score for the keyword match in the range of 0.0 to 1.0. */ public var confidence: Double // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case normalizedText = "normalized_text" case startTime = "start_time" case endTime = "end_time" case confidence = "confidence" } }
28.490196
89
0.686855
fb812777dfcc80589492fe66acd3b74f57bd614d
1,138
// // Response.swift // QSNetwork // // Created by Nory Cao on 16/12/26. // Copyright © 2016年 QS. All rights reserved. // import UIKit open class QSResponse: NSObject { public var request:URLRequest? { return task?.originalRequest } public var response:URLResponse? public var data:Data? public var error:Error? public var task:URLSessionTask? public var encoding = String.Encoding.utf8 public var json:AnyObject? public var JSONReadingOptions = JSONSerialization.ReadingOptions(rawValue: 0) init(data:Data?,response:URLResponse?,error:Error?,task:URLSessionTask?) { super.init() self.data = data self.response = response self.error = error self.task = task jsonT() } func jsonT() -> Void { do{ if let jsonData = self.data { let jsonDict:AnyObject? = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as AnyObject if let jsonD = jsonDict { self.json = jsonD } } }catch{ } } }
27.095238
130
0.59754
20f451c71f06cf5c30ed6cd77be0fa0afd2455ac
6,735
// // AppDelegate.swift // iStackOS // // Created by Marsal on 12/03/16. // Copyright © 2016 Marsal Silveira. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { // ****************************** // // MARK: Properties // ****************************** // var window: UIWindow? // ****************************** // // MARK: Singleton // ****************************** // class func shareInstance() -> AppDelegate { return UIApplication.sharedApplication().delegate as! AppDelegate } // ****************************** // // MARK: UIApplicationDelegate // ****************************** // func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // ****************************** // // MARK: Core Data stack // ****************************** // lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "br.com.marsal.silveira.iStackOS" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("iStackOS", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // ****************************** // // MARK: Core Data Saving support // ****************************** // func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
51.022727
291
0.673348
62dffb47f1243ae1be6fff073b789626bf375557
5,950
/* Copyright (c) 2014-2017 Pixelspark, Tommy van der Vorst Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation /** Column represents a column (identifier) in a Dataset dataset. Column names in Dataset are case-insensitive when compared, but do retain case. There cannot be two or more columns in a Dataset dataset that are equal to each other when compared case-insensitively. */ public struct Column: ExpressibleByStringLiteral, Hashable, CustomDebugStringConvertible { public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType public typealias UnicodeScalarLiteralType = StringLiteralType public let name: String public init(_ name: String) { self.name = name } public init(stringLiteral value: StringLiteralType) { self.name = value } public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { self.name = value } public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { self.name = value } public func hash(into: inout Hasher) { self.name.lowercased().hash(into: &into) } public var debugDescription: String { get { return "Column(\(name))" } } /** Returns a new, unique name for the next column given a set of existing columns. */ public static func defaultNameForNewColumn(_ existing: OrderedSet<Column>) -> Column { var index = existing.count while true { let newName = Column.defaultNameForIndex(index) if !existing.contains(newName) { return newName } index = index + 1 } } /** Return a generated column name for a column at a given index (starting at 0). Note: do not use to generate the name of a column that is to be added to an existing set (column names must be unique). Use defaultNameForNewColumn to generate a new, unique name. */ public static func defaultNameForIndex(_ index: Int) -> Column { var myIndex = index let x = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] var str: String = "" repeat { let i = ((myIndex) % 26) str = x[i] + str myIndex -= i myIndex /= 26 } while myIndex > 0 return Column(str) } public func newName(_ accept: (Column) -> Bool) -> Column { var i = 0 repeat { let newName = Column("\(self.name)_\(Column.defaultNameForIndex(i).name)") let accepted = accept(newName) if accepted { return newName } i += 1 } while true } } /** Description of a dataset's format (column names primarily). */ public struct Schema: Codeable { public let pasteboardName = "nl.pixelspark.Warp.Schema" /** The columns present in this data set. To change, call `change`. */ public private(set) var columns: OrderedSet<Column> /** The set of columns using which rows can uniquely be identified in this data set. This set of columns can be used to perform updates on specific rows. If the data set does not support or have a primary key, this may be nil. In this case, users must choose their own keys (e.g. by asking the user) or use row numbers (e.g. with the .edit data mutation if that is supported) when mutating data. */ public private(set) var identifier: Set<Column>? public init(columns: OrderedSet<Column>, identifier: Set<Column>?) { self.columns = columns self.identifier = identifier } public init?(coder aDecoder: NSCoder) { self.columns = OrderedSet<Column>((aDecoder.decodeObject(forKey: "columns") as? [String] ?? []).map { return Column($0) }) if aDecoder.containsValue(forKey: "identifier") { self.identifier = Set<Column>((aDecoder.decodeObject(forKey: "identifier") as? [String] ?? []).map { return Column($0) }) } else { self.identifier = nil } } public func encode(with aCoder: NSCoder) { aCoder.encode(self.columns.map { return $0.name }, forKey: "columns") aCoder.encode(self.identifier?.map { return $0.name }, forKey: "identifier") } /** Changes the set of columns in this schema to match the given set of columns. If colunns are used as keys or in indexes, those keys or indexes are removed automatically. New keys or indexes are not created automatically. */ public mutating func change(columns newColumns: OrderedSet<Column>) { let removed = self.columns.subtracting(Set(newColumns)) self.columns = newColumns if let id = self.identifier { self.identifier = id.subtracting(removed) } } /** Change the set of columns used as identifier in this schema. All columns listed in the identifier must exist (e.g. they must be in the `columns` set). If this is not the case, the method will cause a fatal error. */ public mutating func change(identifier newIdentifier: Set<Column>?) { if let ni = newIdentifier { precondition(ni.subtracting(self.columns).isEmpty, "Cannot set identifier, it contains columns that do not exist") self.identifier = ni } else { self.identifier = nil } } public mutating func remove(columns: Set<Column>) { self.change(columns: self.columns.subtracting(columns)) } }
39.403974
124
0.727563
4a1e4c84daa7fe77e14bc05181d4952b2f837ed5
5,365
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// public typealias CodeActionProviderCompletion = (LSPResult<[CodeAction]>) -> Void public typealias CodeActionProvider = (CodeActionRequest, @escaping CodeActionProviderCompletion) -> Void /// Request for returning all possible code actions for a given text document and range. /// /// The code action request is sent from the client to the server to compute commands for a given text /// document and range. These commands are typically code fixes to either fix problems or to beautify/ /// refactor code. /// /// Servers that provide code actions should set the `codeActions` server capability. /// /// - Parameters: /// - textDocument: The document in which the command was invoked. /// - range: The specific range inside the document to search for code actions. /// - context: The context of the request. /// /// - Returns: A list of code actions for the given range and context. public struct CodeActionRequest: TextDocumentRequest, Hashable { public static let method: String = "textDocument/codeAction" public typealias Response = CodeActionRequestResponse? /// The range for which the command was invoked. @CustomCodable<PositionRange> public var range: Range<Position> /// Context carrying additional information. public var context: CodeActionContext /// The document in which the command was invoked. public var textDocument: TextDocumentIdentifier public init(range: Range<Position>, context: CodeActionContext, textDocument: TextDocumentIdentifier) { self._range = CustomCodable<PositionRange>(wrappedValue: range) self.context = context self.textDocument = textDocument } } /// Wrapper type for the response of a CodeAction request. /// If the client supports CodeAction literals, the encoded type will be the CodeAction array itself. /// Otherwise, the encoded value will be an array of CodeActions' inner Command structs. public enum CodeActionRequestResponse: ResponseType, Codable, Equatable { case codeActions([CodeAction]) case commands([Command]) public init(codeActions: [CodeAction], clientCapabilities: TextDocumentClientCapabilities.CodeAction?) { if let literalSupport = clientCapabilities?.codeActionLiteralSupport { let supportedKinds = literalSupport.codeActionKind.valueSet self = .codeActions(codeActions.filter { if let kind = $0.kind { return supportedKinds.contains(kind) } else { // The client guarantees that unsupported kinds will be treated, // so it's probably safe to include unspecified kinds into the result. return true } }) } else { self = .commands(codeActions.compactMap { $0.command }) } } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let codeActions = try? container.decode([CodeAction].self) { self = .codeActions(codeActions) } else if let commands = try? container.decode([Command].self) { self = .commands(commands) } else { let error = "CodeActionRequestResponse has neither a CodeAction or a Command." throw DecodingError.dataCorruptedError(in: container, debugDescription: error) } } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .codeActions(let codeActions): try container.encode(codeActions) case .commands(let commands): try container.encode(commands) } } } public struct CodeActionContext: Codable, Hashable { /// An array of diagnostics. public var diagnostics: [Diagnostic] /// Requested kind of actions to return. /// If provided, actions of these kinds are filtered out by the client before being shown, /// so servers can omit computing them. public var only: [CodeActionKind]? public init(diagnostics: [Diagnostic] = [], only: [CodeActionKind]? = nil) { self.diagnostics = diagnostics self.only = only } } public struct CodeAction: Codable, Equatable, ResponseType { /// A short, human-readable, title for this code action. public var title: String /// The kind of the code action. public var kind: CodeActionKind? /// The diagnostics that this code action resolves, if applicable. public var diagnostics: [Diagnostic]? /// The workspace edit this code action performs. public var edit: WorkspaceEdit? /// A command this code action executes. /// If a code action provides an edit and a command, /// first the edit is executed and then the command. public var command: Command? public init(title: String, kind: CodeActionKind? = nil, diagnostics: [Diagnostic]? = nil, edit: WorkspaceEdit? = nil, command: Command? = nil) { self.title = title self.kind = kind self.diagnostics = diagnostics self.edit = edit self.command = command } }
38.049645
146
0.701957
295b6961d3f061b3cf51f641e47879b6a4103491
150
// // SSRTheme.swift // SSRSwift // // Created by shendong on 2019/6/28. // Copyright © 2019 Don.shen. All rights reserved. // import Foundation
15
51
0.666667
1c27adbdde341d55c6cee485596d7b7f53cd1df1
1,788
import Foundation /// The log level. /// /// Log levels are ordered by their severity, with `.trace` being the least severe and /// `.critical` being the most severe. public enum Level: String, Codable, CaseIterable { /// Appropriate for messages that contain information normally of use only when /// tracing the execution of a program. case trace /// Appropriate for messages that contain information normally of use only when /// debugging a program. case debug /// Appropriate for informational messages. case info /// Appropriate for conditions that are not error conditions, but that may require /// special handling. case notice /// Appropriate for messages that are not error conditions, but more severe than /// `.notice`. case warning /// Appropriate for error conditions. case error /// Appropriate for critical error conditions that usually require immediate /// attention. /// /// When a `critical` message is logged, the logging backend (`LogHandler`) is free to perform /// more heavy-weight operations to capture system state (such as capturing stack traces) to facilitate /// debugging. case critical } extension Level { internal var naturalIntegralValue: Int { switch self { case .trace: return 0 case .debug: return 1 case .info: return 2 case .notice: return 3 case .warning: return 4 case .error: return 5 case .critical: return 6 } } } extension Level: Comparable { public static func < (lhs: Level, rhs: Level) -> Bool { return lhs.naturalIntegralValue < rhs.naturalIntegralValue } }
27.507692
107
0.637025
bb8820c921debadc170c4a8e14093d9f639a4397
1,306
// // DMXpT.swift // // Created by Philip DesJean on 9/11/16 // Copyright (c) . All rights reserved. // import Foundation import SwiftyJSON open class DMXpT: NSObject, NSCoding { // MARK: Declaration for string constants to be used to decode and also serialize. // MARK: Properties // MARK: SwiftyJSON Initalizers /** Initates the class based on the object - parameter object: The object of either Dictionary or Array kind that was passed. - returns: An initalized instance of the class. */ convenience public init(object: AnyObject) { self.init(json: JSON(object)) } /** Initates the class based on the JSON that was passed. - parameter json: JSON object from SwiftyJSON. - returns: An initalized instance of the class. */ public init(json: JSON) { } /** Generates description of the object in the form of a NSDictionary. - returns: A Key value pair containing all valid values in the object. */ open func dictionaryRepresentation() -> [String : AnyObject ] { let dictionary: [String : AnyObject ] = [ : ] return dictionary } // MARK: NSCoding Protocol required public init(coder aDecoder: NSCoder) { } open func encode(with aCoder: NSCoder) { } }
21.766667
86
0.650842
237134ba63e1d6cd2085cda6743424a7e80fc8cb
6,641
// // SCNetworkManager+extension.swift // WowLittleHelper // // Created by Stephen Cao on 15/5/19. // Copyright © 2019 Stephen Cao. All rights reserved. // import Foundation import Alamofire import SVProgressHUD extension SCNetworkManager{ func getCardsData(completion:@escaping (_ dict: [String: Any]?,_ isSuccess: Bool)->()){ let urlString = "https://api.clashroyale.com/v1/cards" let params = ["authorization": "Bearer \(HelperCommon.apiKey)"] request(urlString: urlString, method: HTTPMethod.get, params: params) { (res, isSuccess, _, _) in let dict = res as? [String: Any] completion(dict, isSuccess) } } func getCardImage(imageUrlString: String, completion:@escaping (_ image: UIImage?)->()){ guard let url = URL(string: imageUrlString) else{ completion(nil) return } UIImage.downloadImage(url: url) { (image) in completion(image) } } func getClanBadgeImage(badgeId: String, completion:@escaping (_ image: UIImage?)->()){ let urlString = "https://cdn.statsroyale.com/images/badges/\(badgeId).png" guard let url = URL(string: urlString) else{ completion(nil) return } UIImage.downloadImage(url: url) { (image) in completion(image) } } } extension SCNetworkManager{ func getTournamentsData(name: String, completion:@escaping (_ dict: [String: Any]?,_ isSuccess: Bool)->()){ let urlString = "https://api.clashroyale.com/v1/tournaments" let params = ["authorization": "Bearer \(HelperCommon.apiKey)", "name": name] request(urlString: urlString, method: HTTPMethod.get, params: params) { (res, isSuccess, _, _) in let dict = res as? [String: Any] completion(dict, isSuccess) } } func getTournamentDetailsData(tag: String, completion:@escaping (_ dict: [String: Any]?,_ isSuccess: Bool)->()){ let urlString = "https://api.clashroyale.com/v1/tournaments/\((tag as NSString).replacingOccurrences(of: "#", with: "%23"))" let params = ["authorization": "Bearer \(HelperCommon.apiKey)"] request(urlString: urlString, method: HTTPMethod.get, params: params) { (res, isSuccess, _, _) in let dict = res as? [String: Any] completion(dict, isSuccess) } } } extension SCNetworkManager{ func getPlayerData(tag: String, completion:@escaping (_ dict: [String: Any]?,_ isSuccess: Bool)->()){ let urlString = "https://api.clashroyale.com/v1/players/\((tag as NSString).replacingOccurrences(of: "#", with: "%23"))" let params = ["authorization": "Bearer \(HelperCommon.apiKey)"] request(urlString: urlString, method: HTTPMethod.get, params: params) { (res, isSuccess, _, _) in let dict = res as? [String: Any] completion(dict, isSuccess) } } func getPlayerChest(tag: String, completion:@escaping (_ dict: [String: Any]?,_ isSuccess: Bool)->()){ let urlString = "https://api.clashroyale.com/v1/players/\((tag as NSString).replacingOccurrences(of: "#", with: "%23"))/upcomingchests" let params = ["authorization": "Bearer \(HelperCommon.apiKey)"] request(urlString: urlString, method: HTTPMethod.get, params: params) { (res, isSuccess, _, _) in let dict = res as? [String: Any] completion(dict, isSuccess) } } } extension SCNetworkManager{ func getClanData(tag: String, completion:@escaping (_ dict: [String: Any]?,_ isSuccess: Bool)->()){ let urlString = "https://api.clashroyale.com/v1/clans/\((tag as NSString).replacingOccurrences(of: "#", with: "%23"))" let params = ["authorization": "Bearer \(HelperCommon.apiKey)"] request(urlString: urlString, method: HTTPMethod.get, params: params) { (res, isSuccess, _, _) in let dict = res as? [String: Any] completion(dict, isSuccess) } } } extension SCNetworkManager{ func getClanPastWarsData(tag: String, completion:@escaping (_ dict: [String: Any]?,_ isSuccess: Bool)->()){ let urlString = "https://api.clashroyale.com/v1/clans/\((tag as NSString).replacingOccurrences(of: "#", with: "%23"))/warlog" let params = ["authorization": "Bearer \(HelperCommon.apiKey)"] request(urlString: urlString, method: HTTPMethod.get, params: params) { (res, isSuccess, _, _) in let dict = res as? [String: Any] completion(dict, isSuccess) } } } extension SCNetworkManager{ func getClanWarsData(tag: String, completion:@escaping (_ dict: [String: Any]?,_ isSuccess: Bool)->()){ let urlString = "https://api.clashroyale.com/v1/clans/\((tag as NSString).replacingOccurrences(of: "#", with: "%23"))/currentwar" let params = ["authorization": "Bearer \(HelperCommon.apiKey)"] request(urlString: urlString, method: HTTPMethod.get, params: params) { (res, isSuccess, _, _) in let dict = res as? [String: Any] completion(dict, isSuccess) } } } extension SCNetworkManager{ func getLocationsList(completion:@escaping (_ dict: [String: Any]?,_ isSuccess: Bool)->()){ let urlString = "https://api.clashroyale.com/v1/locations" let params = ["authorization": "Bearer \(HelperCommon.apiKey)"] request(urlString: urlString, method: HTTPMethod.get, params: params) { (res, isSuccess, _, _) in let dict = res as? [String: Any] completion(dict, isSuccess) } } } extension SCNetworkManager{ func getLocationsClanRankings(id: String, completion:@escaping (_ dict: [String: Any]?,_ isSuccess: Bool)->()){ let urlString = "https://api.clashroyale.com/v1/locations/\(id)/rankings/clans" let params = ["authorization": "Bearer \(HelperCommon.apiKey)"] request(urlString: urlString, method: HTTPMethod.get, params: params) { (res, isSuccess, _, _) in let dict = res as? [String: Any] completion(dict, isSuccess) } } } extension SCNetworkManager{ func getLocationsPlayerRankings(id: String, completion:@escaping (_ dict: [String: Any]?,_ isSuccess: Bool)->()){ let urlString = "https://api.clashroyale.com/v1/locations/\(id)/rankings/players" let params = ["authorization": "Bearer \(HelperCommon.apiKey)"] request(urlString: urlString, method: HTTPMethod.get, params: params) { (res, isSuccess, _, _) in let dict = res as? [String: Any] completion(dict, isSuccess) } } }
46.118056
143
0.629122
ff834b0124b4210cff1ba158b1c101f981be7715
2,033
import Cocoa class MainSplitView : NSSplitView { let startWidth: CGFloat = 250 let minimumWidth: CGFloat = 200 let maximumWidth: CGFloat = 300 var listView: NSView! var detailView: NSView! { didSet { subviews.removeLast() addSubview(detailView) adjustSubviews() setPosition(startWidth, ofDividerAt: 0) } } override var dividerColor: NSColor { return NSColor(red:0.2, green:0.2, blue:0.2, alpha: 1) } override init(frame: NSRect) { super.init(frame: frame) delegate = self dividerStyle = .thin autosaveName = "MainSplitView" isVertical = true autoresizingMask = [] autoresizesSubviews = false } init(listView: NSView, detailView: NSView) { self.init() self.listView = listView self.detailView = detailView addSubview(listView) addSubview(detailView) } override func viewDidMoveToWindow() { setPosition(startWidth, ofDividerAt: 0) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension MainSplitView: NSSplitViewDelegate { func splitView(_ splitView: NSSplitView, constrainMaxCoordinate proposedMaximumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat { return dividerIndex == 0 ? maximumWidth : proposedMaximumPosition } func splitView(_ splitView: NSSplitView, constrainMinCoordinate proposedMinimumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat { return dividerIndex == 0 ? minimumWidth : proposedMinimumPosition } func splitViewWillResizeSubviews(_ notification: Notification) { if listView.frame.width >= maximumWidth { listView.frame.size.width = maximumWidth } else if listView.frame.width <= minimumWidth { listView.frame.size.width = minimumWidth } } func splitViewDidResizeSubviews(_ notification: Notification) { subviews.forEach { $0.layout() } } func splitView(_ splitView: NSSplitView, canCollapseSubview subview: NSView) -> Bool { return false } }
25.734177
143
0.71028
7109219c6e3386467e6fce8d2c5e3b20add2b288
4,187
// // TaskStorage.swift // Magpie // // Created by Salih Karasuluoglu on 4.04.2019. // import Foundation struct TaskStorage { private typealias Table = [String: [TaskConvertible]] /// <note> AtomicWrapper is for preventing race-conditions. private var tableWrapper = AtomicWrapper<Table>(value: [:]) } extension TaskStorage { func add(_ task: TaskConvertible, for endpoint: Endpoint) { add(task, for: endpoint.request.path.encoded()) } func add(_ task: TaskConvertible, for path: String) { tableWrapper.setValue { table in if !task.inProgress { return } if var currentTasks = table[path] { currentTasks.append(task) table[path] = currentTasks } else { table[path] = [task] } } } } extension TaskStorage { func delete(for endpoint: Endpoint) { if let task = endpoint.task { delete(task, with: endpoint.request.path.encoded()) } } func cancelAndDelete(for endpoint: Endpoint) { if let task = endpoint.task { cancelAndDelete(task, with: endpoint.request.path.encoded()) } } func delete(_ task: TaskConvertible, with path: String) { delete(task, with: path, afterCancellation: false) } func cancelAndDelete(_ task: TaskConvertible, with path: String) { delete(task, with: path, afterCancellation: true) } func deleteAll(with path: String) { deleteAll(with: path, afterCancellation: false) } func cancelAndDeleteAll(with path: String) { deleteAll(with: path, afterCancellation: true) } func deleteAll(relativeTo path: String) { deleteAll(relativeTo: path, afterCancellation: false) } func cancelAndDeleteAll(relativeTo path: String) { deleteAll(relativeTo: path, afterCancellation: true) } func deleteAll() { deleteAll(afterCancellation: false) } func cancelAndDeleteAll() { deleteAll(afterCancellation: true) } } extension TaskStorage { private func delete(_ task: TaskConvertible, with path: String, afterCancellation: Bool) { if afterCancellation { task.cancelNow() } tableWrapper.setValue { table in guard var currentTasks = table[path] else { return } currentTasks.removeAll { $0.taskIdentifier == task.taskIdentifier } if currentTasks.isEmpty { table[path] = nil } else { table[path] = currentTasks } } } private func deleteAll(with path: String, afterCancellation: Bool) { tableWrapper.setValue { table in if afterCancellation { table[path]?.forEach { $0.cancelNow() } } table[path] = nil } } private func deleteAll(relativeTo path: String, afterCancellation: Bool) { tableWrapper.setValue { table in for item in table where item.key.contains(path) { if afterCancellation { item.value.forEach { $0.cancelNow() } } table[item.key] = nil } } } private func deleteAll(afterCancellation: Bool) { tableWrapper.setValue { table in if afterCancellation { table.forEach { $1.forEach { $0.cancelNow() } } } table.removeAll() } } } extension TaskStorage: Printable { /// <mark> CustomStringConvertible var description: String { return """ { \(tableWrapper.getValue() .map({ "\($0.key):[\($0.value.map({ $0.description }).joined(separator: ", "))]" }) .joined(separator: "\n ") ) } """ } /// <mark> CustomDebugStringConvertible var debugDescription: String { return """ { \(tableWrapper.getValue() .map({ "\($0.key):[\n\t\($0.value.map({ $0.debugDescription }).joined(separator: ",\n\t"))]" }) .joined(separator: "\n ") ) } """ } }
27.188312
107
0.564605
11d18b25be5c9a6491079f8a4f954fc418d6a7fd
530
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "ProgressHud", products: [ .library(name: "ProgressHud", targets: ["ProgressHud"]) ], dependencies: [], targets: [ .target( name: "ProgressHud", dependencies: [], path: "ProgressHud", resources: [ .process("Assets") ] ), ] )
23.043478
96
0.54717
3801ed547f4cb7a5a11c58daaa4f7f9c39503710
963
// // ColorUtil.swift // DayPlans // // Created by Will Brandon on 7/20/20. // Copyright © 2020 Will Brandon. All rights reserved. // import Foundation import UIKit class ColorUtil { class func randomColor( redRange: ClosedRange<CGFloat>, greenRange: ClosedRange<CGFloat>, blueRange: ClosedRange<CGFloat>, alphaRange: ClosedRange<CGFloat> ) -> UIColor { let red = CGFloat.random(in: redRange) let green = CGFloat.random(in: greenRange) let blue = CGFloat.random(in: blueRange) let alpha = CGFloat.random(in: alphaRange) return UIColor(red: red, green: green, blue: blue, alpha: alpha) } class func randomColor() -> UIColor { randomColor(redRange: 0...1, greenRange: 0...1, blueRange: 0...1, alphaRange: 0...1) } class func randomOpaqueColor() -> UIColor { randomColor(redRange: 0...1, greenRange: 0...1, blueRange: 0...1, alphaRange: 1...1) } }
30.09375
134
0.635514
fc4a0e27430a0887bbba7685fbda727a826169ec
1,556
// // DroarImageCell.swift // Droar // // Created by Nathan Jangula on 10/26/17. // import Foundation public class DroarImageCell : UITableViewCell, DroarCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var largeImageView: UIImageView! public var title: String? { get { return titleLabel.text } set { titleLabel.text = newValue } } public var detailImage: UIImage? { get { return largeImageView.image } set { largeImageView.image = newValue } } public var allowSelection: Bool { get { return selectionStyle != .none } set { selectionStyle = newValue ? .gray : .none } } public static func create(title: String? = "", image: UIImage? = nil, allowSelection: Bool = false) -> DroarImageCell { var cell: DroarImageCell? for view in Bundle.podBundle.loadNibNamed("DroarImageCell", owner: self, options: nil) ?? [Any]() { if view is DroarImageCell { cell = view as? DroarImageCell break } } cell?.title = title cell?.detailImage = image cell?.allowSelection = allowSelection return cell ?? DroarImageCell() } public func setEnabled(_ enabled: Bool) { titleLabel.isEnabled = enabled backgroundColor = enabled ? UIColor.white : UIColor.disabledGray isUserInteractionEnabled = enabled } public func stateDump() -> [String : String]? { return nil } }
27.785714
123
0.598972
ff37993c3e77dd6ed7e81c8dfdcdcf81354074bd
660
// // RestaurantAnnotation.swift // Foodie // // Created by Soumil Datta on 8/7/20. // Copyright © 2020 Soumil Datta. All rights reserved. // import Foundation import MapKit class RestaurantAnnotation: NSObject, MKAnnotation { let title: String? let locationName: String? let coordinate: CLLocationCoordinate2D init( title: String?, locationName: String?, coordinate: CLLocationCoordinate2D ) { self.title = title self.locationName = locationName self.coordinate = coordinate super.init() } var subtitle: String? { return locationName } }
20
55
0.630303
3ac37ba6576b46cda68140c691ea109e506818d7
15,019
// // GraphAPI.swift // SPAJAM2017Final // // Created by Tatsuya Tanaka on 20170709. // Copyright © 2017年 tattn. All rights reserved. // import Foundation import UIKit import FBSDKLoginKit import Result import RxSwift struct GraphMe { let gender: String let locationName: String let works: [Work] let educations: [Eduction] let id: String // 747789068725242 let birthday: String // MM/HH/YYYY let hometownName: String let name: String let iconUrl: String struct Work { let employerName: String // hoge株式会社 let startDate: String // 0000-00 // 未設定? let id: String let locationName: String let positionName: String // エンジニア } struct Eduction { let name: String } } struct TaggableFriend { let id: String // AaJOeKiZlF3v6we8WQs56p_dRWdzXyyu6Ad0am9Lf0hjW16rbxEXmETWyLxs2mwPzXYMUNtwMTtLZRaOVre1R88lxiGRZat5Ognv79qo-wHLvQ let name: String } struct Feed { let message: String? let id: String? let caption: String? let description: String? let icon: String? let link: String? let name: String? let shares: String? let message_tags: Any? let objectType: String? // enum{link, status, photo, video, offer} let objectId: String? } final class GraphAPI { static func me(completion: @escaping (Result<GraphMe, NSError>) -> Void) { guard FBSDKAccessToken.current() != nil else { return } let params: [String: String] = ["fields": "name,about,birthday,hometown,gender,location,education,work,picture.type(large)", "locale": "ja_JP"] let request = FBSDKGraphRequest(graphPath: "me", parameters: params) _ = request?.start(completionHandler: { (_, result, error) in if let error = error { print("graph me: \(error)") return } if let result = result as? [String: Any] { let graphMe = GraphMe(gender: result["gender"] as! String, locationName: (result["location"] as? [String: Any])?["name"] as? String ?? "", works: ((result["work"] as? [[String: Any]]) ?? []).map { GraphMe.Work.init(employerName: ($0["employer"] as! [String: Any])["name"] as! String, startDate: $0["start_date"] as? String ?? "", id: $0["id"] as! String, locationName: ($0["location"] as? [String: Any] ?? [:])["name"] as? String ?? "", positionName: ($0["position"] as? [String: Any] ?? [:])["name"] as? String ?? "") }, educations: (result["education"] as? [[String: Any]] ?? []).map { GraphMe.Eduction(name: ($0["classes"] as? [String: Any] ?? [:])["name"] as? String ?? "") }, id: result["id"] as! String, birthday: result["birthday"] as? String ?? "", hometownName: (result["hometown"] as? [String: Any])?["name"] as? String ?? "", name: result["name"] as! String, iconUrl: ((result["picture"] as? [String: Any])?["data"] as? [String: Any])?["url"] as? String ?? "") print(graphMe) completion(.success(graphMe)) } }) } // static func friends(completion: @escaping (Result<[TaggableFriend], NSError>) -> Void) { static func friends(completion: @escaping (Result<[GraphMe], NSError>) -> Void) { guard FBSDKAccessToken.current() != nil else { return } let params: [String: String] = ["fields": "id,name,picture", "locale": "ja_JP"] let request = FBSDKGraphRequest(graphPath: "me/friends", parameters: params) _ = request?.start(completionHandler: { (_, result, error) -> Void in if let error = error { print("graph friends: \(error)") return } guard let result = result as? [String: Any] else { return } let summary = result["summary"] as! NSDictionary let counts = summary["total_count"] as! Int let params = "name,about,birthday,hometown,gender,location,education,work,picture.type(large)" // let graphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me/taggable_friends", parameters: ["fields": params, "limit": "\(counts)", "locale": "ja_JP"]) // graphRequest.start( completionHandler: { (_, result, error) -> Void in // // if let error = error { // print("graph taggable_friends: \(error)") // return // } // // guard let result = result as? [String: Any] else { return } // // let friends = (result["data"] as! [[String: Any]]).map { // TaggableFriend(id: $0["id"] as! String, // name: $0["name"] as! String) // } // print("taggable_friends: \(friends)") // completion(.success(friends)) // // }) // タグ付け可能なすべての友達を取得 (idがハッシュ化されているため使用が難しい) (https://developers.facebook.com/docs/graph-api/reference/user-taggable-friend/ ) //let graphRequest = FBSDKGraphRequest(graphPath: "me/taggable_friends", parameters: params) // 同じアプリを承認している友達を取得 (https://developers.facebook.com/docs/graph-api/reference/user/friends ) let graphRequest = FBSDKGraphRequest(graphPath: "me/friends", parameters: ["fields": params, "limit": "\(counts)", "locale": "ja_JP"]) _ = graphRequest?.start { _, result, error in if let error = error { print("graph taggable_friends: \(error)") return } guard let result = result as? [String: Any] else { return } let friends = (result["data"] as! [[String: Any]]).map { result in GraphMe(gender: result["gender"] as! String, locationName: (result["location"] as? [String: Any] ?? [:])["name"] as? String ?? "", works: (result["work"] as? [[String: Any]] ?? []).map { GraphMe.Work.init(employerName: ($0["employer"] as! [String: Any])["name"] as! String, startDate: $0["start_date"] as! String, id: $0["id"] as! String, locationName: ($0["location"] as! [String: Any])["name"] as! String, positionName: ($0["position"] as! [String: Any])["name"] as! String) }, educations: (result["education"] as? [[String: Any]] ?? []).map { GraphMe.Eduction(name: ($0["classes"] as? [String: Any] ?? [:])["name"] as? String ?? "") }, id: result["id"] as! String, birthday: result["birthday"] as? String ?? "", hometownName: (result["hometown"] as? [String: Any] ?? [:])["name"] as? String ?? "", name: result["name"] as! String, iconUrl: ((result["picture"] as! [String: Any])["data"] as! [String: Any])["url"] as! String) } + Mock.friends() print(friends) completion(.success(friends)) } }) } static func profile(userId: String, completion: @escaping (Result<GraphMe, NSError>) -> Void) { guard FBSDKAccessToken.current() != nil else { return } let params: [String: String] = ["fields": "name,about,birthday,hometown,gender,location,education,work,picture.type(large)", "locale": "ja_JP"] let request = FBSDKGraphRequest(graphPath: "/\(userId)", parameters: params) _ = request?.start(completionHandler: { (_, result, error) -> Void in if let error = error { print("graph friends: \(error)") return } guard let result = result as? [String: Any] else { return } let graphMe = GraphMe(gender: result["gender"] as! String, locationName: (result["location"] as! [String: Any])["name"] as! String, works: (result["work"] as! [[String: Any]]).map { GraphMe.Work.init(employerName: ($0["employer"] as! [String: Any])["name"] as! String, startDate: $0["start_date"] as! String, id: $0["id"] as! String, locationName: ($0["location"] as! [String: Any])["name"] as! String, positionName: ($0["position"] as! [String: Any])["name"] as! String) }, educations: (result["education"] as? [[String: Any]] ?? []).map { GraphMe.Eduction(name: ($0["classes"] as? [String: Any] ?? [:])["name"] as? String ?? "") }, id: result["id"] as! String, birthday: result["birthday"] as! String, hometownName: (result["hometown"] as! [String: Any])["name"] as! String, name: result["name"] as! String, iconUrl: ((result["picture"] as! [String: Any])["data"] as! [String: Any])["url"] as! String) print(graphMe) completion(.success(graphMe)) }) } static func feed(userId: String, completion: @escaping (Result<[Feed], NSError>) -> Void) { guard FBSDKAccessToken.current() != nil else { return } let params: [String: String] = ["fields": "message,caption,description,icon,link,name,shares,message_tags,object_type,object_id", "locale": "ja_JP", "limit": "\(100)"] let request = FBSDKGraphRequest(graphPath: "/\(userId)/feed", parameters: params) _ = request?.start(completionHandler: { (_, result, error) -> Void in if let error = error { print("graph friends: \(error)") return } guard let result = result as? [String: Any] else { return } // ページングやりたい // result["paging"]になんかはいってる let feeds = (result["data"] as! [[String: Any]]).map { Feed(message: $0["message"] as? String, id: $0["id"] as? String, caption: $0["caption"] as? String, description: $0["description"] as? String, icon: $0["icon"] as? String, link: $0["link"] as? String, name: $0["name"] as? String, shares: $0["shares"] as? String, message_tags: $0["message_tags"] as Any, objectType: $0["object_type"] as? String, objectId: $0["object_id"] as? String ) } print(feeds) completion(.success(feeds)) }) } static func photos0(userId: String, completion: @escaping (Result<[Feed], NSError>) -> Void) { guard FBSDKAccessToken.current() != nil else { return } let params: [String: String] = ["fields": "link", "locale": "ja_JP", "limit": "\(100)"] let request = FBSDKGraphRequest(graphPath: "/\(userId)/photos", parameters: params) _ = request?.start(completionHandler: { (_, result, error) -> Void in if let error = error { print("graph friends: \(error)") return } guard let result = result as? [String: Any] else { return } // let albumIds = (result["data"] as? [[String: Any]] ?? []).flatMap { $0["id"] as? String } // completion(.success(feeds)) }) } static func photos(userId: String, completion: @escaping (Result<[String], NSError>) -> Void) { guard FBSDKAccessToken.current() != nil else { return } let params: [String: String] = ["fields": "id", "locale": "ja_JP", "limit": "\(100)"] let request = FBSDKGraphRequest(graphPath: "/\(userId)/albums", parameters: params) _ = request?.start(completionHandler: { (_, result, error) -> Void in if let error = error { print("graph friends: \(error)") return } guard let result = result as? [String: Any] else { return } var imageUrls: [String] = [] let group = DispatchGroup() let albumIds = (result["data"] as? [[String: Any]] ?? []).flatMap { $0["id"] as? String } for albumId in albumIds { group.enter() DispatchQueue.global().async { let params: [String: String] = ["fields": "link,picture,images", "locale": "ja_JP", "limit": "\(100)"] let request = FBSDKGraphRequest(graphPath: "/\(albumId)/photos", parameters: params) _ = request?.start(completionHandler: { (_, result, error) -> Void in if let error = error { print("graph friends: \(error)") return } guard let result = result as? [String: Any] else { return } if let imageUrl = ((result["data"] as? [[String: Any]] ?? [])[0]["images"] as? [[String: Any]] ?? [])[0]["source"] as? String { imageUrls.append(imageUrl) } group.leave() }) } } group.notify(queue: .main) { print(imageUrls) completion(.success(imageUrls)) } }) } }
48.921824
176
0.470138
db5551b58e11e471d32e5b81974fc18a94a147ed
907
// // IntIFSpec.swift // OOSwift // // Created by Karsten Litsche on 01.09.17. // // import XCTest @testable import OOBase final class IntIFSpec: XCTestCase { func testGIVEN_ATrueCondition_WHEN_GetValue_THEN_PrimaryValueIsReturned() { // GIVEN let primary = OOIntFake(1) let secondary = OOIntFake(2) let object = IntIF(OOBoolFake(true), THEN: primary, ELSE: secondary) // WHEN let result = object.value // THEN XCTAssertEqual(result, primary.value) } func testGIVEN_AFalseCondition_WHEN_GetValue_THEN_SecondaryValueIsReturned() { // GIVEN let primary = OOIntFake(1) let secondary = OOIntFake(2) let object = IntIF(OOBoolFake(false), THEN: primary, ELSE: secondary) // WHEN let result = object.value // THEN XCTAssertEqual(result, secondary.value) } }
24.513514
82
0.636163
4a4b21e18186c49566d91a340f437f91687621bb
720
// // AppDelegate.swift // QRCode // // Created by pankx on 2017/7/29. // Copyright © 2017年 pankx. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { //1、获取UIWindow对象 window = UIWindow() //2、设置界面 let vc = MainViewController() window?.rootViewController = vc //3、设置window的背景颜色 window?.backgroundColor = UIColor.white //4、设置视图可见 window?.makeKeyAndVisible() return true } }
20
144
0.638889
b9d6860eb01a5ddd1afd23d7422007bba8ad2ed0
1,679
// // LiveListDownloader.swift // VoodooLivePlayer // // Created by voodoo on 2019/12/13. // Copyright © 2019 Voodoo-Live. All rights reserved. // import Foundation public struct LiveListItem { public var flvUrl:String? public var hlsUrl:String? public var coverUrl:String? public var title:String public var name:String } public protocol LiveListDownloaderDelegate : class { func handle(downloader:LiveListDownloader?,error:Error?) func handle(downloader:LiveListDownloader?,liveList:Array<LiveListItem>) } public class LiveListDownloader { public weak var delegate:LiveListDownloaderDelegate? public var urlSession:URLSession init() { urlSession = URLSession(configuration: .default) } public func load() {} public func handle(downloadContent:String?, error:Error?) {} public func download(url:String) { if let httpURL = URL(string: url) { let task = urlSession.dataTask(with: httpURL) { (data:Data?, res:URLResponse?, error:Error?) in if error != nil { self.handle(downloadContent: nil, error: error) } else { if let contentData = data, let content = String(bytes: contentData, encoding: .utf8) { self.handle(downloadContent: content, error: nil) } else { self.handle(downloadContent: nil, error: URLError(URLError.cannotParseResponse)) } } } task.resume() } else { handle(downloadContent: nil, error: URLError(URLError.cannotLoadFromNetwork)) } } }
31.679245
107
0.621203
904a4a2166993a11ee779fc86e324ead5d9e891c
1,062
// // ClientsView.swift // Realtime // // Created by Andrew Levy on 9/30/20. // Copyright © 2020 Rootstrap. All rights reserved. // import SwiftUI struct ClientsView: View { var color: Color = Color(UIColor.systemBlue).opacity(0.8) var body: some View { VStack(alignment: .leading) { HStack(alignment: .center) { Text("Clients") .font(.system(size: 30)) .fontWeight(.heavy) .foregroundColor(.primary) .padding(.bottom, 20) Spacer() Button(action: {}) { Image(systemName: "person.crop.circle.fill.badge.plus") } } ScrollView { VStack { ClientView() ClientView() ClientView() } } }.padding(.horizontal, 30) } } struct ClientsView_Previews: PreviewProvider { static var previews: some View { ClientsView() } }
25.285714
75
0.478343