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
fe8366b433402cfa371c77193eb3544c45eacef9
3,165
// // GameLoader.swift // BlocklySample // // Created by CXY on 2017/11/2. // Copyright © 2017年 Google Inc. All rights reserved. // import UIKit import SceneKit import AVFoundation class GameLoader: NSObject { private static let instance = GameLoader() public class var shared: GameLoader { return instance } private override init() { super.init() } private lazy var audioPlayer: AVAudioPlayer? = { do { // SS1_PUZL_1b SS1_CONGR_1h guard let url = Bundle.main.url(forResource: "SS1_PUZL_1b", withExtension: ".m4a") else { return nil } let audioPlayer = try AVAudioPlayer(contentsOf: url) audioPlayer.numberOfLoops = -1 audioPlayer.prepareToPlay() return audioPlayer } catch (_) { return nil } }() class func loadGameWithScnView(_ scnView: SCNView) -> Actor? { // set the scene to the view let scene = SCNScene(named: "WorldResources.scnassets/_Scenes/3.2.scn")! // Give the `rootNode` a name for easy lookup. scene.rootNode.name = "rootNode" // Load the skybox. scene.background.contents = Asset.texture(named: "zon_bg_skyBox_a_DIFF") let rootNode = scene.rootNode // Set up the camera. let cameraNode = rootNode.childNode(withName: "camera", recursively: true)! let boundingNode = rootNode.childNode(withName: "Scenery", recursively: true) var (_, sceneWidth) = (boundingNode?.boundingSphere)! // Expand so we make sure to get the whole thing with a bit of overlap. sceneWidth *= 2 let dominateDimension = Float(5) sceneWidth = max(dominateDimension * 2.5, sceneWidth) guard sceneWidth.isFinite && sceneWidth > 0 else { return nil} let cameraDistance = Double(cameraNode.position.z) let halfSceneWidth = Double(sceneWidth / 2.0) let distanceToEdge = sqrt(cameraDistance * cameraDistance + halfSceneWidth * halfSceneWidth) let cos = cameraDistance / distanceToEdge let sin = halfSceneWidth / distanceToEdge let halfAngle = atan2(sin, cos) cameraNode.camera?.yFov = 2.0 * halfAngle * 180.0 / .pi // Set up normal lights guard let lightNode = rootNode.childNode(withName: DirectionalLightName, recursively: true) else { return nil } var light: SCNLight? lightNode.enumerateHierarchy { node, stop in if let directional = node.light { light = directional stop.initialize(to: true) } } light?.orthographicScale = 10 light?.shadowMapSize = CGSize(width: 2048, height: 2048) // Add actor let actor = Actor(scene: scene) scnView.scene = scene scnView.allowsCameraControl = true return actor } class func silent() { GameLoader.shared.audioPlayer?.stop() } class func bgmStart() { GameLoader.shared.audioPlayer?.play() } }
32.628866
119
0.60316
fc4d946cc6a113db0b8b5a40d7654ce48d16ffe8
7,762
import XCTest import Turf class JSONTests: XCTestCase { func testRawValues() { XCTAssertEqual(JSONValue(rawValue: "Jason" as NSString), .string("Jason")) XCTAssertEqual(JSONValue(rawValue: 42 as NSNumber), .number(42)) XCTAssertEqual(JSONValue(rawValue: 3.1415 as NSNumber), .number(3.1415)) XCTAssertEqual(JSONValue(rawValue: false as NSNumber), .boolean(false)) XCTAssertEqual(JSONValue(rawValue: true as NSNumber), .boolean(true)) XCTAssertEqual(JSONValue(rawValue: ["Jason", 42, 3.1415, false, true, nil, [], [:]] as NSArray), .array(["Jason", 42, 3.1415, false, true, nil, [], [:]])) XCTAssertEqual(JSONValue(rawValue: [ "string": "Jason", "integer": 42, "float": 3.1415, "false": false, "true": true, "nil": nil, "array": [], "dictionary": [:], ] as NSDictionary), .object([ "string": "Jason", "integer": 42, "float": 3.1415, "false": false, "true": true, "nil": nil, "array": [], "dictionary": [:], ])) XCTAssertNil(JSONValue(rawValue: NSNull())) XCTAssertEqual(JSONValue(rawValue: [NSNull()]), .array([nil])) XCTAssertEqual(JSONArray(rawValue: [NSNull()]), [nil]) XCTAssertEqual(JSONValue(rawValue: ["NSNull": NSNull()]), .object(["NSNull": nil])) XCTAssertEqual(JSONObject(rawValue: ["NSNull": NSNull()]), ["NSNull": nil]) XCTAssertNil(JSONValue(rawValue: Set(["Get"]))) XCTAssertEqual(JSONValue(rawValue: [Set(["Get"])]), .array([nil])) XCTAssertEqual(JSONArray(rawValue: [Set(["Get"])]), [nil]) XCTAssertEqual(JSONValue(rawValue: ["set": Set(["Get"])]), .object(["set": nil])) XCTAssertEqual(JSONObject(rawValue: ["set": Set(["Get"])]), ["set": nil]) } func testLiterals() throws { if case let JSONValue.string(string) = "Jason" { XCTAssertEqual(string, "Jason") } else { XCTFail() } if case let JSONValue.number(number) = 42 { XCTAssertEqual(number, 42) } else { XCTFail() } if case let JSONValue.number(number) = 3.1415 { XCTAssertEqual(number, 3.1415) } else { XCTFail() } if case let JSONValue.boolean(boolean) = false { XCTAssertFalse(boolean) } else { XCTFail() } if case let JSONValue.boolean(boolean) = true { XCTAssertTrue(boolean) } else { XCTFail() } if case let JSONValue.array(array) = ["Jason", 42, 3.1415, false, true, nil, [], [:]], array.count == 8 { if case let .string(string) = array[0] { XCTAssertEqual(string, "Jason") } else { XCTFail() } if case let .number(number) = array[1] { XCTAssertEqual(number, 42) } else { XCTFail() } if case let .number(number) = array[2] { XCTAssertEqual(number, 3.1415) } else { XCTFail() } if case let .boolean(boolean) = array[3] { XCTAssertFalse(boolean) } else { XCTFail() } if case let .boolean(boolean) = array[4] { XCTAssertTrue(boolean) } else { XCTFail() } if case .none = array[5] {} else { XCTFail() } if case let .array(array) = array[6] { XCTAssertEqual(array, []) } else { XCTFail() } if case let .object(object) = array[7] { XCTAssertEqual(object, [:]) } else { XCTFail() } } else { XCTFail() } if case let JSONValue.object(object) = [ "string": "Jason", "integer": 42, "float": 3.1415, "false": false, "true": true, "nil": nil, "array": [], "dictionary": [:], ], object.count == 8 { if case let .string(string) = object["string"] { XCTAssertEqual(string, "Jason") } else { XCTFail() } if case let .number(number) = object["integer"] { XCTAssertEqual(number, 42) } else { XCTFail() } if case let .number(number) = object["float"] { XCTAssertEqual(number, 3.1415) } else { XCTFail() } if case let .boolean(boolean) = object["false"] { XCTAssertFalse(boolean) } else { XCTFail() } if case let .boolean(boolean) = object["true"] { XCTAssertTrue(boolean) } else { XCTFail() } // The optional from dictionary subscripting isn’t unwrapped automatically if matching Optional.none. if case .some(.none) = object["nil"] {} else { XCTFail() } if case let .array(array) = object["array"] { XCTAssertEqual(array, []) } else { XCTFail() } if case let .object(object) = object["dictionary"] { XCTAssertEqual(object, [:]) } else { XCTFail() } } else { XCTFail() } } func testCoding() { let rawArray = ["Jason", 42, 3.1415, false, true, nil, [], [:]] as [Any?] let serializedArray = try! JSONSerialization.data(withJSONObject: rawArray, options: []) var decodedValue: JSONValue? XCTAssertNoThrow(decodedValue = try JSONDecoder().decode(JSONValue.self, from: serializedArray)) XCTAssertNotNil(decodedValue) if case let .array(array) = decodedValue, case let .string(string) = array[0] { XCTAssertEqual(string, rawArray[0] as? String) } else { XCTFail() } XCTAssertEqual(decodedValue?.rawValue as? NSArray, rawArray as NSArray) XCTAssertNoThrow(try JSONEncoder().encode(decodedValue)) let rawObject = [ "string": "Jason", "integer": 42, "float": 3.1415, "false": false, "true": true, "nil": nil, "array": [], "dictionary": [:], ] as [String: Any?] let serializedObject = try! JSONSerialization.data(withJSONObject: rawObject, options: []) XCTAssertNoThrow(decodedValue = try JSONDecoder().decode(JSONValue.self, from: serializedObject)) XCTAssertNotNil(decodedValue) if case let .object(object) = decodedValue, case let .string(string) = object["string"] { XCTAssertEqual(string, rawObject["string"] as? String) } else { XCTFail() } XCTAssertEqual(decodedValue?.rawValue as? NSDictionary, rawObject as NSDictionary) XCTAssertNoThrow(try JSONEncoder().encode(decodedValue)) } }
33.17094
113
0.46908
0995b1e6cd729699e4b1abc3e391761a06734cb3
741
// // CityTests.swift // MapChallengeTests // // Created by Juan López Bosch on 25/07/2020. // Copyright © 2020 Juan López. All rights reserved. // @testable import MapChallenge import XCTest class CityTests: XCTestCase { var sut: City! override func setUpWithError() throws { try super.setUpWithError() sut = .lisbon } override func tearDownWithError() throws { sut = nil try super.tearDownWithError() } func testCity_conformsToIdentifiable() { XCTAssertEqual(sut.id, sut.rawValue) } func testCity_conformsToComparable() { // given let city: City = .valencia // then XCTAssertLessThan(sut, city) } }
19.5
53
0.612686
751bd6b7ca6c071d9479022b35c8975c0ed51285
5,105
// // TweetCell.swift // twitter_alamofire_demo // // Created by Danny on 11/4/18. // Copyright © 2018 Charles Hieger. All rights reserved. // import UIKit import Alamofire import AlamofireImage protocol TweetCellUpdater: class { func updateTableView() } class TweetCell: UITableViewCell { @IBOutlet weak var profileImageView: UIImageView! { didSet { profileImageView.layer.cornerRadius = 3.0 } } @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var screenNameLabel: UILabel! @IBOutlet weak var dateCreatedLabel: UILabel! @IBOutlet weak var tweetTextLabel: UILabel! @IBOutlet weak var replyCountLabel: UILabel! @IBOutlet weak var retweetCountLabel: UILabel! @IBOutlet weak var favoriteCountLabel: UILabel! @IBOutlet weak var messageCountLabel: UILabel! @IBOutlet weak var replyButton: UIButton! @IBOutlet weak var retweetButton: UIButton! @IBOutlet weak var favoriteButton: UIButton! @IBOutlet weak var messageButton: UIButton! weak var delegate: TweetCellUpdater? let favorite_def: UIImage = #imageLiteral(resourceName: "favor-icon") let favorite_sel: UIImage = #imageLiteral(resourceName: "favor-icon-red") let retweet_def: UIImage = #imageLiteral(resourceName: "retweet-icon") let retweet_sel: UIImage = #imageLiteral(resourceName: "retweet-icon-green") var tweet: Tweet! { didSet { nameLabel.text = tweet.user?.name let screenName = tweet.user?.screenName screenNameLabel.text = "@\(String(describing: screenName))" dateCreatedLabel.text = tweet.createdAtString tweetTextLabel.text = tweet.text retweetCountLabel.text = String(tweet.retweetCount!) favoriteCountLabel.text = String(tweet.favoriteCount!) profileImageView.af_setImage(withURL: URL(string: (tweet.user?.profileImgURL)!)!) } } @IBAction func didTapRetweet(_ sender: UIButton) { if (tweet.retweeted)! { tweet.retweeted = false tweet.retweetCount = tweet.retweetCount! - 1 self.retweetButton.setImage(retweet_def, for: .normal) fetchUnretweet() } else { tweet.retweeted = true tweet.retweetCount = tweet.retweetCount! + 1 self.retweetButton.setImage(retweet_sel, for: .normal) fetchRetweet() } self.retweetCountLabel.text = String(tweet.retweetCount!) updateTableView() } func fetchUnretweet() { APIManager.shared.unretweet(tweet, completion: { (tweet, error) in if let error = error { print("Error unretweeting tweet: \(error.localizedDescription)") } else if let tweet = tweet { print("Successfully unretweeted the following Tweet: \n\((tweet.text)!)") } }) } func fetchRetweet() { APIManager.shared.retweet(tweet, completion: { (tweet, error) in if let error = error { print("Error retweeting tweet: \(error.localizedDescription)") } else if let tweet = tweet { print("Successfully retweeted the following Tweet: \n\((tweet.text)!)") } }) } @IBAction func didTapFavorite(_ sender: UIButton) { if (tweet.favorited!) { tweet.favorited = false tweet.favoriteCount = tweet.favoriteCount! - 1 self.favoriteButton.setImage(favorite_def, for: .normal) fetchUnfavoriteTweet() } else { tweet.favorited = true tweet.favoriteCount = tweet.favoriteCount! + 1 self.favoriteButton.setImage(favorite_sel, for: .normal) fetchFavoriteTweet() } self.favoriteCountLabel.text = String(tweet.favoriteCount!) updateTableView() } func fetchUnfavoriteTweet() { APIManager.shared.unfavorite(tweet, completion: { (tweet, error) in if let error = error { print("Error unfavoriting tweet: \(error.localizedDescription)") } else if let tweet = tweet { print("Successfully unfavorited the following Tweet: \n\((tweet.text)!)") } }) } func fetchFavoriteTweet() { APIManager.shared.favorite(tweet, completion: { (tweet, error) in if let error = error { print("Error favoriting tweet: \(error.localizedDescription)") } else if let tweet = tweet { print("Successfully favorited the following Tweet: \n\((tweet.text)!)") } }) } func updateTableView() { delegate?.updateTableView() } 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 } }
34.261745
93
0.613516
46288665156ce9f88ceea3b1d548e712e86cf67e
17,072
// // WithdrawPaymentHistoryViewController.swift // Entreprenetwork // // Created by IPS on 07/04/21. // Copyright © 2021 Sujal Adhia. All rights reserved. // import UIKit class WithdrawPaymentHistoryViewController: UIViewController { //Navigation @IBOutlet fileprivate weak var lblTitle:UILabel! @IBOutlet fileprivate weak var buttonBack:UIButton! @IBOutlet fileprivate weak var lblEarningToDate:UILabel! @IBOutlet fileprivate weak var lblEarningAvailable:UILabel! @IBOutlet fileprivate weak var lblEarningWithDrawToDate:UILabel! @IBOutlet fileprivate weak var lblEarningToDateAmount:UILabel! @IBOutlet fileprivate weak var lblEarningAvailableAmount:UILabel! @IBOutlet fileprivate weak var lblEarningWithDrawToDateAmount:UILabel! //TableView @IBOutlet fileprivate weak var tableViewHistory:UITableView! @IBOutlet fileprivate weak var lblnowithdraval:UILabel! // var isForBusinessEarningHistory:Bool = false fileprivate var arrayOfWithDraw:[[String:Any]] = [] var strBusinessEarningToDate = "Total Business Earnings to Date" var strBusinessEarningAvailable = "Total Business Earnings Available" var strBusinessEarningWithDrawToDate = "Total Business Earnings Withdrawn to Date" var strGroupEarningToDate = "Total Group Earnings to Date" var strGroupEarningAvailable = "Total Group Earnings Available" var strGroupEarningWithDrawToDate = "Total Group Earnings Withdrawn to Date" var isLoadMore:Bool = false var currentPage:Int = 1 var fetchPageLimit:Int = 50 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setup() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.currentPage = 1 self.isLoadMore = false } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.fetchMyBusinessEarningDetailAPIRequest() } // MARK: - Custom Methods func setup(){ if self.isForBusinessEarningHistory{ self.lblEarningToDate.text = "\(self.strBusinessEarningToDate)" self.lblEarningAvailable.text = "\(self.strBusinessEarningAvailable)" self.lblEarningWithDrawToDate.text = "\(self.strBusinessEarningWithDrawToDate)" }else{ self.lblEarningToDate.text = "\(self.strGroupEarningToDate)" self.lblEarningAvailable.text = "\(self.strGroupEarningAvailable)" self.lblEarningWithDrawToDate.text = "\(self.strGroupEarningWithDrawToDate)" } //TableView self.configureTableView() } //configure tableview func configureTableView(){ self.tableViewHistory.delegate = self self.tableViewHistory.dataSource = self self.tableViewHistory.estimatedRowHeight = 100.0 self.tableViewHistory.rowHeight = UITableView.automaticDimension self.tableViewHistory.tableFooterView = UIView() self.tableViewHistory.reloadData() } // MARK: - Selector Methods @IBAction func buttonBackSelector(sender:UIButton){ DispatchQueue.main.async { self.navigationController?.popViewController(animated: true) } } // MARK: - API Methods func fetchMyBusinessEarningDetailAPIRequest(){ var dict:[String:Any] = [:] dict["limit"] = "\(self.fetchPageLimit)" dict["page"] = "\(self.currentPage)" var apiQuery = "" if self.isForBusinessEarningHistory{ apiQuery = kGETMYBusinessEarning }else{ apiQuery = kWithDrawGroupEarningHistory } APIRequestClient.shared.sendAPIRequest(requestType: .POST, queryString:"\(apiQuery)" , parameter:dict as [String:AnyObject], isHudeShow: true, success: { (responseSuccess) in if let success = responseSuccess as? [String:Any],let successData = success["success_data"] as? [String:Any]{ if let arrayWithdraw = successData["withdraw_list"] as? [[String:Any]]{ if self.currentPage == 1{ self.arrayOfWithDraw.removeAll() } self.isLoadMore = arrayWithdraw.count > 0 if arrayWithdraw.count > 0 { for objWithDraw in arrayWithdraw{ self.arrayOfWithDraw.append(objWithDraw) } } DispatchQueue.main.async { self.tableViewHistory.reloadData() } } //configure other details /* "total_business_earnings_to_date": 0, "total_business_earnings_available": 0, "total_business_earnings_withdrawn_to_date": 0 */ DispatchQueue.main.async { if self.isForBusinessEarningHistory{ if let value = successData["total_business_earnings_available"],!(value is NSNull){ if let pi: Double = Double("\(value)"){ let updateValue = String(format:"%.2f", pi) self.lblEarningAvailableAmount.text = CurrencyFormate.Currency(value: Double(updateValue) ?? 0.00)//"$\(updateValue)" } } if let value = successData["total_business_earnings_to_date"],!(value is NSNull){ if let pi: Double = Double("\(value)"){ let updateValue = String(format:"%.2f", pi) self.lblEarningToDateAmount.text = CurrencyFormate.Currency(value: Double(updateValue) ?? 0.00)//"$\(updateValue)" } } if let value = successData["total_business_earnings_withdrawn_to_date"],!(value is NSNull){ if let pi: Double = Double("\(value)"){ let updateValue = String(format:"%.2f", pi) self.lblEarningWithDrawToDateAmount.text = CurrencyFormate.Currency(value: Double(updateValue) ?? 0.00)//"$\(updateValue)" } } }else{ if let value = successData["total_group_earnings_available"],!(value is NSNull){ if let pi: Double = Double("\(value)"){ let updateValue = String(format:"%.2f", pi) self.lblEarningAvailableAmount.text = CurrencyFormate.Currency(value: Double(updateValue) ?? 0.00)//"$\(updateValue)" } } if let value = successData["total_group_earnings_to_date"],!(value is NSNull){ if let pi: Double = Double("\(value)"){ let updateValue = String(format:"%.2f", pi) self.lblEarningToDateAmount.text = CurrencyFormate.Currency(value: Double(updateValue) ?? 0.00)//"$\(updateValue)" } } if let value = successData["total_group_earnings_withdrawn_to_date"],!(value is NSNull){ if let pi: Double = Double("\(value)"){ let updateValue = String(format:"%.2f", pi) self.lblEarningWithDrawToDateAmount.text = CurrencyFormate.Currency(value: Double(updateValue) ?? 0.00) } } } } }else{ DispatchQueue.main.async { // SAAlertBar.show(.error, message:"\(kCommonError)".localizedLowercase) } } }) { (responseFail) in if let failResponse = responseFail as? [String:Any],let errorMessage = failResponse["error_data"] as? [String]{ DispatchQueue.main.async { if errorMessage.count > 0{ SAAlertBar.show(.error, message:"\(errorMessage.first!)".localizedLowercase) } } }else{ DispatchQueue.main.async { // SAAlertBar.show(.error, message:"\(kCommonError)".localizedLowercase) } } } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } } extension WithdrawPaymentHistoryViewController:UITableViewDelegate, UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { DispatchQueue.main.async { self.lblnowithdraval.isHidden = (self.arrayOfWithDraw.count != 0) } return self.arrayOfWithDraw.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.tableViewHistory.dequeueReusableCell(withIdentifier: "WithdrawPaymentHistoryTableViewCell", for: indexPath) as! WithdrawPaymentHistoryTableViewCell var isForJOBPayment = false if self.arrayOfWithDraw.count > indexPath.row{ let objHistory = self.arrayOfWithDraw[indexPath.row] if let value = objHistory["amount"],!(value is NSNull){ if let pi: Double = Double("\(value)"){ let updateValue = String(format:"%.2f", pi) cell.lblAmount.text = CurrencyFormate.Currency(value: Double(updateValue) ?? 0)//"$\(updateValue)" } if let value = objHistory["transaction_fee"],!(value is NSNull){ if let pi: Double = Double("\(value)"){ let updateValue = String(format:"%.2f", pi) cell.lblTransactionFees.text = "- \(CurrencyFormate.Currency(value: Double(updateValue) ?? 0))" } } if let value = objHistory["withdrawal_amount"],!(value is NSNull){ if let pi: Double = Double("\(value)"){ let updateValue = String(format:"%.2f", pi) cell.lblWithdrawalAmount.text = CurrencyFormate.Currency(value: Double(updateValue) ?? 0)//"$\(updateValue)" } } if let value = objHistory["payment_status"],!(value is NSNull){ cell.lblWithdrawalStatus.text = "\(value)".uppercased() } let myFloat = ("\(value)" as NSString).floatValue if let werkulesamount = Int.init(myFloat) as? Int{ if werkulesamount > 1{ //cell.lblWithdrawalAmount.text = "$ \(werkulesamount - 1)" } } } if let value = objHistory["created_at"],!(value is NSNull){ let dateformatter = DateFormatter() dateformatter.dateFormat = "yyyy-MM-dd HH:mm:ss" if let date = dateformatter.date(from: "\(value)"){ dateformatter.dateFormat = "MM/dd/yyyy" var strDate = dateformatter.string(from: date) if let name = objHistory["business_name"],!(name is NSNull){ if "\(name)".count > 0{ strDate.append(" (\(name))") isForJOBPayment = true }else{ strDate.append(" (User Withdrawal)") isForJOBPayment = false } }else{ strDate.append(" (User Withdrawal)") isForJOBPayment = false } cell.lblDate.text = "\(strDate)" } } } if indexPath.row+1 == self.arrayOfWithDraw.count, self.isLoadMore{ //last index DispatchQueue.global(qos: .background).async { self.currentPage += 1 self.fetchMyBusinessEarningDetailAPIRequest() } } if isForJOBPayment{ cell.lblWithdrawaltxt.text = "Payment made" cell.stackViewTransactionFees.isHidden = true cell.stackViewWerkulesAmount.isHidden = true }else{ cell.lblWithdrawaltxt.text = "Withdrawal" cell.stackViewTransactionFees.isHidden = false cell.stackViewWerkulesAmount.isHidden = false } return cell//UITableViewCell() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if self.arrayOfWithDraw.count > indexPath.row{ let objHistory = self.arrayOfWithDraw[indexPath.row] if let isforjob = objHistory["is_job_payment"] as? Bool{ if isforjob{ return 90.0 }else{ return 150.0 } }else{ return 150.0 } } return 150.0//UITableView.automaticDimension } } class WithdrawPaymentHistoryTableViewCell:UITableViewCell{ @IBOutlet weak var containerView:UIView! @IBOutlet weak var shadowBackground:ShadowBackgroundView! @IBOutlet weak var lblDate:UILabel! @IBOutlet weak var lblAmount:UILabel! @IBOutlet weak var lblTransactionFees:UILabel! @IBOutlet weak var lblWithdrawalAmount:UILabel! @IBOutlet weak var lblWithdrawalStatus:UILabel! @IBOutlet weak var lblWithdrawaltxt:UILabel! @IBOutlet weak var stackViewTransactionFees:UIStackView! @IBOutlet weak var stackViewWerkulesAmount:UIStackView! override func awakeFromNib() { super.awakeFromNib() DispatchQueue.main.async { self.containerView.layer.cornerRadius = 15.0 self.containerView.clipsToBounds = true self.shadowBackground.layer.cornerRadius = 15.0 self.shadowBackground.rounding = 15.0 self.shadowBackground.layoutIfNeeded() //self.shadowBackground.clipsToBounds = false } } }
50.508876
196
0.490218
eb8fc432a598ab7d28c2156aea7eea9b2610bce3
479
// // WLService+CoreDataProperties.swift // Pods // // Created by Alexander Givens on 8/6/17. // // import Foundation import CoreData extension WLService { @nonobjc public class func fetchRequest() -> NSFetchRequest<WLService> { return NSFetchRequest<WLService>(entityName: "WLService") } @NSManaged public var externalURL: String? @NSManaged public var id: Int32 @NSManaged public var name: String? @NSManaged public var slug: String? }
19.16
76
0.699374
8f9cc2f5e6bab55666b1975f239fd6c1c0c901f6
2,384
// // Persistence.swift // rolladex // // Created by Ryan Dincher on 1/15/22. // import CoreData struct PersistenceController { static let shared = PersistenceController() static var preview: PersistenceController = { let result = PersistenceController(inMemory: true) let viewContext = result.container.viewContext for _ in 0..<10 { let newItem = Item(context: viewContext) newItem.timestamp = Date() } do { try viewContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() 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 fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } return result }() let container: NSPersistentContainer init(inMemory: Bool = false) { container = NSPersistentContainer(name: "rolladex") if inMemory { container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null") } container.viewContext.automaticallyMergesChangesFromParent = true container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() 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. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) } }
41.824561
199
0.635906
1d4aabeb2a2e1f354d4a6bf2b18e8aa051ae3050
686
// // PlaylistStore.swift // MakeItSensationalProject // // Created by Luca Palmese and Gianluca Orpello for the Developer Academy on 11/11/21. // import SwiftUI class PlaylistStore: ObservableObject { @Published var playlists: [Playlist] = [ Playlist( imageName: "Playlist0", name: "Pop Hits Italia", category: "Apple Music Pop Italiano" ), Playlist( imageName: "Playlist1", name: "RapIT", category: "Apple Music Rap Italiano" ), Playlist( imageName: "Playlist2", name: "Today's Hits", category: "Apple Music" ) ] }
23.655172
87
0.553936
fe0863a0ffc5a22ed3c5f5aa599ad2059d15ff40
1,838
// // SettingsVC.swift // HardcoreTap // // Created by Богдан Быстрицкий on 24/11/2017. // Copyright © 2017 Bogdan Bystritskiy. All rights reserved. // import UIKit import StoreKit class SettingsViewController: UIViewController { @IBOutlet weak var heighOfDisableAdStackView: NSLayoutConstraint! @IBOutlet weak var disableAdButton: UIButton! @IBOutlet weak var tableView: UITableView! var titleSetting = ["Фоновый звук"] var bgSound = true let userDefaults = UserDefaults.standard override func viewDidLoad() { super.viewDidLoad() disableAdButton.addShadow() tableView.tableFooterView = UIView(frame: CGRect.zero) } @IBAction func disableAdButtonDidTapped(_ sender: Any) { } } extension SettingsViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return titleSetting.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SettingsCell cell.titleLabel.text = titleSetting[indexPath.row] let switchView = UISwitch(frame: .zero) switchView.setOn(userDefaults.bool(forKey: "bgSound"), animated: true) switchView.onTintColor = UIColor(red: 223 / 255, green: 15 / 255, blue: 92 / 255, alpha: 1) switchView.tag = indexPath.row switchView.addTarget(self, action: #selector(switchChanged(_:)), for: .valueChanged) cell.accessoryView = switchView return cell } @objc func switchChanged(_ sender: UISwitch!) { if sender.isOn { bgSound = true userDefaults.set(bgSound, forKey: "bgSound") } else { bgSound = false userDefaults.set(bgSound, forKey: "bgSound") } } }
29.645161
101
0.717628
7a3b9640a7beff82f70819e4e4d641d22c06b2f4
4,950
import UIKit import MapboxMaps @objc(DataDrivenSymbolsExample) public class DataDrivenSymbolsExample: UIViewController, ExampleProtocol { internal var mapView: MapView! override public func viewDidLoad() { super.viewDidLoad() let centerCoordinate = CLLocationCoordinate2D(latitude: 37.761, longitude: -119.624) let options = MapInitOptions(cameraOptions: CameraOptions(center: centerCoordinate, zoom: 10.0), styleURI: .outdoors) mapView = MapView(frame: view.bounds, mapInitOptions: options) mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(mapView) // Allows the delegate to receive information about map events. mapView.mapboxMap.onNext(.mapLoaded) { _ in self.setupExample() } } public func setupExample() { // Constant used to identify the source layer let sourceLayerIdentifier = "yosemite-pois" // Add icons from the U.S. National Parks Service to the map's style. // Icons are located in the asset catalog try! mapView.mapboxMap.style.addImage(UIImage(named: "nps-restrooms")!, id: "restrooms") try! mapView.mapboxMap.style.addImage(UIImage(named: "nps-trailhead")!, id: "trailhead") try! mapView.mapboxMap.style.addImage(UIImage(named: "nps-picnic-area")!, id: "picnic-area") // Access a vector tileset that contains places of interest at Yosemite National Park. // This tileset was created by uploading NPS shapefiles to Mapbox Studio. var source = VectorSource() source.url = "mapbox://examples.ciuz0vpc" try! mapView.mapboxMap.style.addSource(source, id: sourceLayerIdentifier) // Create a symbol layer and access the layer contained. var layer = SymbolLayer(id: sourceLayerIdentifier) // The source property refers to the identifier provided when the source was added. layer.source = sourceLayerIdentifier // Access the layer that contains the Point of Interest (POI) data. // The source layer property is a unique identifier for a layer within a vector tile source. layer.sourceLayer = "Yosemite_POI-38jhes" // Expression that adds conditions to the source to determine styling. /// `POITYPE` refers to a key in the data source. The values tell us which icon to use from the sprite sheet let expression = Exp(.switchCase) { // Switching on a value Exp(.eq) { // Evaluates if conditions are equal Exp(.get) { "POITYPE" } // Get the current value for `POITYPE` "Restroom" // returns true for the equal expression if the type is equal to "Restrooms" } "restrooms" // Use the icon named "restrooms" on the sprite sheet if the above condition is true Exp(.eq) { Exp(.get) { "POITYPE" } "Picnic Area" } "picnic-area" Exp(.eq) { Exp(.get) { "POITYPE" } "Trailhead" } "trailhead" "" // default case is to return an empty string so no icon will be loaded } // MARK: Explanation of expression // See https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#case for expression docs /* The expression yields the following JSON [case, [==, [get, POITYPE], Restroom], restrooms, [==, [get, POITYPE], Picnic Area], picnic-area, [==, [get, POITYPE], Trailhead], trailhead ] This is a switch statement that makes decisions on the Key `POITYPE` It will map the value of `POITYPE` to the image name on the sprite sheet. */ // MARK: Alternative expression that yields the same visual Output // See https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#match for expression docs // let expression = Exp(.match) { // Exp(.get) { "POITYPE" } // "Restroom" // "restrooms" // "Picnic Area" // "picnic-area" // "Trailhead" // "trailhead" // "" // } /* The expression yields the following JSON [match, [get, POITYPE], Restroom, restrooms, Picnic Area, picnic-area, Trailhead, trailhead ] This gets the POITYPE and matches the result of it to image name on the sprite sheet. */ layer.iconImage = .expression(expression) try! mapView.mapboxMap.style.addLayer(layer, layerPosition: nil) // The below line is used for internal testing purposes only. finish() } }
40.909091
116
0.592323
1e317ea88595d1db939a9885fc5c0c82e522154c
3,279
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation import azureSwiftRuntime internal struct ServicePrincipalData : ServicePrincipalProtocol, DirectoryObjectProtocol { public var additionalProperties: [String:[String: String?]]? public var objectId: String? public var deletionTimestamp: Date? public var displayName: String? public var appId: String? public var servicePrincipalNames: [String]? enum CodingKeys: String, CodingKey {case additionalProperties = "" case objectId = "objectId" case deletionTimestamp = "deletionTimestamp" case displayName = "displayName" case appId = "appId" case servicePrincipalNames = "servicePrincipalNames" } public init() { } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if container.contains(.additionalProperties) { self.additionalProperties = try container.decode([String:[String: String?]]?.self, forKey: .additionalProperties) } if container.contains(.objectId) { self.objectId = try container.decode(String?.self, forKey: .objectId) } if container.contains(.deletionTimestamp) { self.deletionTimestamp = DateConverter.fromString(dateStr: (try container.decode(String?.self, forKey: .deletionTimestamp)), format: .dateTime) } if container.contains(.displayName) { self.displayName = try container.decode(String?.self, forKey: .displayName) } if container.contains(.appId) { self.appId = try container.decode(String?.self, forKey: .appId) } if container.contains(.servicePrincipalNames) { self.servicePrincipalNames = try container.decode([String]?.self, forKey: .servicePrincipalNames) } if var pageDecoder = decoder as? PageDecoder { if pageDecoder.isPagedData, let nextLinkName = pageDecoder.nextLinkName { pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName) } } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if self.additionalProperties != nil {try container.encode(self.additionalProperties, forKey: .additionalProperties)} if self.objectId != nil {try container.encode(self.objectId, forKey: .objectId)} if self.deletionTimestamp != nil { try container.encode(DateConverter.toString(date: self.deletionTimestamp!, format: .dateTime), forKey: .deletionTimestamp) } if self.displayName != nil {try container.encode(self.displayName, forKey: .displayName)} if self.appId != nil {try container.encode(self.appId, forKey: .appId)} if self.servicePrincipalNames != nil {try container.encode(self.servicePrincipalNames as! [String]?, forKey: .servicePrincipalNames)} } } extension DataFactory { public static func createServicePrincipalProtocol() -> ServicePrincipalProtocol { return ServicePrincipalData() } }
45.541667
152
0.706923
3ab4a68cdd2f6a2a8fd37751fdf744bccdbf71f8
5,411
// // MMAPIKeysAndValues.swift // MobileMessaging // // Created by okoroleva on 08.03.16. // import Foundation struct Consts { static let UUIDRegexPattern = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" struct MessageFetchingSettings { static let messageArchiveLengthDays: Double = 7 // consider messages not older than N days static let fetchLimit = 100 // consider N most recent messages static let fetchingIterationLimit = 2 // fetching may trigger message handling, which in turn may trigger message fetching. This constant is here to break possible inifinite recursion. } struct KeychainKeys { static let prefix = "com.mobile-messaging" static let internalId = "internalId" } struct DynamicBaseUrlConsts { static let newBaseUrlHeader = "newbaseurl" static let storedDynamicBaseUrlKey = "com.mobile-messaging.dynamic-base-url" } struct APIKeys { static let messageId = "messageId" //MARK: delivery static let messageIDs = "messageIDs" //MARK: serviceErrors static let backendErrorDomain = "com.mobile-messaging.backend" static let requestError = "requestError" static let serviceException = "serviceException" static let errorText = "text" static let errorMessageId = "messageId" //MARK: seenMessages static let seenMessages = "messages" static let seenTimestampDelta = "timestampDelta" //MARK: Sync API static let archiveMsgIds = "mIDs" static let DLRMsgIds = "drIDs" //MARK: UserData API struct UserData { static let predefinedUserData = "predefinedUserData" static let customUserData = "customUserData" static let externalUserId = "externalUserId" static let failures = "failures" } //MARK: MO Messages API struct MO { static let failedMOMessageIDs = "failedMessageIDs" static let from = "from" static let messages = "messages" static let destination = "destination" static let text = "text" static let customPayload = "customPayload" static let messageId = "messageId" static let messageSentStatusCode = "statusCode" static let bulkId = "bulkId" static let initialMessageId = "initialMessageId" } } struct APIHeaders { static let foreground = "foreground" static let pushRegistrationId = "pushregistrationid" static let applicationcode = "applicationcode" } struct VersionCheck { //MARK: Library Version API static let lastCheckDateKey = "com.mobile-messaging.library-version-check.last-check-date" static let platformType = "platformType" static let libraryVersion = "libraryVersion" static let libraryVersionUpdateUrl = "updateUrl" } struct PushRegistration { //MARK: Registration API static let isEnabled = "pushRegistrationEnabled" static let platform = "platformType" static let deviceToken = "registrationId" static let internalId = "deviceApplicationInstanceId" static let expiredInternalId = "expiredDeviceApplicationInstanceId" } struct SystemDataKeys { //MARK: SystemData API static let sdkVersion = "sdkVersion" static let osVer = "osVersion" static let deviceManufacturer = "deviceManufacturer" static let deviceModel = "deviceModel" static let appVer = "applicationVersion" static let geofencingServiceEnabled = "geofencing" static let notificationsEnabled = "notificationsEnabled" static let deviceSecure = "deviceSecure" static let osLanguage = "osLanguage" } struct GeoReportingAPIKeys { static let reports = "reports" static let event = "event" static let geoAreaId = "geoAreaId" static let campaignId = "campaignId" static let messageId = "messageId" static let timestampDelta = "timestampDelta" static let finishedCampaignIds = "finishedCampaignIds" static let suspendedCampaignIds = "suspendedCampaignIds" static let messageIdsMap = "messageIds" static let sdkMessageId = "sdkMessageId" static let messages = "messages" } struct InternalDataKeys { static let event = "event" static let deliveryTime = "deliveryTime" static let silent = "silent" static let geo = "geo" static let messageTypeGeo = "geo" static let messageType = "messageType" static let attachments = "atts" static let sendDateTime = "sendDateTime" static let bulkId = "bulkId" static let showInApp = "inApp" static let inAppStyle = "inAppStyle" } struct CustomPayloadKeys { static let isChat: String = "isChat" } struct Attachments { struct Keys { static let url = "url" static let type = "t" } } struct DeliveryReport { static let dlrMessageIds = "dlrIds" } struct APNSPayloadKeys { //MARK: APNs static let payloads = "payloads" static let aps = "aps" static let alert = "alert" static let title = "title" static let body = "body" static let badge = "badge" static let sound = "sound" static let customPayload = "customPayload" static let internalData = "internalData" static let contentAvailable = "content-available" //MARK: Common fields static let messageId = "messageId" } struct APIValues { static let prodDynamicBaseURLString = "https://mobile.infobip.com" static let prodBaseURLString = "https://oneapi2.infobip.com" // not in use afte migration on https://mobile.infobip.com static let platformType = "APNS" } struct SDKSettings { static var messagesRetentionPeriod: TimeInterval = 7 * 24 * 60 * 60 //one week static var reachabilityMonitoringTimeout = DispatchTimeInterval.seconds(10) } }
30.22905
186
0.737941
64c2ef1e4cc48052d6147abc74c26ff7e1d942dc
1,759
// // PersonMDBTests.swift // TMDBSwift-iOS // // Created by Martin Pfundmair on 2018-10-13. // Copyright © 2018 George. All rights reserved. // import XCTest @testable import TMDBSwift class ChangesMDBTests: XCTestCase { let expecationTimeout: TimeInterval = 50 override func setUp() { super.setUp() TMDBConfig.apikey = "8a7a49369d1af6a70ec5a6787bbfcf79" } override func tearDown() { super.tearDown() } func testChanges() { var data: [ChangesMDB]! let expectation = self.expectation(description: "Wait for data to load.") ChangesMDB.changes(changeType: "movie") { api, responseData in data = responseData expectation.fulfill() } waitForExpectations(timeout: expecationTimeout, handler: nil) XCTAssertNotNil(data.first?.id) XCTAssertNotNil(data.first?.adult) } func testChangesWithEnum() { var data: [ChangesMDB]! let expectation = self.expectation(description: "Wait for data to load.") ChangesMDB.changes(type: .movie) { api, responseData in data = responseData expectation.fulfill() } waitForExpectations(timeout: expecationTimeout, handler: nil) XCTAssertNotNil(data.first?.id) XCTAssertNotNil(data.first?.adult) } func testChangesWithParam() { var data: [ChangesMDB]! var api: ClientReturn! let expectation = self.expectation(description: "Wait for data to load.") ChangesMDB.changes(type: .tv, page: 2) { responseApi, responseData in api = responseApi data = responseData expectation.fulfill() } waitForExpectations(timeout: expecationTimeout, handler: nil) XCTAssertNotNil(data.first?.id) XCTAssertNotNil(data.first?.adult) XCTAssertEqual(api.pageResults?.page, 2) } }
26.253731
77
0.698124
f9d5b59baa732ae9d17492dff80285a852edf1fb
2,855
// // OAuth2AuthConfig.swift // OAuth2 // // Created by Pascal Pfiffner on 16/11/15. // Copyright © 2015 Pascal Pfiffner. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #if os(iOS) import UIKit #endif /** Simple struct to hold settings describing how authorization appears to the user. */ public struct OAuth2AuthConfig { /// Sub-stuct holding configuration relevant to UI presentation. public struct UI { /// Title to propagate to views handled by OAuth2, such as OAuth2WebViewController. public var title: String? = nil /// By assigning your own UIBarButtonItem (!) you can override the back button that is shown in the iOS embedded web view (does NOT apply to `SFSafariViewController`). public var backButton: AnyObject? = nil /// If true it makes the login cancellable, otherwise the cancel button is not shown in the embedded web view. public var showCancelButton = true /// Starting with iOS 9, `SFSafariViewController` will be used for embedded authorization instead of our custom class. You can turn this off here. public var useSafariView = true #if os(iOS) /// By assigning your own style you can configure how the embedded authorization is presented. public var modalPresentationStyle = UIModalPresentationStyle.fullScreen /// Assign a UIColor here, to be applied to the Safari view controller (in iOS 10.10+) or the navigation's bar tint color if using the legacy web view controller. public var barTintColor: UIColor? = nil /// You can assign a UIColor here, which will be applied to Safari's (in iOS 10.10+) or the legacy web view controller's item tint colors (also see: `barTintColor`). public var controlTintColor: UIColor? = nil #endif } /// Whether to use an embedded web view for authorization (true) or the OS browser (false, the default). public var authorizeEmbedded = false /// Whether to automatically dismiss the auto-presented authorization screen. public var authorizeEmbeddedAutoDismiss = true /// Context information for the authorization flow: /// - iOS: The parent view controller to present from /// - macOS: An NSWindow from which to present a modal sheet _or_ `nil` to present in a new window public var authorizeContext: AnyObject? = nil /// UI-specific configuration. public var ui = UI() }
39.109589
169
0.740806
64cfd27d3c569aec1abd6d6a3bac4ba2f0aafe0e
4,517
// // Session.swift // OMDb // // Created by Daniel Torres on 4/21/20. // Copyright © 2020 dansTeam. All rights reserved. // import Foundation import GoogleSignIn import Firebase protocol SessionProtocol: class{ var user: User {get set} var observer:PropertyObserver? {get set} } protocol PropertyObserver : class { func willChange(propertyName: String, newPropertyValue: Any?) func didChange(propertyName: String, oldPropertyValue: Any?) } final class Session: NSObject, SessionProtocol{ init(user: User) { self.user = user } weak var observer:PropertyObserver? enum SessionKeys { static let userKey = "user" } var user: User { willSet(newValue) { observer?.willChange(propertyName: SessionKeys.userKey, newPropertyValue: newValue) } didSet { observer?.didChange(propertyName: SessionKeys.userKey, oldPropertyValue: oldValue) } } } extension Session: GIDSignInDelegate{ func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { if let error = error { if (error as NSError).code == GIDSignInErrorCode.hasNoAuthInKeychain.rawValue { print("The user has not signed in before or they have since signed out.") } else { print("\(error.localizedDescription)") } return } guard let authentication = user.authentication else { return } let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken) print("===auth with firebase===") Auth.auth().signIn(with: credential) {[weak self] (authResult, error) in guard let sSelf = self else { return } if let error = error { print("couldn't retrieve user info") print(error.localizedDescription) sSelf.user = UserNotLogged() return } // User is signed in // Perform any operations on signed in user here. let userId = user.userID guard let givenName = user.profile.givenName, let email = user.profile.email, let image = user.profile.imageURL(withDimension: 104*3) else{ print("couldn't retrieve user info") sSelf.user = UserNotLogged() return } let profileFromUserLoggedIn = Profile(id: userId ?? "1", email: email, name: givenName, urlImageProfile: image) sSelf.user = profileFromUserLoggedIn } } func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) { // Perform any operations when the user disconnects from app here. let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() } catch let signOutError as NSError { print ("Error signing out: %@", signOutError) } self.user = UserNotLogged() } } protocol ObserverCollection { func addObserver(observer: PropertyObserver) func removeAll() } protocol ObserverMediator: PropertyObserver & ObserverCollection { } final class SessionObserverMediator: ObserverMediator { var sessionObservers: [PropertyObserver] init(){ self.sessionObservers = [PropertyObserver]() } func willChange(propertyName: String, newPropertyValue: Any?) { for sessionObserver in sessionObservers { sessionObserver.willChange(propertyName: propertyName, newPropertyValue: newPropertyValue) } } func didChange(propertyName: String, oldPropertyValue: Any?) { for sessionObserver in sessionObservers { sessionObserver.didChange(propertyName: propertyName, oldPropertyValue: oldPropertyValue) } } func addObserver(observer: PropertyObserver) { sessionObservers.append(observer) } func removeAll(){ sessionObservers.removeAll() } }
31.587413
97
0.575161
e5b10234ff3c550f6d853ed0b1cd6f0fae2cc819
303
/* nil coalescing operator & anonymous function * * The ?? operator sets the variable to the first option if it is not * nil, and otherwise sets it to the second option. * This might be helpful to guarantee that a var has a value. */ var v:String? = nil v = v ?? { return "No" }() print(v!)
21.642857
70
0.666667
116763534161a187b0e8a0e4f8ce7fdba794a03a
1,463
import Foundation // MARK: 1st Derivative postfix operator ′ public postfix func ′(function: @escaping (Double) -> (Double)) -> (Double) -> (Double) { let h = 1e-3 return { return round((function($0 + h) - function($0 - h)) / (2 * h) / h) * h } } // MARK: 2nd Derivative postfix operator ′′ public postfix func ′′(function: @escaping (Double) -> (Double)) -> (Double) -> (Double) { return (function′)′ } // MARK: 3rd Derivative postfix operator ′′′ public postfix func ′′′(function: @escaping (Double) -> (Double)) -> (Double) -> (Double) { return ((function′)′)′ } // MARK: Nth Derivative infix operator ′ : MultiplicationPrecedence public func ′(lhs: inout (Double) -> Double, rhs: UInt) -> (Double) -> (Double) { return (0..<rhs).reduce(lhs) { (function, _) in return function′ } } // MARK: Definite Integral infix operator ∫ : MultiplicationPrecedence public func ∫(lhs: (a: Double, b: Double), rhs: (Double) -> (Double)) -> Double { let n = Int(1e2 + 1) let h = (lhs.b - lhs.a) / Double(n) return (h / 3.0) * (1..<n).reduce(rhs(lhs.a)) { let coefficient = $1 % 2 == 0 ? 4.0 : 2.0 return $0 + coefficient * rhs(lhs.a + Double($1) * h) } + rhs(lhs.b) } // MARK: Indefinite Integral / Antiderivative prefix operator ∫ public prefix func ∫(function: @escaping (Double) -> (Double)) -> (Double) -> (Double) { return { x in return (0, x)∫function } }
25.666667
91
0.585783
89ffdae9dbce026fb9c287d08fcd79818778ee30
13,206
// Test/Sources/TestSuite/Test_BasicFields_Access_Proto3.swift // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Exercises the apis for optional & repeated fields. /// // ----------------------------------------------------------------------------- import XCTest import Foundation // NOTE: The generator changes what is generated based on the number/types // of fields (using a nested storage class or not), to be completel, all // these tests should be done once with a message that gets that storage // class and a second time with messages that avoid that. class Test_BasicFields_Access_Proto3: XCTestCase { // Optional func testOptionalInt32() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleInt32, 0) msg.singleInt32 = 1 XCTAssertEqual(msg.singleInt32, 1) } func testOptionalInt64() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleInt64, 0) msg.singleInt64 = 2 XCTAssertEqual(msg.singleInt64, 2) } func testOptionalUint32() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleUint32, 0) msg.singleUint32 = 3 XCTAssertEqual(msg.singleUint32, 3) } func testOptionalUint64() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleUint64, 0) msg.singleUint64 = 4 XCTAssertEqual(msg.singleUint64, 4) } func testOptionalSint32() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleSint32, 0) msg.singleSint32 = 5 XCTAssertEqual(msg.singleSint32, 5) } func testOptionalSint64() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleSint64, 0) msg.singleSint64 = 6 XCTAssertEqual(msg.singleSint64, 6) } func testOptionalFixed32() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleFixed32, 0) msg.singleFixed32 = 7 XCTAssertEqual(msg.singleFixed32, 7) } func testOptionalFixed64() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleFixed64, 0) msg.singleFixed64 = 8 XCTAssertEqual(msg.singleFixed64, 8) } func testOptionalSfixed32() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleSfixed32, 0) msg.singleSfixed32 = 9 XCTAssertEqual(msg.singleSfixed32, 9) } func testOptionalSfixed64() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleSfixed64, 0) msg.singleSfixed64 = 10 XCTAssertEqual(msg.singleSfixed64, 10) } func testOptionalFloat() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleFloat, 0.0) msg.singleFloat = 11.0 XCTAssertEqual(msg.singleFloat, 11.0) } func testOptionalDouble() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleDouble, 0.0) msg.singleDouble = 12.0 XCTAssertEqual(msg.singleDouble, 12.0) } func testOptionalBool() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleBool, false) msg.singleBool = true XCTAssertEqual(msg.singleBool, true) } func testOptionalString() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleString, "") msg.singleString = "14" XCTAssertEqual(msg.singleString, "14") } func testOptionalBytes() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleBytes, Data()) msg.singleBytes = Data([15]) XCTAssertEqual(msg.singleBytes, Data([15])) } func testOptionalNestedMessage() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleNestedMessage.bb, 0) var nestedMsg = Proto3TestAllTypes.NestedMessage() nestedMsg.bb = 18 msg.singleNestedMessage = nestedMsg XCTAssertEqual(msg.singleNestedMessage.bb, 18) XCTAssertEqual(msg.singleNestedMessage, nestedMsg) } func testOptionalForeignMessage() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleForeignMessage.c, 0) var foreignMsg = Proto3ForeignMessage() foreignMsg.c = 19 msg.singleForeignMessage = foreignMsg XCTAssertEqual(msg.singleForeignMessage.c, 19) XCTAssertEqual(msg.singleForeignMessage, foreignMsg) } func testOptionalImportMessage() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleImportMessage.d, 0) var importedMsg = Proto3ImportMessage() importedMsg.d = 20 msg.singleImportMessage = importedMsg XCTAssertEqual(msg.singleImportMessage.d, 20) XCTAssertEqual(msg.singleImportMessage, importedMsg) } func testOptionalNestedEnum() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleNestedEnum, .unspecified) msg.singleNestedEnum = .bar XCTAssertEqual(msg.singleNestedEnum, .bar) } func testOptionalForeignEnum() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleForeignEnum, .foreignUnspecified) msg.singleForeignEnum = .foreignBar XCTAssertEqual(msg.singleForeignEnum, .foreignBar) } func testOptionalImportEnum() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singleImportEnum, .unspecified) msg.singleImportEnum = .importBar XCTAssertEqual(msg.singleImportEnum, .importBar) } func testOptionalPublicImportMessage() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.singlePublicImportMessage.e, 0) var pubImportedMsg = Proto3PublicImportMessage() pubImportedMsg.e = 26 msg.singlePublicImportMessage = pubImportedMsg XCTAssertEqual(msg.singlePublicImportMessage.e, 26) XCTAssertEqual(msg.singlePublicImportMessage, pubImportedMsg) } // Repeated func testRepeatedInt32() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedInt32, []) msg.repeatedInt32 = [31] XCTAssertEqual(msg.repeatedInt32, [31]) msg.repeatedInt32.append(131) XCTAssertEqual(msg.repeatedInt32, [31, 131]) } func testRepeatedInt64() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedInt64, []) msg.repeatedInt64 = [32] XCTAssertEqual(msg.repeatedInt64, [32]) msg.repeatedInt64.append(132) XCTAssertEqual(msg.repeatedInt64, [32, 132]) } func testRepeatedUint32() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedUint32, []) msg.repeatedUint32 = [33] XCTAssertEqual(msg.repeatedUint32, [33]) msg.repeatedUint32.append(133) XCTAssertEqual(msg.repeatedUint32, [33, 133]) } func testRepeatedUint64() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedUint64, []) msg.repeatedUint64 = [34] XCTAssertEqual(msg.repeatedUint64, [34]) msg.repeatedUint64.append(134) XCTAssertEqual(msg.repeatedUint64, [34, 134]) } func testRepeatedSint32() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedSint32, []) msg.repeatedSint32 = [35] XCTAssertEqual(msg.repeatedSint32, [35]) msg.repeatedSint32.append(135) XCTAssertEqual(msg.repeatedSint32, [35, 135]) } func testRepeatedSint64() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedSint64, []) msg.repeatedSint64 = [36] XCTAssertEqual(msg.repeatedSint64, [36]) msg.repeatedSint64.append(136) XCTAssertEqual(msg.repeatedSint64, [36, 136]) } func testRepeatedFixed32() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedFixed32, []) msg.repeatedFixed32 = [37] XCTAssertEqual(msg.repeatedFixed32, [37]) msg.repeatedFixed32.append(137) XCTAssertEqual(msg.repeatedFixed32, [37, 137]) } func testRepeatedFixed64() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedFixed64, []) msg.repeatedFixed64 = [38] XCTAssertEqual(msg.repeatedFixed64, [38]) msg.repeatedFixed64.append(138) XCTAssertEqual(msg.repeatedFixed64, [38, 138]) } func testRepeatedSfixed32() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedSfixed32, []) msg.repeatedSfixed32 = [39] XCTAssertEqual(msg.repeatedSfixed32, [39]) msg.repeatedSfixed32.append(139) XCTAssertEqual(msg.repeatedSfixed32, [39, 139]) } func testRepeatedSfixed64() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedSfixed64, []) msg.repeatedSfixed64 = [40] XCTAssertEqual(msg.repeatedSfixed64, [40]) msg.repeatedSfixed64.append(140) XCTAssertEqual(msg.repeatedSfixed64, [40, 140]) } func testRepeatedFloat() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedFloat, []) msg.repeatedFloat = [41.0] XCTAssertEqual(msg.repeatedFloat, [41.0]) msg.repeatedFloat.append(141.0) XCTAssertEqual(msg.repeatedFloat, [41.0, 141.0]) } func testRepeatedDouble() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedDouble, []) msg.repeatedDouble = [42.0] XCTAssertEqual(msg.repeatedDouble, [42.0]) msg.repeatedDouble.append(142.0) XCTAssertEqual(msg.repeatedDouble, [42.0, 142.0]) } func testRepeatedBool() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedBool, []) msg.repeatedBool = [true] XCTAssertEqual(msg.repeatedBool, [true]) msg.repeatedBool.append(false) XCTAssertEqual(msg.repeatedBool, [true, false]) } func testRepeatedString() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedString, []) msg.repeatedString = ["44"] XCTAssertEqual(msg.repeatedString, ["44"]) msg.repeatedString.append("144") XCTAssertEqual(msg.repeatedString, ["44", "144"]) } func testRepeatedBytes() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedBytes, []) msg.repeatedBytes = [Data([45])] XCTAssertEqual(msg.repeatedBytes, [Data([45])]) msg.repeatedBytes.append(Data([145])) XCTAssertEqual(msg.repeatedBytes, [Data([45]), Data([145])]) } func testRepeatedNestedMessage() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedNestedMessage, []) var nestedMsg = Proto3TestAllTypes.NestedMessage() nestedMsg.bb = 48 msg.repeatedNestedMessage = [nestedMsg] XCTAssertEqual(msg.repeatedNestedMessage.count, 1) XCTAssertEqual(msg.repeatedNestedMessage[0].bb, 48) XCTAssertEqual(msg.repeatedNestedMessage, [nestedMsg]) var nestedMsg2 = Proto3TestAllTypes.NestedMessage() nestedMsg2.bb = 148 msg.repeatedNestedMessage.append(nestedMsg2) XCTAssertEqual(msg.repeatedNestedMessage.count, 2) XCTAssertEqual(msg.repeatedNestedMessage[0].bb, 48) XCTAssertEqual(msg.repeatedNestedMessage[1].bb, 148) XCTAssertEqual(msg.repeatedNestedMessage, [nestedMsg, nestedMsg2]) } func testRepeatedForeignMessage() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedForeignMessage, []) var foreignMsg = Proto3ForeignMessage() foreignMsg.c = 49 msg.repeatedForeignMessage = [foreignMsg] XCTAssertEqual(msg.repeatedForeignMessage.count, 1) XCTAssertEqual(msg.repeatedForeignMessage[0].c, 49) XCTAssertEqual(msg.repeatedForeignMessage, [foreignMsg]) var foreignMsg2 = Proto3ForeignMessage() foreignMsg2.c = 149 msg.repeatedForeignMessage.append(foreignMsg2) XCTAssertEqual(msg.repeatedForeignMessage.count, 2) XCTAssertEqual(msg.repeatedForeignMessage[0].c, 49) XCTAssertEqual(msg.repeatedForeignMessage[1].c, 149) XCTAssertEqual(msg.repeatedForeignMessage, [foreignMsg, foreignMsg2]) } func testRepeatedImportMessage() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedImportMessage, []) var importedMsg = Proto3ImportMessage() importedMsg.d = 50 msg.repeatedImportMessage = [importedMsg] XCTAssertEqual(msg.repeatedImportMessage.count, 1) XCTAssertEqual(msg.repeatedImportMessage[0].d, 50) XCTAssertEqual(msg.repeatedImportMessage, [importedMsg]) var importedMsg2 = Proto3ImportMessage() importedMsg2.d = 150 msg.repeatedImportMessage.append(importedMsg2) XCTAssertEqual(msg.repeatedImportMessage.count, 2) XCTAssertEqual(msg.repeatedImportMessage[0].d, 50) XCTAssertEqual(msg.repeatedImportMessage[1].d, 150) XCTAssertEqual(msg.repeatedImportMessage, [importedMsg, importedMsg2]) } func testRepeatedNestedEnum() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedNestedEnum, []) msg.repeatedNestedEnum = [.bar] XCTAssertEqual(msg.repeatedNestedEnum, [.bar]) msg.repeatedNestedEnum.append(.baz) XCTAssertEqual(msg.repeatedNestedEnum, [.bar, .baz]) } func testRepeatedForeignEnum() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedForeignEnum, []) msg.repeatedForeignEnum = [.foreignBar] XCTAssertEqual(msg.repeatedForeignEnum, [.foreignBar]) msg.repeatedForeignEnum.append(.foreignBaz) XCTAssertEqual(msg.repeatedForeignEnum, [.foreignBar, .foreignBaz]) } func testRepeatedImportEnum() { var msg = Proto3TestAllTypes() XCTAssertEqual(msg.repeatedImportEnum, []) msg.repeatedImportEnum = [.importBar] XCTAssertEqual(msg.repeatedImportEnum, [.importBar]) msg.repeatedImportEnum.append(.importBaz) XCTAssertEqual(msg.repeatedImportEnum, [.importBar, .importBaz]) } }
32.053398
80
0.715205
e4690c9a8e1c1f5a193a8d8d16b8665759d9b953
3,288
// // CourseDashboardCell.swift // edX // // Created by Jianfeng Qiu on 13/05/2015. // Copyright (c) 2015 edX. All rights reserved. // import UIKit class CourseDashboardCell: UITableViewCell { static let identifier = "CourseDashboardCellIdentifier" //TODO: all these should be adjusted once the final UI is ready private let ICON_SIZE : CGFloat = OEXTextStyle.pointSizeForTextSize(OEXTextSize.XXLarge) private let ICON_MARGIN : CGFloat = 30.0 private let LABEL_MARGIN : CGFloat = 75.0 private let LABEL_SIZE_HEIGHT = 20.0 private let CONTAINER_SIZE_HEIGHT = 60.0 private let CONTAINER_MARGIN_BOTTOM = 15.0 private let INDICATOR_SIZE_WIDTH = 10.0 private let container = UIView() private let iconView = UIImageView() private let titleLabel = UILabel() private let detailLabel = UILabel() private let bottomLine = UIView() private var titleTextStyle : OEXTextStyle { return OEXTextStyle(weight : .Normal, size: .Base, color : OEXStyles.sharedStyles().neutralXDark()) } private var detailTextStyle : OEXTextStyle { return OEXTextStyle(weight : .Normal, size: .XXSmall, color : OEXStyles.sharedStyles().neutralBase()) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) configureViews() } func useItem(item : StandardCourseDashboardItem) { self.titleLabel.attributedText = titleTextStyle.attributedStringWithText(item.title) self.detailLabel.attributedText = detailTextStyle.attributedStringWithText(item.detail) self.iconView.image = item.icon.imageWithFontSize(ICON_SIZE) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func configureViews() { self.bottomLine.backgroundColor = OEXStyles.sharedStyles().neutralXLight() applyStandardSeparatorInsets() self.container.addSubview(iconView) self.container.addSubview(titleLabel) self.container.addSubview(detailLabel) self.contentView.addSubview(container) self.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator iconView.tintColor = OEXStyles.sharedStyles().neutralLight() container.snp_makeConstraints { make -> Void in make.edges.equalTo(contentView) } iconView.snp_makeConstraints { (make) -> Void in make.leading.equalTo(container).offset(ICON_MARGIN) make.centerY.equalTo(container) } titleLabel.snp_makeConstraints { (make) -> Void in make.leading.equalTo(container).offset(LABEL_MARGIN) make.trailing.lessThanOrEqualTo(container) make.top.equalTo(container).offset(LABEL_SIZE_HEIGHT) make.height.equalTo(LABEL_SIZE_HEIGHT) } detailLabel.snp_makeConstraints { (make) -> Void in make.leading.equalTo(titleLabel) make.trailing.lessThanOrEqualTo(container) make.top.equalTo(titleLabel.snp_bottom) make.height.equalTo(LABEL_SIZE_HEIGHT) } } }
36.131868
109
0.675791
9cf412919159e06d6a99102ef6a93493682d82f5
8,451
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import CNIOSHA1 import NIO import NIOHTTP1 private let magicWebSocketGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" /// Errors that can be thrown by `NIOWebSocket` during protocol upgrade. public enum NIOWebSocketUpgradeError: Error { /// A HTTP header on the upgrade request was invalid. case invalidUpgradeHeader /// The HTTP request targets a websocket pipeline that does not support /// it in some way. case unsupportedWebSocketTarget } fileprivate extension HTTPHeaders { func nonListHeader(_ name: String) throws -> String { let fields = self[canonicalForm: name] guard fields.count == 1 else { throw NIOWebSocketUpgradeError.invalidUpgradeHeader } return fields.first! } } /// A `HTTPProtocolUpgrader` that knows how to do the WebSocket upgrade dance. /// /// Users may frequently want to offer multiple websocket endpoints on the same port. For this /// reason, this `WebSocketUpgrader` only knows how to do the required parts of the upgrade and to /// complete the handshake. Users are expected to provide a callback that examines the HTTP headers /// (including the path) and determines whether this is a websocket upgrade request that is acceptable /// to them. /// /// This upgrader assumes that the `HTTPServerUpgradeHandler` will appropriately mutate the pipeline to /// remove the HTTP `ChannelHandler`s. public final class WebSocketUpgrader: HTTPProtocolUpgrader { /// RFC 6455 specs this as the required entry in the Upgrade header. public let supportedProtocol: String = "websocket" /// We deliberately do not actually set any required headers here, because the websocket /// spec annoyingly does not actually force the client to send these in the Upgrade header, /// which NIO requires. We check for these manually. public let requiredUpgradeHeaders: [String] = [] private let shouldUpgrade: (HTTPRequestHead) -> HTTPHeaders? private let upgradePipelineHandler: (Channel, HTTPRequestHead) -> EventLoopFuture<Void> private let maxFrameSize: Int private let automaticErrorHandling: Bool /// Create a new `WebSocketUpgrader`. /// /// - parameters: /// - automaticErrorHandling: Whether the pipeline should automatically handle protocol /// errors by sending error responses and closing the connection. Defaults to `true`, /// may be set to `false` if the user wishes to handle their own errors. /// - shouldUpgrade: A callback that determines whether the websocket request should be /// upgraded. This callback is responsible for creating a `HTTPHeaders` object with /// any headers that it needs on the response *except for* the `Upgrade`, `Connection`, /// and `Sec-WebSocket-Accept` headers, which this upgrader will handle. Should return /// `nil` if the upgrade should be refused. /// - upgradePipelineHandler: A function that will be called once the upgrade response is /// flushed, and that is expected to mutate the `Channel` appropriately to handle the /// websocket protocol. This only needs to add the user handlers: the /// `WebSocketFrameEncoder` and `WebSocketFrameDecoder` will have been added to the /// pipeline automatically. public convenience init(automaticErrorHandling: Bool = true, shouldUpgrade: @escaping (HTTPRequestHead) -> HTTPHeaders?, upgradePipelineHandler: @escaping (Channel, HTTPRequestHead) -> EventLoopFuture<Void>) { self.init(maxFrameSize: 1 << 14, automaticErrorHandling: automaticErrorHandling, shouldUpgrade: shouldUpgrade, upgradePipelineHandler: upgradePipelineHandler) } /// Create a new `WebSocketUpgrader`. /// /// - parameters: /// - maxFrameSize: The maximum frame size the decoder is willing to tolerate from the /// remote peer. WebSockets in principle allows frame sizes up to `2**64` bytes, but /// this is an objectively unreasonable maximum value (on AMD64 systems it is not /// possible to even. Users may set this to any value up to `UInt32.max`. /// - automaticErrorHandling: Whether the pipeline should automatically handle protocol /// errors by sending error responses and closing the connection. Defaults to `true`, /// may be set to `false` if the user wishes to handle their own errors. /// - shouldUpgrade: A callback that determines whether the websocket request should be /// upgraded. This callback is responsible for creating a `HTTPHeaders` object with /// any headers that it needs on the response *except for* the `Upgrade`, `Connection`, /// and `Sec-WebSocket-Accept` headers, which this upgrader will handle. Should return /// `nil` if the upgrade should be refused. /// - upgradePipelineHandler: A function that will be called once the upgrade response is /// flushed, and that is expected to mutate the `Channel` appropriately to handle the /// websocket protocol. This only needs to add the user handlers: the /// `WebSocketFrameEncoder` and `WebSocketFrameDecoder` will have been added to the /// pipeline automatically. public init(maxFrameSize: Int, automaticErrorHandling: Bool = true, shouldUpgrade: @escaping (HTTPRequestHead) -> HTTPHeaders?, upgradePipelineHandler: @escaping (Channel, HTTPRequestHead) -> EventLoopFuture<Void>) { precondition(maxFrameSize <= UInt32.max, "invalid overlarge max frame size") self.shouldUpgrade = shouldUpgrade self.upgradePipelineHandler = upgradePipelineHandler self.maxFrameSize = maxFrameSize self.automaticErrorHandling = automaticErrorHandling } public func buildUpgradeResponse(upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) throws -> HTTPHeaders { let key = try upgradeRequest.headers.nonListHeader("Sec-WebSocket-Key") let version = try upgradeRequest.headers.nonListHeader("Sec-WebSocket-Version") // The version must be 13. guard version == "13" else { throw NIOWebSocketUpgradeError.invalidUpgradeHeader } guard var extraHeaders = self.shouldUpgrade(upgradeRequest) else { throw NIOWebSocketUpgradeError.unsupportedWebSocketTarget } // Cool, we're good to go! Let's do our upgrade. We do this by concatenating the magic // GUID to the base64-encoded key and taking a SHA1 hash of the result. let acceptValue: String do { var hasher = SHA1() hasher.update(string: key) hasher.update(string: magicWebSocketGUID) acceptValue = String(base64Encoding: hasher.finish()) } extraHeaders.replaceOrAdd(name: "Upgrade", value: "websocket") extraHeaders.add(name: "Sec-WebSocket-Accept", value: acceptValue) extraHeaders.replaceOrAdd(name: "Connection", value: "upgrade") return extraHeaders } public func upgrade(ctx: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> { /// We never use the automatic error handling feature of the WebSocketFrameDecoder: we always use the separate channel /// handler. var upgradeFuture = ctx.pipeline.add(handler: WebSocketFrameEncoder()).flatMap { ctx.pipeline.add(handler: ByteToMessageHandler(WebSocketFrameDecoder(maxFrameSize: self.maxFrameSize, automaticErrorHandling: false))) } if self.automaticErrorHandling { upgradeFuture = upgradeFuture.flatMap { ctx.pipeline.add(handler: WebSocketProtocolErrorHandler())} } return upgradeFuture.flatMap { self.upgradePipelineHandler(ctx.channel, upgradeRequest) } } }
51.846626
146
0.684771
48499a01eec66218f23c69d1b5944034b6d8f6fd
3,773
// // ViewController.swift // ScrollViewNestPageView // // Created by Migu on 2018/8/29. // Copyright © 2018年 VIctorChee. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet var headerView: UIView! @IBOutlet weak var headerViewTopContstraint: NSLayoutConstraint! @IBOutlet weak var segmentedBar: SegmentedBar! private var topShowingHeight: CGFloat { if headerView.frame.minX >= 0 { return segmentedBar.frame.maxY } else { return segmentedBar.frame.maxY + headerView.frame.minY } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. collectionView.contentInsetAdjustmentBehavior = .never } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "contentOffset" { guard let offset = change?[NSKeyValueChangeKey.newKey] as? CGPoint else { return } var constant = -offset.y if constant < -headerView.bounds.height { // SegmentedBar吸顶 constant = -headerView.bounds.height } headerViewTopContstraint.constant = constant headerView.superview?.layoutIfNeeded() } } } extension ViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 3 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ContentCollectionViewCell", for: indexPath) as! ContentCollectionViewCell if indexPath.item == 0 { cell.backgroundColor = UIColor.orange } else if indexPath.item == 1 { cell.backgroundColor = UIColor.purple } else { cell.backgroundColor = UIColor.cyan } if let controller = cell.collectionViewController { controller.collectionView?.reloadData() } else { if let controller = storyboard?.instantiateViewController(withIdentifier: "CollectionViewController") as? CollectionViewController { cell.collectionViewController = controller } } cell.collectionViewController?.placeholderHeight = topShowingHeight cell.collectionViewController?.collectionView?.addObserver(self, forKeyPath: "contentOffset", options: [.old, .new], context: nil) return cell } } extension ViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { guard let layout = collectionViewLayout as? UICollectionViewFlowLayout else { return CGSize.zero } let width = collectionView.bounds.width - layout.sectionInset.left - layout.sectionInset.right - collectionView.adjustedContentInset.left - collectionView.adjustedContentInset.right let height = collectionView.bounds.height - layout.sectionInset.top - layout.sectionInset.bottom - collectionView.adjustedContentInset.top - collectionView.adjustedContentInset.bottom return CGSize(width: width, height: height) } }
42.875
191
0.692817
f486f4b51ce66afd5cda92e6e75d41bf21a0d257
944
// // PropertyGenerationModel.swift // SurfGenKit // // Created by Mikhail Monakov on 18/03/2020. // public struct PropertyGenerationModel: Equatable { let entryName: String let type: String let entityName: String let fromInit: String let toDTOInit: String let isPlain: Bool // indicates that type is standard (Int, Bool) or its array of standard type let isOptional: Bool let description: String? init(entryName: String, entityName: String, typeName: String, fromInit: String, toDTOInit: String, isPlain: Bool, isOptional: Bool, description: String?) { self.entryName = entryName self.entityName = entityName self.type = typeName self.fromInit = fromInit self.toDTOInit = toDTOInit self.isPlain = isPlain self.isOptional = isOptional self.description = description } }
24.842105
98
0.636653
38a947ebafb69717f1858142b2c3ba5c7bfd2672
855
import Foundation public extension PersistedValue where Value == Data? { func string(using encoding: String.Encoding = .utf8) -> PersistedValues.Map<Self, String?> { self.map( transform: { $0.flatMap { String(data: $0, encoding: encoding) } }, untransform: { $0.flatMap { $0.data(using: encoding) } } ) } func integer<T>(_ type: T.Type) -> PersistedValues.Map<PersistedValues.Map<Self, String?>, T?> where T: FixedWidthInteger { self.string() .map( transform: { $0.flatMap(T.init) }, untransform: { $0.flatMap { "\($0)" } } ) } func bool() -> PersistedValues.Map<Self, Bool?> { self.map( transform: { $0.map { $0.first == 1 } }, untransform: { $0.map { Data($0 ? [1] : []) } } ) } }
31.666667
127
0.520468
ff4c761082c9d48d743f704a13e28b240e8f0d2c
328
// // FloatingPointExtension.swift // racing-game // // Created by Argentino Ducret on 5/10/17. // Copyright © 2017 ITBA. All rights reserved. // public extension FloatingPoint { public var degreesToRadians: Self { return self * .pi / 180 } public var radiansToDegrees: Self { return self * 180 / .pi } }
21.866667
65
0.664634
0a38f6b7879651d87d2e98417afe3c9e5e2a00bc
5,277
/* This source file is part of the Swift.org open source project Copyright (c) 2021 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ @testable import Basics @testable import Commands import SPMTestSupport import TSCBasic import XCTest final class SwiftToolTests: CommandsTestCase { func testVerbosityLogLevel() throws { fixture(name: "Miscellaneous/Simple") { packageRoot in do { let options = try SwiftToolOptions.parse(["--package-path", packageRoot.pathString]) let tool = try SwiftTool(options: options) XCTAssertEqual(tool.logLevel, .warning) tool.observabilityScope.emit(error: "error") tool.observabilityScope.emit(warning: "warning") tool.observabilityScope.emit(info: "info") tool.observabilityScope.emit(debug: "debug") } do { let options = try SwiftToolOptions.parse(["--package-path", packageRoot.pathString, "--verbose"]) let tool = try SwiftTool(options: options) XCTAssertEqual(tool.logLevel, .info) tool.observabilityScope.emit(error: "error") tool.observabilityScope.emit(warning: "warning") tool.observabilityScope.emit(info: "info") tool.observabilityScope.emit(debug: "debug") } do { let options = try SwiftToolOptions.parse(["--package-path", packageRoot.pathString, "-v"]) let tool = try SwiftTool(options: options) XCTAssertEqual(tool.logLevel, .info) } do { let options = try SwiftToolOptions.parse(["--package-path", packageRoot.pathString, "--very-verbose"]) let tool = try SwiftTool(options: options) XCTAssertEqual(tool.logLevel, .debug) tool.observabilityScope.emit(error: "error") tool.observabilityScope.emit(warning: "warning") tool.observabilityScope.emit(info: "info") tool.observabilityScope.emit(debug: "debug") } do { let options = try SwiftToolOptions.parse(["--package-path", packageRoot.pathString, "--vv"]) let tool = try SwiftTool(options: options) XCTAssertEqual(tool.logLevel, .debug) } } } func testNetrcAuthorizationProviders() throws { fixture(name: "DependencyResolution/External/XCFramework") { packageRoot in let fs = localFileSystem let localPath = packageRoot.appending(component: ".netrc") // custom .netrc file do { let customPath = fs.homeDirectory.appending(component: UUID().uuidString) try fs.writeFileContents(customPath) { "machine mymachine.labkey.org login [email protected] password custom" } let options = try SwiftToolOptions.parse(["--package-path", packageRoot.pathString, "--netrc-file", customPath.pathString]) let tool = try SwiftTool(options: options) let netrcProviders = try tool.getNetrcAuthorizationProviders() XCTAssertEqual(netrcProviders.count, 1) XCTAssertEqual(netrcProviders.first.map { resolveSymlinks($0.path) }, resolveSymlinks(customPath)) let auth = try tool.getAuthorizationProvider()?.authentication(for: URL(string: "https://mymachine.labkey.org")!) XCTAssertEqual(auth?.user, "[email protected]") XCTAssertEqual(auth?.password, "custom") // delete it try localFileSystem.removeFileTree(customPath) XCTAssertThrowsError(try tool.getNetrcAuthorizationProviders(), "error expected") { error in XCTAssertEqual(error as? StringError, StringError("Did not find .netrc file at \(customPath).")) } } // local .netrc file do { try fs.writeFileContents(localPath) { return "machine mymachine.labkey.org login [email protected] password local" } let options = try SwiftToolOptions.parse(["--package-path", packageRoot.pathString]) let tool = try SwiftTool(options: options) let netrcProviders = try tool.getNetrcAuthorizationProviders() XCTAssertTrue(netrcProviders.count >= 1) // This might include .netrc in user's home dir XCTAssertNotNil(netrcProviders.first { resolveSymlinks($0.path) == resolveSymlinks(localPath) }) let auth = try tool.getAuthorizationProvider()?.authentication(for: URL(string: "https://mymachine.labkey.org")!) XCTAssertEqual(auth?.user, "[email protected]") XCTAssertEqual(auth?.password, "local") } // Tests should not modify user's home dir .netrc so leaving that out intentionally } } }
43.975
139
0.605079
8ae249d08010cc589281c5c1d58c0d1e195b4755
1,879
// // ListViewController.swift // CurveExample // // Created by Hani on 27.10.18. // Copyright © 2018 Hani. All rights reserved. // import UIKit final class ListViewController: UITableViewController { override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section == 0 ? "Drawing Examples" : "Animation Examples" } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? SampleCurve.allCases.count : SamplePolynomialCurve.allCases.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "drawingCell", for: indexPath) cell.textLabel?.text = SampleCurve.allCases[indexPath.row].title return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "animationCell", for: indexPath) cell.textLabel?.text = SamplePolynomialCurve.allCases[indexPath.row].title return cell } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let cell = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) else { return } if let viewController = segue.destination as? DrawingViewController { viewController.sampleCurve = SampleCurve.allCases[indexPath.row] } else if let viewController = segue.destination as? AnimationViewController { viewController.sampleCurve = SamplePolynomialCurve.allCases[indexPath.row] } } }
37.58
109
0.668441
ebc4588473f6faa98b4000255d120e4b5f0280a4
1,213
// // ForumThread+CoreDataProperties.swift // Saralin // // Created by zhang on 2019/9/3. // Copyright © 2019 zaczh. All rights reserved. // // import Foundation import CoreData extension ForumThread { @nonobjc public class func fetchRequest() -> NSFetchRequest<ForumThread> { return NSFetchRequest<ForumThread>(entityName: "ForumThread") } @NSManaged public var authorid: String? @NSManaged public var authorname: String? @NSManaged public var containedimagescount: NSNumber? @NSManaged public var createdate: Date? @NSManaged public var createdeviceidentifier: String? @NSManaged public var createdevicename: String? @NSManaged public var fid: String? @NSManaged public var isnew: NSNumber? @NSManaged public var issettop: NSNumber? @NSManaged public var lastreplydate: Date? @NSManaged public var lasttimeviewed: Date? @NSManaged public var newreplycount: NSNumber? @NSManaged public var readlevel: NSNumber? @NSManaged public var replycount: NSNumber? @NSManaged public var tid: String? @NSManaged public var timemodified: Date? @NSManaged public var title: String? @NSManaged public var viewcount: NSNumber? }
30.325
78
0.731245
1137fc799c7761ad1374f0fd9885847a31e1294d
2,355
/* * Copyright (c) 2014 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. * * 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 class Album: NSObject, NSCoding { var title : String! var artist : String! var genre : String! var coverUrl : String! var year : String! init(title: String, artist: String, genre: String, coverUrl: String, year: String) { super.init() self.title = title self.artist = artist self.genre = genre self.coverUrl = coverUrl self.year = year } required init(coder decoder: NSCoder) { super.init() self.title = decoder.decodeObjectForKey("title") as String? self.artist = decoder.decodeObjectForKey("artist") as String? self.genre = decoder.decodeObjectForKey("genre") as String? self.coverUrl = decoder.decodeObjectForKey("cover_url") as String? self.year = decoder.decodeObjectForKey("year") as String? } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(title, forKey: "title") aCoder.encodeObject(artist, forKey: "artist") aCoder.encodeObject(genre, forKey: "genre") aCoder.encodeObject(coverUrl, forKey: "cover_url") aCoder.encodeObject(year, forKey: "year") } func description() -> String { return "title: \(title)" + "artist: \(artist)" + "genre: \(genre)" + "coverUrl: \(coverUrl)" + "year: \(year)" } }
34.632353
86
0.714225
72a4ca0c384c3f60e7431b78092444f03198939d
1,524
// // NSViewController.swift // CoreUtil // // Created by yuki on 2021/07/19. // Copyright © 2021 yuki. All rights reserved. // import Cocoa private var chainObjectKey = 0 private var chainObjectFlagKey = 0 extension NSViewController { public var isChainObjectLoaded: Bool { get { objc_getAssociatedObject(self, &chainObjectFlagKey) as? Bool ?? false } set { objc_setAssociatedObject(self, &chainObjectFlagKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public var chainObject: Any? { get { objc_getAssociatedObject(self, &chainObjectKey) } set { guard let chainObject = newValue else { return } if self.isChainObjectLoaded { return }; self.isChainObjectLoaded = true objc_setAssociatedObject(self, &chainObjectKey, chainObject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) Self.activateObjectChain for child in children { child.chainObject = chainObject } self.chainObjectDidLoad() } } @objc open func chainObjectDidLoad() {} static let activateObjectChain: () = method_exchangeImplementations( class_getInstanceMethod(NSViewController.self, #selector(addChild))!, class_getInstanceMethod(NSViewController.self, #selector(chain_addChild))! ) @objc private dynamic func chain_addChild(_ childViewController: NSViewController) { childViewController.chainObject = chainObject self.chain_addChild(childViewController) } }
34.636364
113
0.69685
d625bb34f2fb76b948d671b3aac5848dc3d96b15
5,349
// // GameViewController.swift // GrasshopperRound2 // // Created by Justin Smith on 1/7/18. // Copyright © 2018 Justin Smith. All rights reserved. // import UIKit import SpriteKit import GameplayKit import Geo import Singalong let linesF : ([CGPoint]) -> [Line] = lineCreate let lines2D : ([[CGPoint]]) -> [[Line]] = { $0.map(lineCreate) } let rectangles = linesF <=> linesF let rectangles2D = lines2D <=> lines2D let rectangles2DFlat = rectangles2D >>> {$0.flatMap{$0}} let corOv : (PointCollection) -> [Oval] = { (points) in // Corner Ovals let top = points.top, bottom = points.bottom let corners : [CGPoint] = [top.first!, top.last!, bottom.last!, bottom.first!] let corOv : [Oval] = corners.map(redCirc) return corOv } func originSwap (model: NonuniformModel2D, scale: CGFloat, bounds: CGRect) -> NonuniformModel2D { //_skCordinateModel = model // IMPORTANT: Scale the orgin by opposite of scale! for some reason // rest of scaling in addChildR let origin = CGPoint(model.origin.x / scale, bounds.size.height / scale - model.origin.y / scale) let _skCordinateModel = NonuniformModel2D(origin: origin, rowSizes: Grid(model.rowSizes.map{ -$0}), colSizes: model.colSizes) // transform Cordinate Space return _skCordinateModel } func gridItemed(points: PointCollection, offset: CGFloat)-> [[Geometry]] { let ghp = getHandleOvals(points: BorderPoints(top: points.top, right: points.right, bottom: points.bottom, left: points.left), offset: offset) let flattendGHP = ghp.flatMap{$0} let handleLines = zip(points.boundaries, flattendGHP).map(Line.init) // put in on screen when gameScene loads into View let gridItems : [[Geometry]] = [handleLines, flattendGHP] return gridItems } public struct BorderPoints { public var top: [CGPoint] public var right: [CGPoint] public var bottom: [CGPoint] public var left: [CGPoint] public init(top: [CGPoint], right: [CGPoint], bottom: [CGPoint], left: [CGPoint] ) { self.top = top self.right = right self.bottom = bottom self.left = left } } func addOffset<A>(a:A) -> (A, CGFloat) { return (a, 80) } // //func secondOffsetLabelLeft(ps:[[CGPoint]]) -> [Label] //{ // return ( (ps |> leftToRightToBorders).left, unitX * -80) |> offsetPoints //} public func leftToRightToBorders (ltR: [[CGPoint]]) -> BorderPoints { return BorderPoints(top: ltR.last! , right: ltR.map{ $0.last! }, bottom: ltR.first!, left: ltR.map{ $0.first! }) } func reduceLargest(a: CGFloat, b: CGFloat) -> CGFloat { return a > b ? a : b } func reduceSmallest(a: CGFloat, b: CGFloat) -> CGFloat { return a < b ? a : b } func leftToRightToBordersArray (ltR: [[CGPoint]]) -> [[CGPoint]] { return [ ltR.last!, ltR.map{ $0.last! }, ltR.first!, ltR.map{ $0.first! } ] } let pointLabeled : (PointCollection)-> [LabeledPoint] = { $0.all.map { return LabeledPoint(position: $0, label: "Std") } } let lineToSegment : (Line) -> (CGSegment) = { return CGSegment(p1: $0.start, p2: $0.end) } let segmentToOriginVector : (CGSegment) -> (CGPoint, CGVector) = { return ($0.p1, $0.vector) } let segmentToString : (CGSegment) -> (String) = { let tuple = $0 |> segmentToOriginVector let vectorStr = (tuple.1 |> vectorToOrthogonal).map(orthToString) ?? "Unknown" return "\(tuple.0), \(vectorStr) " } let vectorToOrthogonal : (CGVector) -> Orthogonal? = { return $0.dx == 0.0 ? .vertical : $0.dy == 0.0 ? .horizontal : nil} let orthToString : (Orthogonal) -> String = { return $0 == .horizontal ? "horizontal" : "vertical" } let lineStr = lineToSegment >>> segmentToString public func basic(m: NonuniformModel2D) -> [Geometry]{ let rectangles = (m.orderedPointsLeftToRight, m.orderedPointsUpToDown) |> rectangles2DFlat let pnts = m |> nonuniformToPoints |> pointLabeled let rtrn : [Geometry] = rectangles as [Geometry] + pnts as [Geometry] return rtrn } func baySelected(points: PointCollection) -> [Oval] { var selectedItems : [Oval] if points.top.count > 1, points.bottom.count > 1 { // top left to right let first = points.top[0...1] // bottom right to left let second = points.bottom[0...1].reversed() // and back to the top let final = points.top[0] let firstBay = Array(first + second ) + [final] let circles = centers(between: firstBay).map(redCirc) selectedItems = circles } else { selectedItems = [] } return selectedItems } func circlesSelectedItems(points: PointCollection) -> [Oval] { if points.top.count > 1, points.bottom.count > 1 { // top left to right let first = points.top[0...1] // bottom right to left let second = points.bottom[0...1].reversed() // and back to the top let final = points.top[0] let firstBay = Array(first + second ) + [final] let circles = centers(between: firstBay).map(redCirc) return circles } return [] } public func toGeometry<A:Geometry>(_ a: A ) -> Geometry { return a as Geometry } func lineZero(line: Line)-> Bool { return line.start == line.end } public func reduceDuplicates(geo:[Line])-> [Line] { var mutGeo = geo mutGeo.removeAll( where: lineZero ) return mutGeo } // ...SceneKit Handlering // Viewcontroller Functions
24.20362
144
0.653767
64f1ccb17fb1f046298613fb7f33a6d8a659b9a1
193
import Foundation public typealias ClosureVoid = ()->Void public typealias ClosureBool = (Bool)->Void public typealias ClosureString = (String)->Void public typealias ClosureInt = (Int)->Void
27.571429
47
0.777202
503f4871ef9eb207227bae816ec6231cafb61892
1,597
// // MockNetworkTransport.swift // ApolloDeveloperKitTests // // Created by Ryosuke Ito on 2/13/20. // Copyright © 2020 Ryosuke Ito. All rights reserved. // import Apollo import Foundation class MockNetworkTransport: NetworkTransport { var clientName = "clientName" var clientVersion = "clientVersion" private var results = ArraySlice<Result<Any, Error>>() var isResultsEmpty: Bool { return results.isEmpty } func append<Data>(response: GraphQLResponse<Data>) where Data: GraphQLSelectionSet { results.append(.success(response)) } func append(error: Error) { results.append(.failure(error)) } func send<Operation>(operation: Operation, cachePolicy: CachePolicy, contextIdentifier: UUID?, callbackQueue: DispatchQueue, completionHandler: @escaping (Result<GraphQLResult<Operation.Data>, Error>) -> Void) -> Cancellable where Operation : GraphQLOperation { let result = results.popFirst() switch result { case .success(let graphQLResult as GraphQLResult<Operation.Data>)?: completionHandler(.success(graphQLResult)) case .failure(let error)?: completionHandler(.failure(error)) case .success: fatalError("The type of the next response doesn't match the expected type.") case nil: fatalError("The number of invocation of send(operation:completionHandler:) exceeds the number of results.") } return MockCancellable() } } class MockCancellable: Cancellable { func cancel() { // do nothing } }
31.313725
265
0.678147
e5c868209a5c6d17e2603520bd5421f7fbb825d0
16,203
// // RoomViewController.swift // OpenVideoCall // // Created by GongYuhua on 16/8/22. // Copyright © 2016年 Agora. All rights reserved. // import UIKit import AgoraRtcEngineKit protocol RoomVCDataSource: NSObjectProtocol { func roomVCNeedAgoraKit() -> AgoraRtcEngineKit func roomVCNeedSettings() -> Settings } class RoomViewController: UIViewController { @IBOutlet weak var containerView: UIView! @IBOutlet weak var messageTableContainerView: UIView! @IBOutlet weak var cameraButton: UIButton! @IBOutlet weak var audioMixingButton: UIButton! @IBOutlet weak var speakerPhoneButton: UIButton! @IBOutlet weak var beautyButton: UIButton! @IBOutlet weak var muteVideoButton: UIButton! @IBOutlet weak var muteAudioButton: UIButton! @IBOutlet var backgroundDoubleTap: UITapGestureRecognizer! private var agoraKit: AgoraRtcEngineKit { return dataSource!.roomVCNeedAgoraKit() } private var settings: Settings { return dataSource!.roomVCNeedSettings() } private var isSwitchCamera = true { didSet { agoraKit.switchCamera() } } private var isAudioMixing = false { didSet { guard oldValue != isAudioMixing else { return } audioMixingButton?.isSelected = isAudioMixing if isAudioMixing { // play music file agoraKit.startAudioMixing( FileCenter.audioFilePath(), loopback: false, replace: false, cycle: 1 ) } else { // stop play agoraKit.stopAudioMixing() } } } private var isBeauty = false { didSet { guard oldValue != isBeauty else { return } beautyButton?.isSelected = isBeauty var options: AgoraBeautyOptions? = nil if isBeauty { options = AgoraBeautyOptions() options?.lighteningContrastLevel = .normal options?.lighteningLevel = 0.7 options?.smoothnessLevel = 0.5 options?.rednessLevel = 0.1 } // improve local render view agoraKit.setBeautyEffectOptions(isBeauty, options: options) } } private var isSpeakerPhone = true { didSet { guard oldValue != isSpeakerPhone else { return } speakerPhoneButton.isSelected = !isSpeakerPhone // switch playout audio route agoraKit.setEnableSpeakerphone(isSpeakerPhone) } } private var isVideoMuted = false { didSet { guard oldValue != isVideoMuted else { return } muteVideoButton?.isSelected = isVideoMuted setVideoMuted(isVideoMuted, forUid: 0) updateSelfViewVisiable() // mute local video agoraKit.muteLocalVideoStream(isVideoMuted) } } private var isAudioMuted = false { didSet { guard oldValue != isAudioMuted else { return } muteAudioButton?.isSelected = isAudioMuted // mute local audio agoraKit.muteLocalAudioStream(isAudioMuted) } } private var isDebugMode = false { didSet { guard oldValue != isDebugMode else { return } options.isDebugMode = isDebugMode messageTableContainerView.isHidden = !isDebugMode } } private var videoSessions = [VideoSession]() { didSet { // videoSessions and videoViewLayouter manage all render views let animation = videoSessions.count > 0 ? true : false updateInterface(with: self.videoSessions, targetSize: containerView.frame.size, animation: animation) } } private var doubleClickFullSession: VideoSession? { didSet { if videoSessions.count >= 3 && doubleClickFullSession != oldValue { updateInterface(with: videoSessions, targetSize: containerView.frame.size, animation: true) } } } private let videoViewLayouter = VideoViewLayouter() private let cryptoLoader = AgoraRtcCryptoLoader() private weak var optionsVC: RoomOptionsViewController? private lazy var options = RoomOptions(isDebugMode: false) private var messageVC: MessageViewController? weak var dataSource: RoomVCDataSource? override func viewDidLoad() { super.viewDidLoad() title = settings.roomName loadAgoraKit() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let segueId = segue.identifier else { return } switch segueId { case "roomEmbedMessage": messageVC = segue.destination as? MessageViewController case "roomToOptions": let optionsVC = segue.destination as? RoomOptionsViewController optionsVC?.delegate = self optionsVC?.dataSource = self self.optionsVC = optionsVC default: break } } deinit { leaveChannel() } @IBAction func doAudioMixingPressed(_ sender: UIButton) { isAudioMixing.toggle() } @IBAction func doBeautyPressed(_ sender: UIButton) { isBeauty.toggle() } @IBAction func doSpeakerPhonePressed(_ sender: UIButton) { isSpeakerPhone.toggle() } @IBAction func doMuteVideoPressed(_ sender: UIButton) { isVideoMuted.toggle() } @IBAction func doMuteAudioPressed(_ sender: UIButton) { isAudioMuted.toggle() } @IBAction func doCameraPressed(_ sender: UIButton) { isSwitchCamera.toggle() } @IBAction func doBackDoubleTapped(_ sender: UITapGestureRecognizer) { if doubleClickFullSession == nil { // full screen display after be double clicked if let tappedIndex = videoViewLayouter.reponseViewIndex(of: sender.location(in: containerView)) { doubleClickFullSession = videoSessions[tappedIndex] } } else { doubleClickFullSession = nil } } } // MARK: - AgoraRtcEngineKit private extension RoomViewController { func loadAgoraKit() { // Step 1, set delegate agoraKit.delegate = self // Step 2, set communication mode agoraKit.setChannelProfile(.communication) // Step 3, enable the video module agoraKit.enableVideo() // set video configuration agoraKit.setVideoEncoderConfiguration( AgoraVideoEncoderConfiguration( size: settings.dimension, frameRate: settings.frameRate, bitrate: AgoraVideoBitrateStandard, orientationMode: .adaptative ) ) // add local render view and start preview addLocalSession() agoraKit.startPreview() // Step 4, enable encryption mode if let type = settings.encryptionType, let text = type.text, !text.isEmpty { agoraKit.setEncryptionMode(type.modeString()) agoraKit.setEncryptionSecret(text) } // Step 5, join channel and start group chat // If join channel success, agoraKit triggers it's delegate function // 'rtcEngine(_ engine: AgoraRtcEngineKit, didJoinChannel channel: String, withUid uid: UInt, elapsed: Int)' agoraKit.joinChannel(byToken: KeyCenter.Token, channelId: settings.roomName!, info: nil, uid: 0, joinSuccess: nil) setIdleTimerActive(false) } func addLocalSession() { let localSession = VideoSession.localSession() videoSessions.append(localSession) agoraKit.setupLocalVideo(localSession.canvas) let mediaInfo = MediaInfo(dimension: settings.dimension, fps: settings.frameRate.rawValue) localSession.mediaInfo = mediaInfo } func leaveChannel() { // Step 1, release local AgoraRtcVideoCanvas instance agoraKit.setupLocalVideo(nil) // Step 2, leave channel and end group chat agoraKit.leaveChannel(nil) // Step 3, please attention, stop preview after leave channel agoraKit.stopPreview() // Step 4, remove all render views for session in videoSessions { session.hostingView.removeFromSuperview() } videoSessions.removeAll() setIdleTimerActive(true) } } // MARK: - AgoraRtcEngineDelegate extension RoomViewController: AgoraRtcEngineDelegate { func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinChannel channel: String, withUid uid: UInt, elapsed: Int) { info(string: "Join channel: \(channel)") } func rtcEngineConnectionDidInterrupted(_ engine: AgoraRtcEngineKit) { alert(string: "Connection Interrupted") } func rtcEngineConnectionDidLost(_ engine: AgoraRtcEngineKit) { alert(string: "Connection Lost") } func rtcEngine(_ engine: AgoraRtcEngineKit, didOccurError errorCode: AgoraErrorCode) { alert(string: "Occur error: \(errorCode.rawValue)") } // first remote video frame func rtcEngine(_ engine: AgoraRtcEngineKit, firstRemoteVideoDecodedOfUid uid: UInt, size: CGSize, elapsed: Int) { let userSession = videoSession(of: uid) let sie = size.fixedSize(with: containerView.bounds.size) userSession.size = sie userSession.updateMediaInfo(resolution: size) agoraKit.setupRemoteVideo(userSession.canvas) } // first local video frame func rtcEngine(_ engine: AgoraRtcEngineKit, firstLocalVideoFrameWith size: CGSize, elapsed: Int) { if let selfSession = videoSessions.first { let fixedSize = size.fixedSize(with: containerView.bounds.size) selfSession.size = fixedSize updateInterface(with: videoSessions, targetSize: containerView.frame.size, animation: false) info(string: "local video dimension: \(size.width) x \(size.height)") } } // user offline func rtcEngine(_ engine: AgoraRtcEngineKit, didOfflineOfUid uid: UInt, reason: AgoraUserOfflineReason) { var indexToDelete: Int? for (index, session) in videoSessions.enumerated() where session.uid == uid { indexToDelete = index break } if let indexToDelete = indexToDelete { let deletedSession = videoSessions.remove(at: indexToDelete) deletedSession.hostingView.removeFromSuperview() if let doubleClickFullSession = doubleClickFullSession , doubleClickFullSession == deletedSession { self.doubleClickFullSession = nil } // release canvas's view deletedSession.canvas.view = nil } } // video muted func rtcEngine(_ engine: AgoraRtcEngineKit, didVideoMuted muted: Bool, byUid uid: UInt) { setVideoMuted(muted, forUid: uid) } // remote stat func rtcEngine(_ engine: AgoraRtcEngineKit, remoteVideoStats stats: AgoraRtcRemoteVideoStats) { if let session = fetchSession(of: stats.uid) { session.updateMediaInfo(resolution: CGSize(width: CGFloat(stats.width), height: CGFloat(stats.height)), fps: Int(stats.rendererOutputFrameRate)) } } // audio mixing func rtcEngineLocalAudioMixingDidFinish(_ engine: AgoraRtcEngineKit) { isAudioMixing = false } } // MARK: RoomOptionsVCDelegate extension RoomViewController: RoomOptionsVCDelegate { func roomOptionsVC(_ vc: RoomOptionsViewController, debugModeDid enable: Bool) { isDebugMode = enable } } // MARK: RoomOptionsVCDataSource extension RoomViewController: RoomOptionsVCDataSource { func roomOptionsVCNeedOptions() -> RoomOptions { return options } } // MARK: - Private private extension RoomViewController { // Update views func updateInterface(with sessions: [VideoSession], targetSize: CGSize, animation: Bool) { if animation { UIView.animate(withDuration: 0.3, delay: 0, options: .beginFromCurrentState, animations: {[weak self] () -> Void in self?.updateInterface(with: sessions, targetSize: targetSize) self?.view.layoutIfNeeded() }, completion: nil) } else { updateInterface(with: sessions, targetSize: targetSize) } } func updateInterface(with sessions: [VideoSession], targetSize: CGSize) { guard !sessions.isEmpty else { return } let selfSession = sessions.first! videoViewLayouter.selfView = selfSession.hostingView videoViewLayouter.selfSize = selfSession.size videoViewLayouter.targetSize = targetSize var peerVideoViews = [VideoView]() for i in 1..<sessions.count { peerVideoViews.append(sessions[i].hostingView) } videoViewLayouter.videoViews = peerVideoViews videoViewLayouter.fullView = doubleClickFullSession?.hostingView videoViewLayouter.containerView = containerView videoViewLayouter.layoutVideoViews() updateSelfViewVisiable() // Only three people or more can switch the layout if sessions.count >= 3 { backgroundDoubleTap.isEnabled = true } else { backgroundDoubleTap.isEnabled = false doubleClickFullSession = nil } } func fetchSession(of uid: UInt) -> VideoSession? { for session in videoSessions { if session.uid == uid { return session } } return nil } func videoSession(of uid: UInt) -> VideoSession { if let fetchedSession = fetchSession(of: uid) { return fetchedSession } else { let newSession = VideoSession(uid: uid) videoSessions.append(newSession) return newSession } } func updateSelfViewVisiable() { guard let selfView = videoSessions.first?.hostingView else { return } if videoSessions.count == 2 { selfView.isHidden = isVideoMuted } else { selfView.isHidden = false } } func setVideoMuted(_ muted: Bool, forUid uid: UInt) { fetchSession(of: uid)?.isVideoMuted = muted } func setIdleTimerActive(_ active: Bool) { UIApplication.shared.isIdleTimerDisabled = !active } // Log func info(string: String) { guard !string.isEmpty else { return } messageVC?.append(info: string) } func alert(string: String) { guard !string.isEmpty else { return } messageVC?.append(alert: string) } } extension RoomViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let appDelegate = UIApplication.shared.delegate as? AppDelegate { appDelegate.orientation = .all } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if let appDelegate = UIApplication.shared.delegate as? AppDelegate { appDelegate.orientation = .portrait } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { for session in videoSessions { if let sessionSize = session.size { session.size = sessionSize.fixedSize(with: size) } } updateInterface(with: videoSessions, targetSize: size, animation: true) } }
32.799595
156
0.614392
71ffcbd44b5a2eda63365bd8d482537b23529e4a
612
// // BleUUIDNames.swift // Bluefruit Connect // // Created by Antonio García on 15/02/16. // Copyright © 2016 Adafruit. All rights reserved. // import Foundation class BleUUIDNames { // Manager static let shared = BleUUIDNames() // Data fileprivate var gattUUIds: [String:String]? init() { // Read known UUIDs let path = Bundle.main.path(forResource: "GattUUIDs", ofType: "plist")! gattUUIds = NSDictionary(contentsOfFile: path) as? [String: String] } func nameForUUID(_ uuidString: String) -> String? { return gattUUIds?[uuidString] } }
21.857143
79
0.642157
acb24e36d830ee702a891103024b45db78510249
9,158
// // EditorViewController+Cell.swift // Cerise // // Created by bl4ckra1sond3tre on 2019/3/19. // Copyright © 2019 blessingsoftware. All rights reserved. // import UIKit import RxCocoa import RxSwift import Keldeo extension EditorViewController { final class TextFieldCell: RxTableViewCell, Reusable { var textChanged: ControlEvent<String> { let source = textField.rx.text.orEmpty .map { $0.cerise.trimming(.whitespaceAndNewline) } return ControlEvent(events: source) } var textFieldDidBeginEditing: ControlEvent<Void> { return textField.rx.didBeginEditing } var textFieldDidEndEditing: ControlEvent<Void> { return textField.rx.didEndEditing } private(set) lazy var textField: UITextField = { let textField = UITextField() textField.textAlignment = .center textField.textColor = UIColor.cerise.text textField.returnKeyType = .done return textField }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none contentView.addSubview(textField) textField.cerise.layout { builder in builder.edges == contentView.cerise.edgesAnchor } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } } extension EditorViewController { final class TextViewCell: RxTableViewCell, Reusable { var textChanged: ControlEvent<String> { let source = textView.rx.text.orEmpty .map { $0.cerise.trimming(.whitespaceAndNewline) } return ControlEvent(events: source) } var textViewDidBeginEditing: ControlEvent<Void> { return textView.rx.didBeginEditing } var textViewDidEndEditing: ControlEvent<Void> { return textView.rx.didEndEditing } var textViewDidChangeAction: ((CGFloat) -> Void)? private(set) lazy var titleLabel: UILabel = { let label = UILabel() label.textColor = UIColor.cerise.title return label }() private let textViewMinimumHeight: CGFloat = 30.0 static let minimumHeight: CGFloat = 16 + 30 + 10 + 30 + 20 private(set) lazy var textView: UITextView = { let textView = UITextView() textView.delegate = self textView.isScrollEnabled = false textView.textColor = UIColor.cerise.text textView.backgroundColor = .clear textView.font = UIFont.systemFont(ofSize: 14.0) textView.textContainer.lineFragmentPadding = 0.0 textView.textContainerInset = .zero textView.autocapitalizationType = .none textView.autocorrectionType = .no textView.spellCheckingType = .no textView.returnKeyType = .done textView.keyboardDismissMode = .interactive textView.keyboardAppearance = .dark return textView }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none textLabel?.textColor = UIColor.cerise.title contentView.addSubview(titleLabel) titleLabel.cerise.layout { builder in builder.top == contentView.topAnchor + 16 builder.leading == contentView.leadingAnchor + 20 builder.trailing == contentView.trailingAnchor - 20 builder.height == 30 } contentView.addSubview(textView) textView.cerise.layout { builder in builder.leading == titleLabel.leadingAnchor builder.trailing == titleLabel.trailingAnchor builder.top == titleLabel.bottomAnchor + 10 builder.bottom == contentView.bottomAnchor - 20 builder.height >= 30 } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } } extension EditorViewController.TextViewCell: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { let size = textView.sizeThatFits(CGSize(width: textView.frame.width, height: CGFloat.greatestFiniteMagnitude)) //var bounds = textView.bounds //bounds.size = size //textView.bounds = bounds //textViewHeightConstraint.constant = max(textViewMinixumHeight, size.height) textViewDidChangeAction?(size.height + 80.0) } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { textView.resignFirstResponder() return false } return true } } extension EditorViewController { final class DatePickerCell: RxTableViewCell, Reusable { static let datePickerTag = 99 var datePicked: ControlEvent<Date> { return ControlEvent(events: datePicker.rx.date) } private(set) lazy var datePicker: UIDatePicker = { let datePicker = UIDatePicker() datePicker.tag = DatePickerCell.datePickerTag datePicker.datePickerMode = .date datePicker.backgroundColor = UIColor.cerise.dark datePicker.setValue(UIColor.cerise.text, forKey: "textColor") return datePicker }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(datePicker) datePicker.cerise.layout { builder in builder.edges == contentView.cerise.edgesAnchor } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setDate(_ date: Date, animated: Bool = true) { datePicker.setDate(date, animated: animated) } } final class DisclosureCell: UITableViewCell, Reusable { private(set) lazy var titleLabel: UILabel = { let label = UILabel() label.textColor = UIColor.cerise.title return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .value1, reuseIdentifier: reuseIdentifier) accessoryType = .disclosureIndicator textLabel?.textColor = UIColor.cerise.title detailTextLabel?.textColor = UIColor.cerise.text selectedBackgroundView = UIView() selectedBackgroundView?.backgroundColor = UIColor(named: "BK20") contentView.addSubview(titleLabel) titleLabel.cerise.layout { builder in builder.centerY == contentView.centerYAnchor builder.leading == contentView.leadingAnchor + 20 builder.trailing == contentView.trailingAnchor - 20 } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } } extension EditorViewController { final class TagPickerCell: RxTableViewCell, Reusable { var tagPicked: ControlEvent<Tagble> { return ControlEvent(events: tagitView.itemSelected) } private(set) lazy var titleLabel: UILabel = { let label = UILabel() label.textColor = UIColor.cerise.title return label }() private(set) lazy var tagitView: TagitView = { let view = TagitView(frame: .zero) return view }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectedBackgroundView = UIView() selectedBackgroundView?.backgroundColor = UIColor(named: "BK20") contentView.addSubview(titleLabel) titleLabel.cerise.layout { builder in builder.centerY == contentView.centerYAnchor builder.leading == contentView.leadingAnchor + 20 } contentView.addSubview(tagitView) tagitView.cerise.layout { builder in builder.leading == titleLabel.trailingAnchor + 20 builder.trailing == contentView.trailingAnchor - 20 builder.centerY == contentView.centerYAnchor builder.height == contentView.heightAnchor } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setTag(_ tag: Tagble, animated: Bool = true) { tagitView.select(tag: tag, animated: animated) } } }
35.223077
118
0.613562
e4e6fc1a3b21af475f35b42fe357af61ae6976c5
263
// // ProfileType.swift // Listpie // // Created by Ebru Kaya on 19.06.2018. // Copyright © 2018 Ebru Kaya. All rights reserved. // import Foundation enum ProfileType: String { case currentUser = "currentUser" case differentUser = "differentUser" }
17.533333
52
0.688213
f9a6c5ec07a8cbc470645bc3982b9c6b221e73f8
30,136
import Foundation final class Repository: NSObject, NSCoding { enum Keys { static let pulls_url = "pulls_url" static let subscribers_url = "subscribers_url" static let tags_url = "tags_url" static let clone_url = "clone_url" static let git_url = "git_url" static let size = "size" static let git_tags_url = "git_tags_url" static let subscribers_count = "subscribers_count" static let id = "id" static let default_branch = "default_branch" static let issue_events_url = "issue_events_url" static let mirror_url = "mirror_url" static let has_pages = "has_pages" static let downloads_url = "downloads_url" static let comments_url = "comments_url" static let homepage = "homepage" static let teams_url = "teams_url" static let url = "url" static let allow_squash_merge = "allow_squash_merge" static let hooks_url = "hooks_url" static let html_url = "html_url" static let issues_url = "issues_url" static let full_name = "full_name" static let fork = "fork" static let description_ = "description" static let notifications_url = "notifications_url" static let ssh_url = "ssh_url" static let stargazers_count = "stargazers_count" static let allow_merge_commit = "allow_merge_commit" static let issue_comment_url = "issue_comment_url" static let languages_url = "languages_url" static let branches_url = "branches_url" static let milestones_url = "milestones_url" static let assignees_url = "assignees_url" static let collaborators_url = "collaborators_url" static let has_issues = "has_issues" static let network_count = "network_count" static let archive_url = "archive_url" static let created_at = "created_at" static let compare_url = "compare_url" static let open_issues_count = "open_issues_count" static let labels_url = "labels_url" static let forks_count = "forks_count" static let events_url = "events_url" static let blobs_url = "blobs_url" static let has_downloads = "has_downloads" static let svn_url = "svn_url" static let forks_url = "forks_url" static let source = "source" static let private_ = "private" static let releases_url = "releases_url" static let language = "language" static let pushed_at = "pushed_at" static let contents_url = "contents_url" static let statuses_url = "statuses_url" static let parent = "parent" static let owner = "owner" static let allow_rebase_merge = "allow_rebase_merge" static let git_refs_url = "git_refs_url" static let stargazers_url = "stargazers_url" static let name = "name" static let topics = "topics" static let updated_at = "updated_at" static let subscription_url = "subscription_url" static let contributors_url = "contributors_url" static let trees_url = "trees_url" static let keys_url = "keys_url" static let has_wiki = "has_wiki" static let git_commits_url = "git_commits_url" static let commits_url = "commits_url" static let watchers_count = "watchers_count" static let organization = "organization" static let deployments_url = "deployments_url" static let permissions = "permissions" static let merges_url = "merges_url" } let pulls_url: String? let subscribers_url: String? let tags_url: String? let clone_url: String? let git_url: String? let size: NSNumber? let git_tags_url: String? let subscribers_count: NSNumber? let id: NSNumber let default_branch: String? let issue_events_url: String? let mirror_url: String? let has_pages: Bool? let downloads_url: String? let comments_url: String? let homepage: String? let teams_url: String? let url: String let allow_squash_merge: Bool? let hooks_url: String? let html_url: String let issues_url: String? let full_name: String let fork: Bool let description_: String? let notifications_url: String? let ssh_url: String? let stargazers_count: NSNumber? let allow_merge_commit: Bool? let issue_comment_url: String? let languages_url: String? let branches_url: String? let milestones_url: String? let assignees_url: String? let collaborators_url: String? let has_issues: Bool? let network_count: NSNumber? let archive_url: String? let created_at: String? let compare_url: String? let open_issues_count: NSNumber? let labels_url: String? let forks_count: NSNumber? let events_url: String? let blobs_url: String? let has_downloads: Bool? let svn_url: String? let forks_url: String? let source: Repository? let private_: Bool let releases_url: String? let language: String? let pushed_at: String? let contents_url: String? let statuses_url: String? let parent: Repository? let owner: User let allow_rebase_merge: Bool? let git_refs_url: String? let stargazers_url: String? let name: String let topics: [String]? let updated_at: String? let subscription_url: String? let contributors_url: String? let trees_url: String? let keys_url: String? let has_wiki: Bool? let git_commits_url: String? let commits_url: String? let watchers_count: NSNumber? let organization: Organization? let deployments_url: String? let permissions: Permission? let merges_url: String? convenience init?(json: [String: Any]?) { let pulls_url = json?[Keys.pulls_url] as? String let subscribers_url = json?[Keys.subscribers_url] as? String let tags_url = json?[Keys.tags_url] as? String let clone_url = json?[Keys.clone_url] as? String let git_url = json?[Keys.git_url] as? String let size = json?[Keys.size] as? NSNumber let git_tags_url = json?[Keys.git_tags_url] as? String let subscribers_count = json?[Keys.subscribers_count] as? NSNumber guard let id = json?[Keys.id] as? NSNumber else { return nil } let default_branch = json?[Keys.default_branch] as? String let issue_events_url = json?[Keys.issue_events_url] as? String let mirror_url = json?[Keys.mirror_url] as? String let has_pages = json?[Keys.has_pages] as? Bool let downloads_url = json?[Keys.downloads_url] as? String let comments_url = json?[Keys.comments_url] as? String let homepage = json?[Keys.homepage] as? String let teams_url = json?[Keys.teams_url] as? String guard let url = json?[Keys.url] as? String else { return nil } let allow_squash_merge = json?[Keys.allow_squash_merge] as? Bool let hooks_url = json?[Keys.hooks_url] as? String guard let html_url = json?[Keys.html_url] as? String else { return nil } let issues_url = json?[Keys.issues_url] as? String guard let full_name = json?[Keys.full_name] as? String else { return nil } guard let fork = json?[Keys.fork] as? Bool else { return nil } let description_ = json?[Keys.description_] as? String let notifications_url = json?[Keys.notifications_url] as? String let ssh_url = json?[Keys.ssh_url] as? String let stargazers_count = json?[Keys.stargazers_count] as? NSNumber let allow_merge_commit = json?[Keys.allow_merge_commit] as? Bool let issue_comment_url = json?[Keys.issue_comment_url] as? String let languages_url = json?[Keys.languages_url] as? String let branches_url = json?[Keys.branches_url] as? String let milestones_url = json?[Keys.milestones_url] as? String let assignees_url = json?[Keys.assignees_url] as? String let collaborators_url = json?[Keys.collaborators_url] as? String let has_issues = json?[Keys.has_issues] as? Bool let network_count = json?[Keys.network_count] as? NSNumber let archive_url = json?[Keys.archive_url] as? String let created_at = json?[Keys.created_at] as? String let compare_url = json?[Keys.compare_url] as? String let open_issues_count = json?[Keys.open_issues_count] as? NSNumber let labels_url = json?[Keys.labels_url] as? String let forks_count = json?[Keys.forks_count] as? NSNumber let events_url = json?[Keys.events_url] as? String let blobs_url = json?[Keys.blobs_url] as? String let has_downloads = json?[Keys.has_downloads] as? Bool let svn_url = json?[Keys.svn_url] as? String let forks_url = json?[Keys.forks_url] as? String let sourceJSON = json?[Keys.source] as? [String: Any] let source = Repository(json: sourceJSON) guard let private_ = json?[Keys.private_] as? Bool else { return nil } let releases_url = json?[Keys.releases_url] as? String let language = json?[Keys.language] as? String let pushed_at = json?[Keys.pushed_at] as? String let contents_url = json?[Keys.contents_url] as? String let statuses_url = json?[Keys.statuses_url] as? String let parentJSON = json?[Keys.parent] as? [String: Any] let parent = Repository(json: parentJSON) guard let ownerJSON = json?[Keys.owner] as? [String: Any] else { return nil } guard let owner = User(json: ownerJSON) else { return nil } let allow_rebase_merge = json?[Keys.allow_rebase_merge] as? Bool let git_refs_url = json?[Keys.git_refs_url] as? String let stargazers_url = json?[Keys.stargazers_url] as? String guard let name = json?[Keys.name] as? String else { return nil } let topics = json?[Keys.topics] as? [String] let updated_at = json?[Keys.updated_at] as? String let subscription_url = json?[Keys.subscription_url] as? String let contributors_url = json?[Keys.contributors_url] as? String let trees_url = json?[Keys.trees_url] as? String let keys_url = json?[Keys.keys_url] as? String let has_wiki = json?[Keys.has_wiki] as? Bool let git_commits_url = json?[Keys.git_commits_url] as? String let commits_url = json?[Keys.commits_url] as? String let watchers_count = json?[Keys.watchers_count] as? NSNumber let organizationJSON = json?[Keys.organization] as? [String: Any] let organization = Organization(json: organizationJSON) let deployments_url = json?[Keys.deployments_url] as? String let permissionsJSON = json?[Keys.permissions] as? [String: Any] let permissions = Permission(json: permissionsJSON) let merges_url = json?[Keys.merges_url] as? String self.init( pulls_url: pulls_url, subscribers_url: subscribers_url, tags_url: tags_url, clone_url: clone_url, git_url: git_url, size: size, git_tags_url: git_tags_url, subscribers_count: subscribers_count, id: id, default_branch: default_branch, issue_events_url: issue_events_url, mirror_url: mirror_url, has_pages: has_pages, downloads_url: downloads_url, comments_url: comments_url, homepage: homepage, teams_url: teams_url, url: url, allow_squash_merge: allow_squash_merge, hooks_url: hooks_url, html_url: html_url, issues_url: issues_url, full_name: full_name, fork: fork, description_: description_, notifications_url: notifications_url, ssh_url: ssh_url, stargazers_count: stargazers_count, allow_merge_commit: allow_merge_commit, issue_comment_url: issue_comment_url, languages_url: languages_url, branches_url: branches_url, milestones_url: milestones_url, assignees_url: assignees_url, collaborators_url: collaborators_url, has_issues: has_issues, network_count: network_count, archive_url: archive_url, created_at: created_at, compare_url: compare_url, open_issues_count: open_issues_count, labels_url: labels_url, forks_count: forks_count, events_url: events_url, blobs_url: blobs_url, has_downloads: has_downloads, svn_url: svn_url, forks_url: forks_url, source: source, private_: private_, releases_url: releases_url, language: language, pushed_at: pushed_at, contents_url: contents_url, statuses_url: statuses_url, parent: parent, owner: owner, allow_rebase_merge: allow_rebase_merge, git_refs_url: git_refs_url, stargazers_url: stargazers_url, name: name, topics: topics, updated_at: updated_at, subscription_url: subscription_url, contributors_url: contributors_url, trees_url: trees_url, keys_url: keys_url, has_wiki: has_wiki, git_commits_url: git_commits_url, commits_url: commits_url, watchers_count: watchers_count, organization: organization, deployments_url: deployments_url, permissions: permissions, merges_url: merges_url ) } init( pulls_url: String?, subscribers_url: String?, tags_url: String?, clone_url: String?, git_url: String?, size: NSNumber?, git_tags_url: String?, subscribers_count: NSNumber?, id: NSNumber, default_branch: String?, issue_events_url: String?, mirror_url: String?, has_pages: Bool?, downloads_url: String?, comments_url: String?, homepage: String?, teams_url: String?, url: String, allow_squash_merge: Bool?, hooks_url: String?, html_url: String, issues_url: String?, full_name: String, fork: Bool, description_: String?, notifications_url: String?, ssh_url: String?, stargazers_count: NSNumber?, allow_merge_commit: Bool?, issue_comment_url: String?, languages_url: String?, branches_url: String?, milestones_url: String?, assignees_url: String?, collaborators_url: String?, has_issues: Bool?, network_count: NSNumber?, archive_url: String?, created_at: String?, compare_url: String?, open_issues_count: NSNumber?, labels_url: String?, forks_count: NSNumber?, events_url: String?, blobs_url: String?, has_downloads: Bool?, svn_url: String?, forks_url: String?, source: Repository?, private_: Bool, releases_url: String?, language: String?, pushed_at: String?, contents_url: String?, statuses_url: String?, parent: Repository?, owner: User, allow_rebase_merge: Bool?, git_refs_url: String?, stargazers_url: String?, name: String, topics: [String]?, updated_at: String?, subscription_url: String?, contributors_url: String?, trees_url: String?, keys_url: String?, has_wiki: Bool?, git_commits_url: String?, commits_url: String?, watchers_count: NSNumber?, organization: Organization?, deployments_url: String?, permissions: Permission?, merges_url: String? ) { self.pulls_url = pulls_url self.subscribers_url = subscribers_url self.tags_url = tags_url self.clone_url = clone_url self.git_url = git_url self.size = size self.git_tags_url = git_tags_url self.subscribers_count = subscribers_count self.id = id self.default_branch = default_branch self.issue_events_url = issue_events_url self.mirror_url = mirror_url self.has_pages = has_pages self.downloads_url = downloads_url self.comments_url = comments_url self.homepage = homepage self.teams_url = teams_url self.url = url self.allow_squash_merge = allow_squash_merge self.hooks_url = hooks_url self.html_url = html_url self.issues_url = issues_url self.full_name = full_name self.fork = fork self.description_ = description_ self.notifications_url = notifications_url self.ssh_url = ssh_url self.stargazers_count = stargazers_count self.allow_merge_commit = allow_merge_commit self.issue_comment_url = issue_comment_url self.languages_url = languages_url self.branches_url = branches_url self.milestones_url = milestones_url self.assignees_url = assignees_url self.collaborators_url = collaborators_url self.has_issues = has_issues self.network_count = network_count self.archive_url = archive_url self.created_at = created_at self.compare_url = compare_url self.open_issues_count = open_issues_count self.labels_url = labels_url self.forks_count = forks_count self.events_url = events_url self.blobs_url = blobs_url self.has_downloads = has_downloads self.svn_url = svn_url self.forks_url = forks_url self.source = source self.private_ = private_ self.releases_url = releases_url self.language = language self.pushed_at = pushed_at self.contents_url = contents_url self.statuses_url = statuses_url self.parent = parent self.owner = owner self.allow_rebase_merge = allow_rebase_merge self.git_refs_url = git_refs_url self.stargazers_url = stargazers_url self.name = name self.topics = topics self.updated_at = updated_at self.subscription_url = subscription_url self.contributors_url = contributors_url self.trees_url = trees_url self.keys_url = keys_url self.has_wiki = has_wiki self.git_commits_url = git_commits_url self.commits_url = commits_url self.watchers_count = watchers_count self.organization = organization self.deployments_url = deployments_url self.permissions = permissions self.merges_url = merges_url } convenience init?(coder aDecoder: NSCoder) { let pulls_url = aDecoder.decodeObject(forKey: Keys.pulls_url) as? String let subscribers_url = aDecoder.decodeObject(forKey: Keys.subscribers_url) as? String let tags_url = aDecoder.decodeObject(forKey: Keys.tags_url) as? String let clone_url = aDecoder.decodeObject(forKey: Keys.clone_url) as? String let git_url = aDecoder.decodeObject(forKey: Keys.git_url) as? String let size = aDecoder.decodeObject(forKey: Keys.size) as? NSNumber let git_tags_url = aDecoder.decodeObject(forKey: Keys.git_tags_url) as? String let subscribers_count = aDecoder.decodeObject(forKey: Keys.subscribers_count) as? NSNumber guard let id = aDecoder.decodeObject(forKey: Keys.id) as? NSNumber else { return nil } let default_branch = aDecoder.decodeObject(forKey: Keys.default_branch) as? String let issue_events_url = aDecoder.decodeObject(forKey: Keys.issue_events_url) as? String let mirror_url = aDecoder.decodeObject(forKey: Keys.mirror_url) as? String let has_pages = aDecoder.decodeObject(forKey: Keys.has_pages) as? Bool let downloads_url = aDecoder.decodeObject(forKey: Keys.downloads_url) as? String let comments_url = aDecoder.decodeObject(forKey: Keys.comments_url) as? String let homepage = aDecoder.decodeObject(forKey: Keys.homepage) as? String let teams_url = aDecoder.decodeObject(forKey: Keys.teams_url) as? String guard let url = aDecoder.decodeObject(forKey: Keys.url) as? String else { return nil } let allow_squash_merge = aDecoder.decodeObject(forKey: Keys.allow_squash_merge) as? Bool let hooks_url = aDecoder.decodeObject(forKey: Keys.hooks_url) as? String guard let html_url = aDecoder.decodeObject(forKey: Keys.html_url) as? String else { return nil } let issues_url = aDecoder.decodeObject(forKey: Keys.issues_url) as? String guard let full_name = aDecoder.decodeObject(forKey: Keys.full_name) as? String else { return nil } let fork = aDecoder.decodeBool(forKey: Keys.fork) let description_ = aDecoder.decodeObject(forKey: Keys.description_) as? String let notifications_url = aDecoder.decodeObject(forKey: Keys.notifications_url) as? String let ssh_url = aDecoder.decodeObject(forKey: Keys.ssh_url) as? String let stargazers_count = aDecoder.decodeObject(forKey: Keys.stargazers_count) as? NSNumber let allow_merge_commit = aDecoder.decodeObject(forKey: Keys.allow_merge_commit) as? Bool let issue_comment_url = aDecoder.decodeObject(forKey: Keys.issue_comment_url) as? String let languages_url = aDecoder.decodeObject(forKey: Keys.languages_url) as? String let branches_url = aDecoder.decodeObject(forKey: Keys.branches_url) as? String let milestones_url = aDecoder.decodeObject(forKey: Keys.milestones_url) as? String let assignees_url = aDecoder.decodeObject(forKey: Keys.assignees_url) as? String let collaborators_url = aDecoder.decodeObject(forKey: Keys.collaborators_url) as? String let has_issues = aDecoder.decodeObject(forKey: Keys.has_issues) as? Bool let network_count = aDecoder.decodeObject(forKey: Keys.network_count) as? NSNumber let archive_url = aDecoder.decodeObject(forKey: Keys.archive_url) as? String let created_at = aDecoder.decodeObject(forKey: Keys.created_at) as? String let compare_url = aDecoder.decodeObject(forKey: Keys.compare_url) as? String let open_issues_count = aDecoder.decodeObject(forKey: Keys.open_issues_count) as? NSNumber let labels_url = aDecoder.decodeObject(forKey: Keys.labels_url) as? String let forks_count = aDecoder.decodeObject(forKey: Keys.forks_count) as? NSNumber let events_url = aDecoder.decodeObject(forKey: Keys.events_url) as? String let blobs_url = aDecoder.decodeObject(forKey: Keys.blobs_url) as? String let has_downloads = aDecoder.decodeObject(forKey: Keys.has_downloads) as? Bool let svn_url = aDecoder.decodeObject(forKey: Keys.svn_url) as? String let forks_url = aDecoder.decodeObject(forKey: Keys.forks_url) as? String let source = aDecoder.decodeObject(forKey: Keys.source) as? Repository let private_ = aDecoder.decodeBool(forKey: Keys.private_) let releases_url = aDecoder.decodeObject(forKey: Keys.releases_url) as? String let language = aDecoder.decodeObject(forKey: Keys.language) as? String let pushed_at = aDecoder.decodeObject(forKey: Keys.pushed_at) as? String let contents_url = aDecoder.decodeObject(forKey: Keys.contents_url) as? String let statuses_url = aDecoder.decodeObject(forKey: Keys.statuses_url) as? String let parent = aDecoder.decodeObject(forKey: Keys.parent) as? Repository guard let owner = aDecoder.decodeObject(forKey: Keys.owner) as? User else { return nil } let allow_rebase_merge = aDecoder.decodeObject(forKey: Keys.allow_rebase_merge) as? Bool let git_refs_url = aDecoder.decodeObject(forKey: Keys.git_refs_url) as? String let stargazers_url = aDecoder.decodeObject(forKey: Keys.stargazers_url) as? String guard let name = aDecoder.decodeObject(forKey: Keys.name) as? String else { return nil } let topics = aDecoder.decodeObject(forKey: Keys.topics) as? [String] let updated_at = aDecoder.decodeObject(forKey: Keys.updated_at) as? String let subscription_url = aDecoder.decodeObject(forKey: Keys.subscription_url) as? String let contributors_url = aDecoder.decodeObject(forKey: Keys.contributors_url) as? String let trees_url = aDecoder.decodeObject(forKey: Keys.trees_url) as? String let keys_url = aDecoder.decodeObject(forKey: Keys.keys_url) as? String let has_wiki = aDecoder.decodeObject(forKey: Keys.has_wiki) as? Bool let git_commits_url = aDecoder.decodeObject(forKey: Keys.git_commits_url) as? String let commits_url = aDecoder.decodeObject(forKey: Keys.commits_url) as? String let watchers_count = aDecoder.decodeObject(forKey: Keys.watchers_count) as? NSNumber let organization = aDecoder.decodeObject(forKey: Keys.organization) as? Organization let deployments_url = aDecoder.decodeObject(forKey: Keys.deployments_url) as? String let permissions = aDecoder.decodeObject(forKey: Keys.permissions) as? Permission let merges_url = aDecoder.decodeObject(forKey: Keys.merges_url) as? String self.init( pulls_url: pulls_url, subscribers_url: subscribers_url, tags_url: tags_url, clone_url: clone_url, git_url: git_url, size: size, git_tags_url: git_tags_url, subscribers_count: subscribers_count, id: id, default_branch: default_branch, issue_events_url: issue_events_url, mirror_url: mirror_url, has_pages: has_pages, downloads_url: downloads_url, comments_url: comments_url, homepage: homepage, teams_url: teams_url, url: url, allow_squash_merge: allow_squash_merge, hooks_url: hooks_url, html_url: html_url, issues_url: issues_url, full_name: full_name, fork: fork, description_: description_, notifications_url: notifications_url, ssh_url: ssh_url, stargazers_count: stargazers_count, allow_merge_commit: allow_merge_commit, issue_comment_url: issue_comment_url, languages_url: languages_url, branches_url: branches_url, milestones_url: milestones_url, assignees_url: assignees_url, collaborators_url: collaborators_url, has_issues: has_issues, network_count: network_count, archive_url: archive_url, created_at: created_at, compare_url: compare_url, open_issues_count: open_issues_count, labels_url: labels_url, forks_count: forks_count, events_url: events_url, blobs_url: blobs_url, has_downloads: has_downloads, svn_url: svn_url, forks_url: forks_url, source: source, private_: private_, releases_url: releases_url, language: language, pushed_at: pushed_at, contents_url: contents_url, statuses_url: statuses_url, parent: parent, owner: owner, allow_rebase_merge: allow_rebase_merge, git_refs_url: git_refs_url, stargazers_url: stargazers_url, name: name, topics: topics, updated_at: updated_at, subscription_url: subscription_url, contributors_url: contributors_url, trees_url: trees_url, keys_url: keys_url, has_wiki: has_wiki, git_commits_url: git_commits_url, commits_url: commits_url, watchers_count: watchers_count, organization: organization, deployments_url: deployments_url, permissions: permissions, merges_url: merges_url ) } func encode(with aCoder: NSCoder) { aCoder.encode(pulls_url, forKey: Keys.pulls_url) aCoder.encode(subscribers_url, forKey: Keys.subscribers_url) aCoder.encode(tags_url, forKey: Keys.tags_url) aCoder.encode(clone_url, forKey: Keys.clone_url) aCoder.encode(git_url, forKey: Keys.git_url) aCoder.encode(size, forKey: Keys.size) aCoder.encode(git_tags_url, forKey: Keys.git_tags_url) aCoder.encode(subscribers_count, forKey: Keys.subscribers_count) aCoder.encode(id, forKey: Keys.id) aCoder.encode(default_branch, forKey: Keys.default_branch) aCoder.encode(issue_events_url, forKey: Keys.issue_events_url) aCoder.encode(mirror_url, forKey: Keys.mirror_url) aCoder.encode(has_pages, forKey: Keys.has_pages) aCoder.encode(downloads_url, forKey: Keys.downloads_url) aCoder.encode(comments_url, forKey: Keys.comments_url) aCoder.encode(homepage, forKey: Keys.homepage) aCoder.encode(teams_url, forKey: Keys.teams_url) aCoder.encode(url, forKey: Keys.url) aCoder.encode(allow_squash_merge, forKey: Keys.allow_squash_merge) aCoder.encode(hooks_url, forKey: Keys.hooks_url) aCoder.encode(html_url, forKey: Keys.html_url) aCoder.encode(issues_url, forKey: Keys.issues_url) aCoder.encode(full_name, forKey: Keys.full_name) aCoder.encode(fork, forKey: Keys.fork) aCoder.encode(description_, forKey: Keys.description_) aCoder.encode(notifications_url, forKey: Keys.notifications_url) aCoder.encode(ssh_url, forKey: Keys.ssh_url) aCoder.encode(stargazers_count, forKey: Keys.stargazers_count) aCoder.encode(allow_merge_commit, forKey: Keys.allow_merge_commit) aCoder.encode(issue_comment_url, forKey: Keys.issue_comment_url) aCoder.encode(languages_url, forKey: Keys.languages_url) aCoder.encode(branches_url, forKey: Keys.branches_url) aCoder.encode(milestones_url, forKey: Keys.milestones_url) aCoder.encode(assignees_url, forKey: Keys.assignees_url) aCoder.encode(collaborators_url, forKey: Keys.collaborators_url) aCoder.encode(has_issues, forKey: Keys.has_issues) aCoder.encode(network_count, forKey: Keys.network_count) aCoder.encode(archive_url, forKey: Keys.archive_url) aCoder.encode(created_at, forKey: Keys.created_at) aCoder.encode(compare_url, forKey: Keys.compare_url) aCoder.encode(open_issues_count, forKey: Keys.open_issues_count) aCoder.encode(labels_url, forKey: Keys.labels_url) aCoder.encode(forks_count, forKey: Keys.forks_count) aCoder.encode(events_url, forKey: Keys.events_url) aCoder.encode(blobs_url, forKey: Keys.blobs_url) aCoder.encode(has_downloads, forKey: Keys.has_downloads) aCoder.encode(svn_url, forKey: Keys.svn_url) aCoder.encode(forks_url, forKey: Keys.forks_url) aCoder.encode(source, forKey: Keys.source) aCoder.encode(private_, forKey: Keys.private_) aCoder.encode(releases_url, forKey: Keys.releases_url) aCoder.encode(language, forKey: Keys.language) aCoder.encode(pushed_at, forKey: Keys.pushed_at) aCoder.encode(contents_url, forKey: Keys.contents_url) aCoder.encode(statuses_url, forKey: Keys.statuses_url) aCoder.encode(parent, forKey: Keys.parent) aCoder.encode(owner, forKey: Keys.owner) aCoder.encode(allow_rebase_merge, forKey: Keys.allow_rebase_merge) aCoder.encode(git_refs_url, forKey: Keys.git_refs_url) aCoder.encode(stargazers_url, forKey: Keys.stargazers_url) aCoder.encode(name, forKey: Keys.name) aCoder.encode(topics, forKey: Keys.topics) aCoder.encode(updated_at, forKey: Keys.updated_at) aCoder.encode(subscription_url, forKey: Keys.subscription_url) aCoder.encode(contributors_url, forKey: Keys.contributors_url) aCoder.encode(trees_url, forKey: Keys.trees_url) aCoder.encode(keys_url, forKey: Keys.keys_url) aCoder.encode(has_wiki, forKey: Keys.has_wiki) aCoder.encode(git_commits_url, forKey: Keys.git_commits_url) aCoder.encode(commits_url, forKey: Keys.commits_url) aCoder.encode(watchers_count, forKey: Keys.watchers_count) aCoder.encode(organization, forKey: Keys.organization) aCoder.encode(deployments_url, forKey: Keys.deployments_url) aCoder.encode(permissions, forKey: Keys.permissions) aCoder.encode(merges_url, forKey: Keys.merges_url) } }
43.113019
102
0.731086
5ba18f06e18d763738da0c73ff93bfc783b55268
6,731
import Foundation import XCTest @testable import SwiftyVK final class ConnectionObserverTests: XCTestCase { func test_registerAllObservers() { // Given var names = [Notification.Name]() let context = makeContext() context.center.onAddObserver = { name in guard let name = name else { return } names.append(name) } // When context.observer().subscribe(object: self, callbacks: (onConnect: {}, onDisconnect: {})) // Then XCTAssertEqual(names, [Notifications.active, Notifications.inactive, Notifications.reachability]) } func test_callOnConnect_whenAppResignActive() { // Given var onConnectCallCount = 0 var onDisconnectCallCount = 0 let context = makeContext() context.observer().subscribe( object: self, callbacks: ( onConnect: { onConnectCallCount += 1 }, onDisconnect: { onDisconnectCallCount += 1 } )) // When context.center.blocks[Notifications.active]?(Notification(name: Notifications.active)) context.center.blocks[Notifications.inactive]?(Notification(name: Notifications.inactive)) context.center.blocks[Notifications.inactive]?(Notification(name: Notifications.inactive)) // Then XCTAssertEqual(onConnectCallCount, 0) XCTAssertEqual(onDisconnectCallCount, 1) } func test_callOnDisonnect_whenAppBecomeActive() { // Given var onConnectCallCount = 0 var onDisconnectCallCount = 0 let context = makeContext() let observer = context.observer() observer.subscribe( object: self, callbacks: ( onConnect: { onConnectCallCount += 1 }, onDisconnect: { onDisconnectCallCount += 1 } )) // When context.center.blocks[Notifications.inactive]?(Notification(name: Notifications.inactive)) context.center.blocks[Notifications.active]?(Notification(name: Notifications.active)) context.center.blocks[Notifications.active]?(Notification(name: Notifications.active)) // Then XCTAssertEqual(onConnectCallCount, 1) XCTAssertEqual(onDisconnectCallCount, 2) } func test_callOnConnect_whenNetworkReachable() { // Given var onConnectCallCount = 0 var onDisconnectCallCount = 0 let context = makeContext() let observer = context.observer() observer.subscribe( object: self, callbacks: ( onConnect: { onConnectCallCount += 1 }, onDisconnect: { onDisconnectCallCount += 1 } )) // When context.reachability.isReachable = true context.center.blocks[Notifications.reachability]?(Notification(name: Notifications.reachability)) // Then XCTAssertEqual(onConnectCallCount, 1) XCTAssertEqual(onDisconnectCallCount, 1) } func test_callOnDisconnect_whenNetworkUnreachable() { // Given var onConnectCallCount = 0 var onDisconnectCallCount = 0 let context = makeContext() context.observer().subscribe( object: self, callbacks: ( onConnect: { onConnectCallCount += 1 }, onDisconnect: { onDisconnectCallCount += 1 } )) // When context.center.blocks[Notifications.inactive]?(Notification(name: Notifications.inactive)) context.reachability.isReachable = false context.center.blocks[Notifications.reachability]?(Notification(name: Notifications.reachability)) // Then XCTAssertEqual(onConnectCallCount, 0) XCTAssertEqual(onDisconnectCallCount, 1) } func test_notCallOnDisconnect_whenNetworkUnreachableAndAppIsInactive() { // Given var onConnectCallCount = 0 var onDisconnectCallCount = 0 let context = makeContext() context.observer().subscribe( object: self, callbacks: ( onConnect: { onConnectCallCount += 1 }, onDisconnect: { onDisconnectCallCount += 1 } )) // When context.reachability.isReachable = false context.center.blocks[Notifications.reachability]?(Notification(name: Notifications.reachability)) // Then XCTAssertEqual(onConnectCallCount, 0) XCTAssertEqual(onDisconnectCallCount, 1) } func test_unsubscribe() { // Given var onConnectCallCount = 0 var onDisconnectCallCount = 0 let context = makeContext() let observer = context.observer() observer.subscribe( object: self, callbacks: ( onConnect: { onConnectCallCount += 1 }, onDisconnect: { onDisconnectCallCount += 1 } )) // When observer.unsubscribe(object: self) context.center.blocks[Notifications.active]?(Notification(name: Notifications.active)) context.center.blocks[Notifications.inactive]?(Notification(name: Notifications.inactive)) context.center.blocks[Notifications.inactive]?(Notification(name: Notifications.inactive)) // Then XCTAssertEqual(onConnectCallCount, 0) XCTAssertEqual(onDisconnectCallCount, 1) } } private func makeContext() -> (observer: () -> ConnectionObserverImpl, center: VKNotificationCenterMock, reachability: VKReachabilityMock) { let center = VKNotificationCenterMock() let reachability = VKReachabilityMock() let observer = { ConnectionObserverImpl( appStateCenter: center, reachabilityCenter: center, reachability: reachability, activeNotificationName: Notifications.active, inactiveNotificationName: Notifications.inactive, reachabilityNotificationName: Notifications.reachability ) } return (observer, center, reachability) } struct Notifications { static let active = Notification.Name("active") static let inactive = Notification.Name("inactive") static let reachability = Notification.Name("reachability") }
33.824121
140
0.59278
561f62360002002cd7bf903633fd199eea9e8844
1,935
// // AUIView.swift // AppUIKit // // Created by ricky on 2016. 12. 5.. // Copyright © 2016년 appcid. All rights reserved. // import Cocoa open class AUIView: NSView { /* -tintColor always returns a color. The color returned is the first non-default value in the receiver's superview chain (starting with itself). If no non-default value is found, a system-defined color is returned. If this view's -tintAdjustmentMode returns Dimmed, then the color that is returned for -tintColor will automatically be dimmed. If your view subclass uses tintColor in its rendering, override -tintColorDidChange in order to refresh the rendering if the color changes. */ public var tintColor: NSColor! = NSColor.defaultTint public var backgroundColor = NSColor.white { didSet { needsDisplay = true } } @IBInspectable var backgroundColorCSS: String { get { return backgroundColor.css } set { backgroundColor = Color(hexString: newValue) } } override public init(frame frameRect: NSRect) { super.init(frame: frameRect) setup() } required public init?(coder: NSCoder) { super.init(coder: coder) setup() } func setup() { wantsLayer = false layerContentsRedrawPolicy = .onSetNeedsDisplay } open override var wantsUpdateLayer: Bool { return wantsLayer } override open func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) if let context = NSGraphicsContext.current?.cgContext { context.setFillColor(backgroundColor.cgColor) context.fill(dirtyRect) } } open override func updateLayer() { guard let layer = layer else { return } layer.backgroundColor = backgroundColor.cgColor } }
26.875
147
0.623256
e898f8dda77ea4be01437ebb248716e138daf40a
1,888
// Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation public func scale<Bound>(domain: Interval<Bound>, range: Interval<Bound>) -> (Bound) -> Bound where Bound: FloatingPoint { { range.scale(domain.descale($0)) } } public func scale<S>(domain: Interval<S.Scalar>, range: Interval<S>) -> (S.Scalar) -> S where S: SIMD, S.Scalar: FloatingPoint { { range.scale(domain.descale($0)) } } public func scale(domain: Interval<Double>, range: Interval<Colour>) -> (Double) -> Colour { { range.scale(domain.descale($0)) } } public func scale(domain: Interval<Date>, range: Interval<Double>) -> (Date) -> Double { { range.scale(domain.descale($0)) } } public func scale(domain: DurationUnit, range: DurationUnit) -> (Double) -> Double { { $0 * domain / range } }
37.76
128
0.698623
0afa3e135a1ab1acc115ba27b1a900369c7f112c
23,654
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // PurchasesOrchestratorTests.swift // // Created by Andrés Boedo on 1/9/21. import Foundation import Nimble @testable import RevenueCat import StoreKit import XCTest class PurchasesOrchestratorTests: StoreKitConfigTestCase { var productsManager: MockProductsManager! var storeKitWrapper: MockStoreKitWrapper! var systemInfo: MockSystemInfo! var subscriberAttributesManager: MockSubscriberAttributesManager! var operationDispatcher: MockOperationDispatcher! var receiptFetcher: MockReceiptFetcher! var customerInfoManager: MockCustomerInfoManager! var backend: MockBackend! var identityManager: MockIdentityManager! var transactionsManager: MockTransactionsManager! var deviceCache: MockDeviceCache! var mockManageSubsHelper: MockManageSubscriptionsHelper! var mockBeginRefundRequestHelper: MockBeginRefundRequestHelper! var orchestrator: PurchasesOrchestrator! override func setUpWithError() throws { try super.setUpWithError() try setUpSystemInfo() productsManager = MockProductsManager(systemInfo: systemInfo) operationDispatcher = MockOperationDispatcher() receiptFetcher = MockReceiptFetcher(requestFetcher: MockRequestFetcher(), systemInfo: systemInfo) deviceCache = MockDeviceCache(systemInfo: systemInfo) backend = MockBackend() customerInfoManager = MockCustomerInfoManager(operationDispatcher: OperationDispatcher(), deviceCache: deviceCache, backend: backend, systemInfo: systemInfo) identityManager = MockIdentityManager(mockAppUserID: "appUserID") transactionsManager = MockTransactionsManager(receiptParser: MockReceiptParser()) let attributionFetcher = MockAttributionFetcher(attributionFactory: MockAttributionTypeFactory(), systemInfo: systemInfo) subscriberAttributesManager = MockSubscriberAttributesManager( backend: backend, deviceCache: deviceCache, attributionFetcher: attributionFetcher, attributionDataMigrator: MockAttributionDataMigrator()) mockManageSubsHelper = MockManageSubscriptionsHelper(systemInfo: systemInfo, customerInfoManager: customerInfoManager, identityManager: identityManager) mockBeginRefundRequestHelper = MockBeginRefundRequestHelper(systemInfo: systemInfo, customerInfoManager: customerInfoManager, identityManager: identityManager) setupStoreKitWrapper() setUpOrchestrator() setUpStoreKit2Listener() } fileprivate func setUpStoreKit2Listener() { if #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) { orchestrator.storeKit2Listener = MockStoreKit2TransactionListener() } } @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) var mockStoreKit2TransactionListener: MockStoreKit2TransactionListener? { return orchestrator.storeKit2Listener as? MockStoreKit2TransactionListener } fileprivate func setUpSystemInfo(finishTransactions: Bool = true) throws { let platformInfo = Purchases.PlatformInfo(flavor: "xyz", version: "1.2.3") systemInfo = try MockSystemInfo(platformInfo: platformInfo, finishTransactions: finishTransactions) } fileprivate func setupStoreKitWrapper() { storeKitWrapper = MockStoreKitWrapper() storeKitWrapper.mockAddPaymentTransactionState = .purchased storeKitWrapper.mockCallUpdatedTransactionInstantly = true } fileprivate func setUpOrchestrator() { orchestrator = PurchasesOrchestrator(productsManager: productsManager, storeKitWrapper: storeKitWrapper, systemInfo: systemInfo, subscriberAttributesManager: subscriberAttributesManager, operationDispatcher: operationDispatcher, receiptFetcher: receiptFetcher, customerInfoManager: customerInfoManager, backend: backend, identityManager: identityManager, transactionsManager: transactionsManager, deviceCache: deviceCache, manageSubscriptionsHelper: mockManageSubsHelper, beginRefundRequestHelper: mockBeginRefundRequestHelper) storeKitWrapper.delegate = orchestrator } func testPurchaseSK1PackageSendsReceiptToBackendIfSuccessful() async throws { customerInfoManager.stubbedCachedCustomerInfoResult = mockCustomerInfo backend.stubbedPostReceiptCustomerInfo = mockCustomerInfo let product = try await fetchSk1Product() let storeProduct = try await fetchSk1StoreProduct() let package = Package(identifier: "package", packageType: .monthly, storeProduct: storeProduct, offeringIdentifier: "offering") let payment = storeKitWrapper.payment(withProduct: product) _ = await withCheckedContinuation { continuation in orchestrator.purchase(sk1Product: product, payment: payment, package: package) { transaction, customerInfo, error, userCancelled in continuation.resume(returning: (transaction, customerInfo, error, userCancelled)) } } expect(self.backend.invokedPostReceiptDataCount) == 1 } func testPurchaseSK1PromotionalOffer() async throws { customerInfoManager.stubbedCachedCustomerInfoResult = mockCustomerInfo backend.stubbedPostReceiptCustomerInfo = mockCustomerInfo backend.stubbedPostOfferCompetionResult = ("signature", "identifier", UUID(), 12345, nil) let product = try await fetchSk1Product() let storeProductDiscount = MockStoreProductDiscount(offerIdentifier: "offerid1", currencyCode: product.priceLocale.currencyCode, price: 11.1, localizedPriceString: "$11.10", paymentMode: .payAsYouGo, subscriptionPeriod: .init(value: 1, unit: .month), type: .promotional) _ = await withCheckedContinuation { continuation in orchestrator.promotionalOffer(forProductDiscount: storeProductDiscount, product: StoreProduct(sk1Product: product)) { paymentDiscount, error in continuation.resume(returning: (paymentDiscount, error)) } } expect(self.backend.invokedPostOfferCount) == 1 expect(self.backend.invokedPostOfferParameters?.offerIdentifier) == storeProductDiscount.offerIdentifier } func testPurchaseSK1PackageWithDiscountSendsReceiptToBackendIfSuccessful() async throws { customerInfoManager.stubbedCachedCustomerInfoResult = mockCustomerInfo backend.stubbedPostOfferCompetionResult = ("signature", "identifier", UUID(), 12345, nil) backend.stubbedPostReceiptCustomerInfo = mockCustomerInfo let product = try await fetchSk1Product() let storeProduct = StoreProduct(sk1Product: product) let package = Package(identifier: "package", packageType: .monthly, storeProduct: storeProduct, offeringIdentifier: "offering") let discount = MockStoreProductDiscount(offerIdentifier: "offerid1", currencyCode: storeProduct.currencyCode, price: 11.1, localizedPriceString: "$11.10", paymentMode: .payAsYouGo, subscriptionPeriod: .init(value: 1, unit: .month), type: .promotional) let offer = PromotionalOffer(discount: discount, signedData: .init(identifier: "", keyIdentifier: "", nonce: UUID(), signature: "", timestamp: 0)) _ = await withCheckedContinuation { continuation in orchestrator.purchase(sk1Product: product, promotionalOffer: offer, package: package) { transaction, customerInfo, error, userCancelled in continuation.resume(returning: (transaction, customerInfo, error, userCancelled)) } } expect(self.backend.invokedPostReceiptDataCount) == 1 } @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) func testPurchaseSK2PackageReturnsCorrectValues() async throws { try AvailabilityChecks.iOS15APIAvailableOrSkipTest() let mockTransaction = try await createTransactionWithPurchase() customerInfoManager.stubbedCachedCustomerInfoResult = mockCustomerInfo backend.stubbedPostReceiptCustomerInfo = mockCustomerInfo mockStoreKit2TransactionListener?.mockTransaction = .init(mockTransaction) let product = try await self.fetchSk2Product() let (transaction, customerInfo, userCancelled) = try await orchestrator.purchase(sk2Product: product, promotionalOffer: nil) expect(transaction?.sk2Transaction) == mockTransaction expect(userCancelled) == false let expectedCustomerInfo = try CustomerInfo(data: [ "request_date": "2019-08-16T10:30:42Z", "subscriber": [ "first_seen": "2019-07-17T00:05:54Z", "original_app_user_id": "", "subscriptions": [:], "other_purchases": [:] ]]) expect(customerInfo) == expectedCustomerInfo } @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) func testPurchaseSK2PackageHandlesPurchaseResult() async throws { try AvailabilityChecks.iOS15APIAvailableOrSkipTest() customerInfoManager.stubbedCachedCustomerInfoResult = mockCustomerInfo backend.stubbedPostReceiptCustomerInfo = mockCustomerInfo let storeProduct = StoreProduct.from(product: try await fetchSk2StoreProduct()) let package = Package(identifier: "package", packageType: .monthly, storeProduct: storeProduct, offeringIdentifier: "offering") _ = await withCheckedContinuation { continuation in orchestrator.purchase(product: storeProduct, package: package) { transaction, customerInfo, error, userCancelled in continuation.resume(returning: (transaction, customerInfo, error, userCancelled)) } } let mockListener = try XCTUnwrap(orchestrator.storeKit2Listener as? MockStoreKit2TransactionListener) expect(mockListener.invokedHandle) == true } @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) func testPurchaseSK2PackageSendsReceiptToBackendIfSuccessful() async throws { try AvailabilityChecks.iOS15APIAvailableOrSkipTest() customerInfoManager.stubbedCachedCustomerInfoResult = mockCustomerInfo backend.stubbedPostReceiptCustomerInfo = mockCustomerInfo let product = try await fetchSk2Product() _ = try await orchestrator.purchase(sk2Product: product, promotionalOffer: nil) expect(self.backend.invokedPostReceiptDataCount) == 1 } @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) func testPurchaseSK2PackageSkipsIfPurchaseFailed() async throws { try AvailabilityChecks.iOS15APIAvailableOrSkipTest() testSession.failTransactionsEnabled = true customerInfoManager.stubbedCachedCustomerInfoResult = mockCustomerInfo backend.stubbedPostReceiptCustomerInfo = mockCustomerInfo let product = try await fetchSk2Product() let storeProduct = StoreProduct(sk2Product: product) let discount = MockStoreProductDiscount(offerIdentifier: "offerid1", currencyCode: storeProduct.currencyCode, price: 11.1, localizedPriceString: "$11.10", paymentMode: .payAsYouGo, subscriptionPeriod: .init(value: 1, unit: .month), type: .promotional) let offer = PromotionalOffer(discount: discount, signedData: .init(identifier: "", keyIdentifier: "", nonce: UUID(), signature: "", timestamp: 0)) do { _ = try await orchestrator.purchase(sk2Product: product, promotionalOffer: offer) XCTFail("Expected error") } catch { expect(self.backend.invokedPostReceiptData) == false let mockListener = try XCTUnwrap(orchestrator.storeKit2Listener as? MockStoreKit2TransactionListener) expect(mockListener.invokedHandle) == false } } @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) func testPurchaseSK2PackageReturnsMissingReceiptErrorIfSendReceiptFailed() async throws { try AvailabilityChecks.iOS15APIAvailableOrSkipTest() receiptFetcher.shouldReturnReceipt = false let expectedError = ErrorUtils.missingReceiptFileError() let product = try await fetchSk2Product() do { _ = try await orchestrator.purchase(sk2Product: product, promotionalOffer: nil) XCTFail("Expected error") } catch { expect(error).to(matchError(expectedError)) let mockListener = try XCTUnwrap(orchestrator.storeKit2Listener as? MockStoreKit2TransactionListener) expect(mockListener.invokedHandle) == true } } @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) func testStoreKit2TransactionListenerDelegate() async throws { try AvailabilityChecks.iOS15APIAvailableOrSkipTest() customerInfoManager.stubbedCachedCustomerInfoResult = mockCustomerInfo orchestrator.transactionsUpdated() expect(self.backend.invokedPostReceiptData).to(beTrue()) expect(self.backend.invokedPostReceiptDataParameters?.isRestore).to(beFalse()) } func testStoreKit2TransactionListenerDelegateWithObserverMode() async throws { try AvailabilityChecks.iOS15APIAvailableOrSkipTest() try setUpSystemInfo(finishTransactions: false) setUpOrchestrator() customerInfoManager.stubbedCachedCustomerInfoResult = mockCustomerInfo orchestrator.transactionsUpdated() expect(self.backend.invokedPostReceiptData).to(beTrue()) expect(self.backend.invokedPostReceiptDataParameters?.isRestore).to(beTrue()) } @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) func testPurchaseSK2PromotionalOffer() async throws { try AvailabilityChecks.iOS15APIAvailableOrSkipTest() customerInfoManager.stubbedCachedCustomerInfoResult = mockCustomerInfo backend.stubbedPostReceiptCustomerInfo = mockCustomerInfo backend.stubbedPostOfferCompetionResult = ("signature", "identifier", UUID(), 12345, nil) let product = try await fetchSk2Product() let storeProduct = StoreProduct(sk2Product: product) let storeProductDiscount = MockStoreProductDiscount(offerIdentifier: "offerid1", currencyCode: storeProduct.currencyCode, price: 11.1, localizedPriceString: "$11.10", paymentMode: .payAsYouGo, subscriptionPeriod: .init(value: 1, unit: .month), type: .promotional) _ = try await orchestrator.promotionalOffer(forProductDiscount: storeProductDiscount, product: StoreProduct(sk2Product: product)) expect(self.backend.invokedPostOfferCount) == 1 expect(self.backend.invokedPostOfferParameters?.offerIdentifier) == storeProductDiscount.offerIdentifier } func testShowManageSubscriptionsCallsCompletionWithErrorIfThereIsAFailure() { let message = "Failed to get managementURL from CustomerInfo. Details: customerInfo is nil." mockManageSubsHelper.mockError = ErrorUtils.customerInfoError(withMessage: message) var receivedError: Error? var completionCalled = false orchestrator.showManageSubscription { error in completionCalled = true receivedError = error } expect(completionCalled).toEventually(beTrue()) expect(receivedError).toNot(beNil()) expect(receivedError).to(matchError(ErrorCode.customerInfoError)) } @available(iOS 15.0, macCatalyst 15.0, *) @available(watchOS, unavailable) @available(tvOS, unavailable) @available(macOS, unavailable) func testBeginRefundForProductCompletesWithoutErrorAndPassesThroughStatusIfSuccessful() async throws { let expectedStatus = RefundRequestStatus.userCancelled mockBeginRefundRequestHelper.mockRefundRequestStatus = expectedStatus let refundStatus = try await orchestrator.beginRefundRequest(forProduct: "1234") expect(refundStatus) == expectedStatus } @available(iOS 15.0, macCatalyst 15.0, *) @available(watchOS, unavailable) @available(tvOS, unavailable) @available(macOS, unavailable) func testBeginRefundForProductCompletesWithErrorIfThereIsAFailure() async { let expectedError = ErrorUtils.beginRefundRequestError(withMessage: "test") mockBeginRefundRequestHelper.mockError = expectedError do { _ = try await orchestrator.beginRefundRequest(forProduct: "1235") XCTFail("beginRefundRequestForProduct should have thrown an error") } catch { expect(error).to(matchError(expectedError)) } } @available(iOS 15.0, macCatalyst 15.0, *) @available(watchOS, unavailable) @available(tvOS, unavailable) @available(macOS, unavailable) func testBeginRefundForEntitlementCompletesWithoutErrorAndPassesThroughStatusIfSuccessful() async throws { let expectedStatus = RefundRequestStatus.userCancelled mockBeginRefundRequestHelper.mockRefundRequestStatus = expectedStatus let receivedStatus = try await orchestrator.beginRefundRequest(forEntitlement: "1234") expect(receivedStatus) == expectedStatus } @available(iOS 15.0, macCatalyst 15.0, *) @available(watchOS, unavailable) @available(tvOS, unavailable) @available(macOS, unavailable) func testBeginRefundForEntitlementCompletesWithErrorIfThereIsAFailure() async { let expectedError = ErrorUtils.beginRefundRequestError(withMessage: "test") mockBeginRefundRequestHelper.mockError = expectedError do { _ = try await orchestrator.beginRefundRequest(forEntitlement: "1234") XCTFail("beginRefundRequestForEntitlement should have thrown error") } catch { expect(error).toNot(beNil()) expect(error).to(matchError(expectedError)) } } @available(iOS 15.0, macCatalyst 15.0, *) @available(watchOS, unavailable) @available(tvOS, unavailable) @available(macOS, unavailable) func testBeginRefundForActiveEntitlementCompletesWithoutErrorAndPassesThroughStatusIfSuccessful() async throws { let expectedStatus = RefundRequestStatus.userCancelled mockBeginRefundRequestHelper.mockRefundRequestStatus = expectedStatus let receivedStatus = try await orchestrator.beginRefundRequestForActiveEntitlement() expect(receivedStatus) == expectedStatus } @available(iOS 15.0, macCatalyst 15.0, *) @available(watchOS, unavailable) @available(tvOS, unavailable) @available(macOS, unavailable) func testBeginRefundForActiveEntitlementCompletesWithErrorIfThereIsAFailure() async { let expectedError = ErrorUtils.beginRefundRequestError(withMessage: "test") mockBeginRefundRequestHelper.mockError = expectedError do { _ = try await orchestrator.beginRefundRequestForActiveEntitlement() XCTFail("beginRefundRequestForActiveEntitlement should have thrown error") } catch { expect(error).toNot(beNil()) expect(error).to(matchError(expectedError)) expect(error.localizedDescription).to(equal(expectedError.localizedDescription)) } } } private extension PurchasesOrchestratorTests { @MainActor func fetchSk1Product() async throws -> SK1Product { return MockSK1Product( mockProductIdentifier: Self.productID, mockSubscriptionGroupIdentifier: "group1" ) } @MainActor func fetchSk1StoreProduct() async throws -> SK1StoreProduct { return try await SK1StoreProduct(sk1Product: fetchSk1Product()) } var mockCustomerInfo: CustomerInfo { // swiftlint:disable:next force_try try! CustomerInfo(data: [ "request_date": "2019-08-16T10:30:42Z", "subscriber": [ "first_seen": "2019-07-17T00:05:54Z", "original_app_user_id": "", "subscriptions": [:], "other_purchases": [:] ]]) } }
46.93254
116
0.620064
8a5c3278e02facc2abf8b5aa27ea88474c5ac819
194
import PackageDescription let package = Package( name: "BrickRequest", dependencies: [ .Package(url: "https://github.com/Alamofire/Alamofire.git", majorVersion: 3), ] )
21.555556
90
0.654639
7a24f0f45d54a9ef1a65e8a74e079440f64d5ce5
10,010
import Foundation import UIKit public protocol DesktopAppDelegate{ /// Called when desktop application is doubled tapped. /// /// - Parameter application: The current desktop application. func didDoubleClick(_ application: DesktopApplication) /// Called when application is about to start dragging. /// /// - Parameter application: The current Desktop Application. func willStartDragging(_ application: DesktopApplication) /// Called when dragging is over. /// /// - Parameter application: The current Desktop Application. func didFinishDragging(_ application: DesktopApplication) } /// DesktopViewConnectionDelegate is the bridge between the MacAppDesktopView and the DesktopAppDelegate. public protocol DesktopViewConnectionDelegate{ /// Called when desktop application is doubled tapped. func didDoubleClick() /// Called when application is about to start dragging. func willStartDragging() /// Called when dragging is over. func didFinishDragging() } /// The DesktopAppDataSource is what provides the display meta data to the Desktop Application View public protocol DesktopAppDataSource{ /// The image that will be displayed as an icon var image: UIImage {get} /// The title/text that will be displayed on the app var name: String {get} } public class DesktopApplication{ /// This function creates an instance of Desktop Application using `MacApp` instance and `OSWindow` instance. Where the `MacApp` is used as a data source and the `OSWindow` is used as a delegate. /// /// - Parameters: /// - app: The app which we want to display on the desktop. Note that this MacApp must have a desktopIcon value. /// - window: The OSWindow instance in which we are display the desktop application. /// - Returns: The new created instance of DesktopApplication public static func make(app: MacApp,in window: OSWindow)->DesktopApplication{ let desktopApp = DesktopApplication(with: window) desktopApp.app = app desktopApp.delegate = window return desktopApp } /// The data source for this Desktop Application public var app: MacApp?{ didSet{ view = MacAppDesktopView(dataSource: self) } } /// The delegate for this Desktop Application public var delegate: DesktopAppDelegate?{ didSet{ view?.delegate = self } } /// The Desktop View public var view: MacAppDesktopView! /// A strong reference to the current window, in case the desktop application needs to make some changes to it. var window: OSWindow! public init(with window: OSWindow){ self.window = window } } /// Conform to DesktopViewConnectionDelegate extension DesktopApplication: DesktopViewConnectionDelegate{ public func didFinishDragging() { delegate?.didFinishDragging(self) } public func willStartDragging() { delegate?.willStartDragging(self) } public func didDoubleClick(){ delegate?.didDoubleClick(self) } } /// Conform to DesktopAppDataSource extension DesktopApplication: DesktopAppDataSource{ public var name: String { return app?.windowTitle ?? "" } public var image: UIImage { return app!.desktopIcon! } } /// The MacAppDesktopView public class MacAppDesktopView: UIView{ /// The data source var dataSource: DesktopAppDataSource? /// The delegate var delegate: DesktopViewConnectionDelegate? /// The icon (as image view) var icon: UIImageView! /// The text label var text: UILabel! /// The transition window frame (The border the user sees when the app is being dragged) var transitionWindowFrame: MovingApplication? /// The last location (A property used for dragging) var lastLocation: CGPoint = .zero /// The width of desktop applications static let width: CGFloat = 65.0 /// The space between the image view and the frame static let space: CGFloat = 3.0 /// The scale of the image relative to the width static let imageScale: CGFloat = 0.8 /// initialization should always be done using this initailizer because a data source is needed in order to calculate the view's frame height. /// /// - Parameter dataSource: The desktop app data source which contains an image and a string. convenience init(dataSource: DesktopAppDataSource){ //calculate needed height let imageHeight: CGFloat = MacAppDesktopView.imageScale * MacAppDesktopView.width let textWidth = MacAppDesktopView.width - MacAppDesktopView.space * 2 let textHeight = Utils.heightForView(dataSource.name, font: SystemSettings.notePadFont, width: textWidth, numberOfLines: 0) let totalHeight = textHeight + imageHeight let rect = CGRect(origin: CGPoint.zero, size: CGSize(width: MacAppDesktopView.width, height: totalHeight)) self.init(frame: rect) self.dataSource = dataSource setup() } /// Never ussed this /// /// - Parameter frame: The frame size of the view override public init(frame: CGRect){ super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup(){ // setup image view let imageWidth = MacAppDesktopView.imageScale * MacAppDesktopView.width icon = UIImageView(frame: CGRect(x: (MacAppDesktopView.width - imageWidth)/2, y: 0, width: imageWidth, height: imageWidth)) icon.image = dataSource?.image icon.contentMode = .scaleAspectFit // setup text view let textWidth = MacAppDesktopView.width - MacAppDesktopView.space * 2 let textHeight = Utils.heightForView(dataSource!.name, font: SystemSettings.notePadFont, width: textWidth, numberOfLines: 0) text = UILabel(frame: CGRect(x: (MacAppDesktopView.width - textWidth)/2, y: imageWidth, width: textWidth, height: textHeight)) text.backgroundColor = .white text.text = dataSource?.name text.font = SystemSettings.notePadFont text.textAlignment = .center text.numberOfLines = 0 addSubview(icon) addSubview(text) // setup transition frame transitionWindowFrame = MovingApplication(textHeight: textHeight, textWidth: textWidth, totalWidth: MacAppDesktopView.width) transitionWindowFrame?.isHidden = true transitionWindowFrame?.backgroundColor = .clear addSubview(transitionWindowFrame!) // add gesture recognizers addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handlePan(sender:)))) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:))) tapGesture.numberOfTapsRequired = 2 addGestureRecognizer(tapGesture) } /// Selector function, handles taps /// /// - Parameter sender: UITapGestureRecognizer func handleTap(sender: UITapGestureRecognizer){ delegate?.didDoubleClick() } /// Selector fuction, handles drag /// /// - Parameter sender: UIPanGestureRecognizer func handlePan(sender: UIPanGestureRecognizer){ let translation = sender.translation(in: self.superview!) switch sender.state{ case .began: transitionWindowFrame?.isHidden = false transitionWindowFrame?.frame = CGRect(origin: CGPoint(x: 0 , y: 0), size: bounds.size) transitionWindowFrame?.lastLocation = (self.transitionWindowFrame?.center)! delegate?.willStartDragging() break case .ended: transitionWindowFrame?.isHidden = true self.center = convert(transitionWindowFrame!.center, to: superview!) delegate?.didFinishDragging() return default: break } let point = CGPoint(x: (transitionWindowFrame?.lastLocation.x)! + translation.x , y: (transitionWindowFrame?.lastLocation.y)! + translation.y) transitionWindowFrame?.center = point } } /// This is the class of which we create the transitioning window frame class MovingApplication: UIView{ var lastLocation = CGPoint(x: 0, y: 0) var width: CGFloat! var imageSize: CGFloat! var textHeight: CGFloat! var textWidth: CGFloat! convenience init(textHeight: CGFloat,textWidth: CGFloat,totalWidth: CGFloat){ self.init(frame: CGRect(x: 0, y: 0, width: textWidth, height: totalWidth * MacAppDesktopView.imageScale + textHeight)) self.textHeight = textHeight self.textWidth = textWidth self.width = totalWidth self.imageSize = totalWidth * MacAppDesktopView.imageScale } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { UIColor.lightGray.setStroke() let path = UIBezierPath() path.move(to: CGPoint(x: (width - imageSize)/2, y: 0)) path.addLine(to: CGPoint(x: (width - imageSize)/2, y: imageSize)) path.addLine(to: CGPoint(x: 0, y: imageSize)) path.addLine(to: CGPoint(x: 0, y: textHeight + imageSize)) path.addLine(to: CGPoint(x: textWidth, y: textHeight + imageSize)) path.addLine(to: CGPoint(x: textWidth, y: imageSize)) path.addLine(to: CGPoint(x: imageSize, y: imageSize)) path.addLine(to: CGPoint(x: imageSize , y: 0)) path.close() path.lineWidth = 1 path.stroke() } }
33.703704
199
0.659241
abc1505f14dbac771551ecd4f9c51d3982cbc47a
1,014
// // NormalBaseVC.swift // WDL_TYR // // Created by 黄露 on 2018/8/24. // Copyright © 2018年 yingli. All rights reserved. // import UIKit class NormalBaseVC: MainBaseVC { override func viewDidLoad() { super.viewDidLoad() self.wr_setStatusBarStyle(UIStatusBarStyle.default) self.wr_setNavBarBarTintColor(UIColor(hex: "F6F6F6")) self.wr_setNavBarTintColor(UIColor(hex: "999999")) self.wr_setNavBarTitleColor(UIColor(hex: "333333")) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
26.684211
106
0.675542
e2d7c013aae700f2ab7f91a4dc1624ecaaba95f3
2,666
// // UILabel+Message.swift // SwiftEntryKit // // Created by Daniel Huri on 04/14/2018. // Copyright (c) 2018 [email protected]. All rights reserved. // import UIKit import QuickLayout extension UILabel { var style: EKProperty.LabelStyle { set { font = newValue.font textColor = newValue.color textAlignment = newValue.alignment numberOfLines = newValue.numberOfLines } get { return EKProperty.LabelStyle(font: font, color: textColor, alignment: textAlignment, numberOfLines: numberOfLines) } } var content: EKProperty.LabelContent { set { text = newValue.text style = newValue.style } get { return EKProperty.LabelContent(text: text ?? "", style: style) } } } extension UIButton { var buttonContent: EKProperty.ButtonContent { set { setTitle(newValue.label.text, for: .normal) setTitleColor(newValue.label.style.color, for: .normal) titleLabel?.font = newValue.label.style.font backgroundColor = newValue.backgroundColor } get { fatalError("buttonContent doesn't have a getter") } } } extension UIImageView { var imageContent: EKProperty.ImageContent { set { image = newValue.image contentMode = newValue.contentMode if let size = newValue.size { set(.width, of: size.width) set(.height, of: size.height) } else { forceContentWrap() } layoutIfNeeded() if newValue.makeRound { clipsToBounds = true layer.cornerRadius = max(bounds.width, bounds.height) * 0.5 } } get { fatalError("imageContent doesn't have a getter") } } } extension UITextField { var textFieldContent: EKProperty.TextFieldContent { set { attributedPlaceholder = NSAttributedString(string: newValue.placeholder.text, attributes: [.font: newValue.placeholder.style.font, .foregroundColor: newValue.placeholder.style.color]) keyboardType = newValue.keyboardType textColor = newValue.textStyle.color font = newValue.textStyle.font textAlignment = newValue.textStyle.alignment isSecureTextEntry = newValue.isSecure text = newValue.textContent } get { fatalError("textFieldContent doesn't have a getter") } } }
28.978261
195
0.575019
7aab97f2d20a2a48ae90e95e536c759b9e1a6707
4,198
//===--------------- Job.swift - Swift Job Abstraction --------------------===// // // 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 // //===----------------------------------------------------------------------===// import TSCBasic /// A job represents an individual subprocess that should be invoked during compilation. public struct Job: Codable, Equatable, Hashable { public enum Kind: String, Codable { case compile case mergeModule = "merge-module" case link case generateDSYM = "generate-dsym" case autolinkExtract = "autolink-extract" case emitModule = "emit-module" case generatePCH = "generate-pch" /// Generate a compiled Clang module. case generatePCM = "generate-pcm" case interpret case repl case verifyDebugInfo = "verify-debug-info" case printTargetInfo = "print-target-info" case versionRequest = "version-request" } public enum ArgTemplate: Equatable, Hashable { /// Represents a command-line flag that is substitued as-is. case flag(String) /// Represents a virtual path on disk. case path(VirtualPath) } /// The tool to invoke. public var tool: VirtualPath /// The command-line arguments of the job. public var commandLine: [ArgTemplate] /// Whether or not the job supports using response files to pass command line arguments. public var supportsResponseFiles: Bool /// The list of inputs to use for displaying purposes. public var displayInputs: [TypedVirtualPath] /// The list of inputs for this job. public var inputs: [TypedVirtualPath] /// The outputs produced by the job. public var outputs: [TypedVirtualPath] /// Any extra environment variables which should be set while running the job. public var extraEnvironment: [String: String] /// Whether or not the job must be executed in place, replacing the current driver process. public var requiresInPlaceExecution: Bool /// The kind of job. public var kind: Kind public init( kind: Kind, tool: VirtualPath, commandLine: [ArgTemplate], displayInputs: [TypedVirtualPath]? = nil, inputs: [TypedVirtualPath], outputs: [TypedVirtualPath], extraEnvironment: [String: String] = [:], requiresInPlaceExecution: Bool = false, supportsResponseFiles: Bool = false ) { self.kind = kind self.tool = tool self.commandLine = commandLine self.displayInputs = displayInputs ?? [] self.inputs = inputs self.outputs = outputs self.extraEnvironment = extraEnvironment self.requiresInPlaceExecution = requiresInPlaceExecution self.supportsResponseFiles = supportsResponseFiles } } // MARK: - Job.ArgTemplate + Codable extension Job.ArgTemplate: Codable { private enum CodingKeys: String, CodingKey { case flag, path } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case let .flag(a1): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .flag) try unkeyedContainer.encode(a1) case let .path(a1): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .path) try unkeyedContainer.encode(a1) } } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) guard let key = values.allKeys.first(where: values.contains) else { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Did not find a matching key")) } switch key { case .flag: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let a1 = try unkeyedValues.decode(String.self) self = .flag(a1) case .path: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let a1 = try unkeyedValues.decode(VirtualPath.self) self = .path(a1) } } }
32.796875
127
0.690329
e6403525b98285a27b33944fc778b668655e5eaa
936
// // SSSettingsTableViewCell.swift // ArduinoController-ios // // Created by Saee Saadat on 2/14/21. // import UIKit class SSSettingsTableViewCell: UITableViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var separator: UIView! override func awakeFromNib() { super.awakeFromNib() } func setupCell(title: String, icon: UIImage?, tint: UIColor = SSColors.accent.color, isLast: Bool = false) { self.titleLabel.text = title self.iconImageView.image = icon self.titleLabel.textColor = tint self.iconImageView.tintColor = tint self.separator.isHidden = isLast } override func setSelected(_ selected: Bool, animated: Bool) { // super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
24
112
0.647436
f8faff77f87818c50f6b4e6967c2946c08bc0aad
500
// // File.swift // // // Created by Joe Blau on 6/9/19. // import Foundation public struct TweetItem: Codable { public let _id: String public let text: String public let username: String public let id: String public let publishedAt: String public let isRetweeted: Bool public let retweetCount: Int public let favouriteCount: Int public let links: [String] public let hashtags: [String] public let mentions: [String] public let symbols: [String] }
20.833333
34
0.68
147438b8b3cee080eee4a1de7b31e94f6eb1bdd6
308
// // ThematicBreak.swift // Down // // Created by John Nguyen on 09.04.19. // import Foundation import libcmark public class ThematicBreak: BaseNode {} // MARK: - Debug extension ThematicBreak: CustomDebugStringConvertible { public var debugDescription: String { "Thematic Break" } }
15.4
55
0.694805
2f39a5b70ba0bab4affc58998379c08ec24260a0
1,688
// // Action.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public class Action: Codable { /** The globally unique identifier for the object. */ public var _id: String? public var name: String? /** The ID of the integration for which this action is associated */ public var integrationId: String? /** Category of Action */ public var category: String? /** Action contract */ public var contract: ActionContract? /** Version of this action */ public var version: Int? /** Indication of whether or not the action is designed to accept sensitive data */ public var secure: Bool? /** Configuration to support request and response processing */ public var config: ActionConfig? /** The URI for this object */ public var selfUri: String? public init(_id: String?, name: String?, integrationId: String?, category: String?, contract: ActionContract?, version: Int?, secure: Bool?, config: ActionConfig?, selfUri: String?) { self._id = _id self.name = name self.integrationId = integrationId self.category = category self.contract = contract self.version = version self.secure = secure self.config = config self.selfUri = selfUri } public enum CodingKeys: String, CodingKey { case _id = "id" case name case integrationId case category case contract case version case secure case config case selfUri } }
24.463768
187
0.60545
9042e1c3a0d7c52c87e4f1159bae68da8d9eb7d7
2,506
// // Copyright 2018-2020 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Amplify import Combine class MockDataStoreCategoryPlugin: MessageReporter, DataStoreCategoryPlugin { var key: String { return "MockDataStoreCategoryPlugin" } func configure(using configuration: Any) throws { notify() } func reset(onComplete: @escaping BasicClosure) { notify("reset") onComplete() } func save<M: Model>(_ model: M, where condition: QueryPredicate? = nil, completion: (DataStoreResult<M>) -> Void) { notify("save") } func query<M: Model>(_ modelType: M.Type, byId id: String, completion: (DataStoreResult<M?>) -> Void) { notify("queryById") } func query<M: Model>(_ modelType: M.Type, where predicate: QueryPredicate?, paginate paginationInput: QueryPaginationInput?, completion: (DataStoreResult<[M]>) -> Void) { notify("queryByPredicate") } func delete<M: Model>(_ modelType: M.Type, withId id: String, completion: (DataStoreResult<Void>) -> Void) { notify("deleteById") } func delete<M: Model>(_ model: M, where predicate: QueryPredicate? = nil, completion: @escaping DataStoreCallback<Void>) { notify("deleteByPredicate") } func clear(completion: @escaping DataStoreCallback<Void>) { notify("clear") } @available(iOS 13.0, *) func publisher<M: Model>(for modelType: M.Type) -> AnyPublisher<MutationEvent, DataStoreError> { let mutationEvent = MutationEvent(id: "testevent", modelId: "123", modelName: modelType.modelName, json: "", mutationType: .create, createdAt: .now()) notify("publisher") return Result.Publisher(mutationEvent).eraseToAnyPublisher() } } class MockSecondDataStoreCategoryPlugin: MockDataStoreCategoryPlugin { override var key: String { return "MockSecondDataStoreCategoryPlugin" } }
30.938272
77
0.531125
6962de786c11965dc96b320db3cd6f611738e961
180,812
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2021 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator. // DO NOT EDIT. import Foundation import SotoCore extension OpenSearch { // MARK: Enums public enum AutoTuneDesiredState: String, CustomStringConvertible, Codable { case disabled = "DISABLED" case enabled = "ENABLED" public var description: String { return self.rawValue } } public enum AutoTuneState: String, CustomStringConvertible, Codable { case disabled = "DISABLED" case disabledAndRollbackComplete = "DISABLED_AND_ROLLBACK_COMPLETE" case disabledAndRollbackError = "DISABLED_AND_ROLLBACK_ERROR" case disabledAndRollbackInProgress = "DISABLED_AND_ROLLBACK_IN_PROGRESS" case disabledAndRollbackScheduled = "DISABLED_AND_ROLLBACK_SCHEDULED" case disableInProgress = "DISABLE_IN_PROGRESS" case enabled = "ENABLED" case enableInProgress = "ENABLE_IN_PROGRESS" case error = "ERROR" public var description: String { return self.rawValue } } public enum AutoTuneType: String, CustomStringConvertible, Codable { case scheduledAction = "SCHEDULED_ACTION" public var description: String { return self.rawValue } } public enum DeploymentStatus: String, CustomStringConvertible, Codable { case completed = "COMPLETED" case eligible = "ELIGIBLE" case inProgress = "IN_PROGRESS" case notEligible = "NOT_ELIGIBLE" case pendingUpdate = "PENDING_UPDATE" public var description: String { return self.rawValue } } public enum DescribePackagesFilterName: String, CustomStringConvertible, Codable { case packageID = "PackageID" case packageName = "PackageName" case packageStatus = "PackageStatus" public var description: String { return self.rawValue } } public enum DomainPackageStatus: String, CustomStringConvertible, Codable { case active = "ACTIVE" case associating = "ASSOCIATING" case associationFailed = "ASSOCIATION_FAILED" case dissociating = "DISSOCIATING" case dissociationFailed = "DISSOCIATION_FAILED" public var description: String { return self.rawValue } } public enum EngineType: String, CustomStringConvertible, Codable { case elasticsearch = "Elasticsearch" case openSearch = "OpenSearch" public var description: String { return self.rawValue } } public enum InboundConnectionStatusCode: String, CustomStringConvertible, Codable { case active = "ACTIVE" case approved = "APPROVED" case deleted = "DELETED" case deleting = "DELETING" case pendingAcceptance = "PENDING_ACCEPTANCE" case provisioning = "PROVISIONING" case rejected = "REJECTED" case rejecting = "REJECTING" public var description: String { return self.rawValue } } public enum LogType: String, CustomStringConvertible, Codable { case auditLogs = "AUDIT_LOGS" case esApplicationLogs = "ES_APPLICATION_LOGS" case indexSlowLogs = "INDEX_SLOW_LOGS" case searchSlowLogs = "SEARCH_SLOW_LOGS" public var description: String { return self.rawValue } } public enum OpenSearchPartitionInstanceType: String, CustomStringConvertible, Codable { case c42XlargeSearch = "c4.2xlarge.search" case c44XlargeSearch = "c4.4xlarge.search" case c48XlargeSearch = "c4.8xlarge.search" case c4LargeSearch = "c4.large.search" case c4XlargeSearch = "c4.xlarge.search" case c518XlargeSearch = "c5.18xlarge.search" case c52XlargeSearch = "c5.2xlarge.search" case c54XlargeSearch = "c5.4xlarge.search" case c59XlargeSearch = "c5.9xlarge.search" case c5LargeSearch = "c5.large.search" case c5XlargeSearch = "c5.xlarge.search" case c6g12XlargeSearch = "c6g.12xlarge.search" case c6g2XlargeSearch = "c6g.2xlarge.search" case c6g4XlargeSearch = "c6g.4xlarge.search" case c6g8XlargeSearch = "c6g.8xlarge.search" case c6gLargeSearch = "c6g.large.search" case c6gXlargeSearch = "c6g.xlarge.search" case d22XlargeSearch = "d2.2xlarge.search" case d24XlargeSearch = "d2.4xlarge.search" case d28XlargeSearch = "d2.8xlarge.search" case d2XlargeSearch = "d2.xlarge.search" case i22XlargeSearch = "i2.2xlarge.search" case i2XlargeSearch = "i2.xlarge.search" case i316XlargeSearch = "i3.16xlarge.search" case i32XlargeSearch = "i3.2xlarge.search" case i34XlargeSearch = "i3.4xlarge.search" case i38XlargeSearch = "i3.8xlarge.search" case i3LargeSearch = "i3.large.search" case i3XlargeSearch = "i3.xlarge.search" case m32XlargeSearch = "m3.2xlarge.search" case m3LargeSearch = "m3.large.search" case m3MediumSearch = "m3.medium.search" case m3XlargeSearch = "m3.xlarge.search" case m410XlargeSearch = "m4.10xlarge.search" case m42XlargeSearch = "m4.2xlarge.search" case m44XlargeSearch = "m4.4xlarge.search" case m4LargeSearch = "m4.large.search" case m4XlargeSearch = "m4.xlarge.search" case m512XlargeSearch = "m5.12xlarge.search" case m524XlargeSearch = "m5.24xlarge.search" case m52XlargeSearch = "m5.2xlarge.search" case m54XlargeSearch = "m5.4xlarge.search" case m5LargeSearch = "m5.large.search" case m5XlargeSearch = "m5.xlarge.search" case m6g12XlargeSearch = "m6g.12xlarge.search" case m6g2XlargeSearch = "m6g.2xlarge.search" case m6g4XlargeSearch = "m6g.4xlarge.search" case m6g8XlargeSearch = "m6g.8xlarge.search" case m6gLargeSearch = "m6g.large.search" case m6gXlargeSearch = "m6g.xlarge.search" case r32XlargeSearch = "r3.2xlarge.search" case r34XlargeSearch = "r3.4xlarge.search" case r38XlargeSearch = "r3.8xlarge.search" case r3LargeSearch = "r3.large.search" case r3XlargeSearch = "r3.xlarge.search" case r416XlargeSearch = "r4.16xlarge.search" case r42XlargeSearch = "r4.2xlarge.search" case r44XlargeSearch = "r4.4xlarge.search" case r48XlargeSearch = "r4.8xlarge.search" case r4LargeSearch = "r4.large.search" case r4XlargeSearch = "r4.xlarge.search" case r512XlargeSearch = "r5.12xlarge.search" case r524XlargeSearch = "r5.24xlarge.search" case r52XlargeSearch = "r5.2xlarge.search" case r54XlargeSearch = "r5.4xlarge.search" case r5LargeSearch = "r5.large.search" case r5XlargeSearch = "r5.xlarge.search" case r6g12XlargeSearch = "r6g.12xlarge.search" case r6g2XlargeSearch = "r6g.2xlarge.search" case r6g4XlargeSearch = "r6g.4xlarge.search" case r6g8XlargeSearch = "r6g.8xlarge.search" case r6gLargeSearch = "r6g.large.search" case r6gXlargeSearch = "r6g.xlarge.search" case r6gd12XlargeSearch = "r6gd.12xlarge.search" case r6gd16XlargeSearch = "r6gd.16xlarge.search" case r6gd2XlargeSearch = "r6gd.2xlarge.search" case r6gd4XlargeSearch = "r6gd.4xlarge.search" case r6gd8XlargeSearch = "r6gd.8xlarge.search" case r6gdLargeSearch = "r6gd.large.search" case r6gdXlargeSearch = "r6gd.xlarge.search" case t2MediumSearch = "t2.medium.search" case t2MicroSearch = "t2.micro.search" case t2SmallSearch = "t2.small.search" case t32XlargeSearch = "t3.2xlarge.search" case t3LargeSearch = "t3.large.search" case t3MediumSearch = "t3.medium.search" case t3MicroSearch = "t3.micro.search" case t3NanoSearch = "t3.nano.search" case t3SmallSearch = "t3.small.search" case t3XlargeSearch = "t3.xlarge.search" case t4gMediumSearch = "t4g.medium.search" case t4gSmallSearch = "t4g.small.search" case ultrawarm1LargeSearch = "ultrawarm1.large.search" case ultrawarm1MediumSearch = "ultrawarm1.medium.search" case ultrawarm1XlargeSearch = "ultrawarm1.xlarge.search" public var description: String { return self.rawValue } } public enum OpenSearchWarmPartitionInstanceType: String, CustomStringConvertible, Codable { case ultrawarm1LargeSearch = "ultrawarm1.large.search" case ultrawarm1MediumSearch = "ultrawarm1.medium.search" case ultrawarm1XlargeSearch = "ultrawarm1.xlarge.search" public var description: String { return self.rawValue } } public enum OptionState: String, CustomStringConvertible, Codable { case active = "Active" case processing = "Processing" case requiresIndexDocuments = "RequiresIndexDocuments" public var description: String { return self.rawValue } } public enum OutboundConnectionStatusCode: String, CustomStringConvertible, Codable { case active = "ACTIVE" case approved = "APPROVED" case deleted = "DELETED" case deleting = "DELETING" case pendingAcceptance = "PENDING_ACCEPTANCE" case provisioning = "PROVISIONING" case rejected = "REJECTED" case rejecting = "REJECTING" case validating = "VALIDATING" case validationFailed = "VALIDATION_FAILED" public var description: String { return self.rawValue } } public enum PackageStatus: String, CustomStringConvertible, Codable { case available = "AVAILABLE" case copying = "COPYING" case copyFailed = "COPY_FAILED" case deleted = "DELETED" case deleteFailed = "DELETE_FAILED" case deleting = "DELETING" case validating = "VALIDATING" case validationFailed = "VALIDATION_FAILED" public var description: String { return self.rawValue } } public enum PackageType: String, CustomStringConvertible, Codable { case txtDictionary = "TXT-DICTIONARY" public var description: String { return self.rawValue } } public enum ReservedInstancePaymentOption: String, CustomStringConvertible, Codable { case allUpfront = "ALL_UPFRONT" case noUpfront = "NO_UPFRONT" case partialUpfront = "PARTIAL_UPFRONT" public var description: String { return self.rawValue } } public enum RollbackOnDisable: String, CustomStringConvertible, Codable { case defaultRollback = "DEFAULT_ROLLBACK" case noRollback = "NO_ROLLBACK" public var description: String { return self.rawValue } } public enum ScheduledAutoTuneActionType: String, CustomStringConvertible, Codable { case jvmHeapSizeTuning = "JVM_HEAP_SIZE_TUNING" case jvmYoungGenTuning = "JVM_YOUNG_GEN_TUNING" public var description: String { return self.rawValue } } public enum ScheduledAutoTuneSeverityType: String, CustomStringConvertible, Codable { case high = "HIGH" case low = "LOW" case medium = "MEDIUM" public var description: String { return self.rawValue } } public enum TLSSecurityPolicy: String, CustomStringConvertible, Codable { case policyMinTLS10201907 = "Policy-Min-TLS-1-0-2019-07" case policyMinTLS12201907 = "Policy-Min-TLS-1-2-2019-07" public var description: String { return self.rawValue } } public enum TimeUnit: String, CustomStringConvertible, Codable { case hours = "HOURS" public var description: String { return self.rawValue } } public enum UpgradeStatus: String, CustomStringConvertible, Codable { case failed = "FAILED" case inProgress = "IN_PROGRESS" case succeeded = "SUCCEEDED" case succeededWithIssues = "SUCCEEDED_WITH_ISSUES" public var description: String { return self.rawValue } } public enum UpgradeStep: String, CustomStringConvertible, Codable { case preUpgradeCheck = "PRE_UPGRADE_CHECK" case snapshot = "SNAPSHOT" case upgrade = "UPGRADE" public var description: String { return self.rawValue } } public enum VolumeType: String, CustomStringConvertible, Codable { case gp2 case io1 case standard public var description: String { return self.rawValue } } // MARK: Shapes public struct AWSDomainInformation: AWSEncodableShape & AWSDecodableShape { public let domainName: String public let ownerId: String? public let region: String? public init(domainName: String, ownerId: String? = nil, region: String? = nil) { self.domainName = domainName self.ownerId = ownerId self.region = region } public func validate(name: String) throws { try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") try self.validate(self.ownerId, name: "ownerId", parent: name, max: 12) try self.validate(self.ownerId, name: "ownerId", parent: name, min: 12) try self.validate(self.ownerId, name: "ownerId", parent: name, pattern: "^[0-9]+$") try self.validate(self.region, name: "region", parent: name, max: 30) try self.validate(self.region, name: "region", parent: name, min: 5) try self.validate(self.region, name: "region", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") } private enum CodingKeys: String, CodingKey { case domainName = "DomainName" case ownerId = "OwnerId" case region = "Region" } } public struct AcceptInboundConnectionRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "connectionId", location: .uri("ConnectionId")) ] /// The ID of the inbound connection you want to accept. public let connectionId: String public init(connectionId: String) { self.connectionId = connectionId } public func validate(name: String) throws { try self.validate(self.connectionId, name: "connectionId", parent: name, max: 256) try self.validate(self.connectionId, name: "connectionId", parent: name, min: 10) try self.validate(self.connectionId, name: "connectionId", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") } private enum CodingKeys: CodingKey {} } public struct AcceptInboundConnectionResponse: AWSDecodableShape { /// The InboundConnection of the accepted inbound connection. public let connection: InboundConnection? public init(connection: InboundConnection? = nil) { self.connection = connection } private enum CodingKeys: String, CodingKey { case connection = "Connection" } } public struct AccessPoliciesStatus: AWSDecodableShape { /// The access policy configured for the domain. Access policies can be resource-based, IP-based, or IAM-based. See Configuring access policiesfor more information. public let options: String /// The status of the access policy for the domain. See OptionStatus for the status information that's included. public let status: OptionStatus public init(options: String, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct AddTagsRequest: AWSEncodableShape { /// Specify the ARN of the domain you want to add tags to. public let arn: String /// List of Tag to add to the domain. public let tagList: [Tag] public init(arn: String, tagList: [Tag]) { self.arn = arn self.tagList = tagList } public func validate(name: String) throws { try self.validate(self.arn, name: "arn", parent: name, max: 2048) try self.validate(self.arn, name: "arn", parent: name, min: 20) try self.validate(self.arn, name: "arn", parent: name, pattern: ".*") try self.tagList.forEach { try $0.validate(name: "\(name).tagList[]") } } private enum CodingKeys: String, CodingKey { case arn = "ARN" case tagList = "TagList" } } public struct AdditionalLimit: AWSDecodableShape { /// Additional limit is specific to a given InstanceType and for each of its InstanceRole etc. Attributes and their details: MaximumNumberOfDataNodesSupported This attribute is present on the master node only to specify how much data nodes up to which given ESPartitionInstanceType can support as master node. MaximumNumberOfDataNodesWithoutMasterNode This attribute is present on data node only to specify how much data nodes of given ESPartitionInstanceType up to which you don't need any master nodes to govern them. public let limitName: String? /// Value for a given AdditionalLimit$LimitName . public let limitValues: [String]? public init(limitName: String? = nil, limitValues: [String]? = nil) { self.limitName = limitName self.limitValues = limitValues } private enum CodingKeys: String, CodingKey { case limitName = "LimitName" case limitValues = "LimitValues" } } public struct AdvancedOptionsStatus: AWSDecodableShape { /// The status of advanced options for the specified domain. public let options: [String: String] /// The OptionStatus for advanced options for the specified domain. public let status: OptionStatus public init(options: [String: String], status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct AdvancedSecurityOptions: AWSDecodableShape { /// True if advanced security is enabled. public let enabled: Bool? /// True if the internal user database is enabled. public let internalUserDatabaseEnabled: Bool? /// Describes the SAML application configured for a domain. public let samlOptions: SAMLOptionsOutput? public init(enabled: Bool? = nil, internalUserDatabaseEnabled: Bool? = nil, samlOptions: SAMLOptionsOutput? = nil) { self.enabled = enabled self.internalUserDatabaseEnabled = internalUserDatabaseEnabled self.samlOptions = samlOptions } private enum CodingKeys: String, CodingKey { case enabled = "Enabled" case internalUserDatabaseEnabled = "InternalUserDatabaseEnabled" case samlOptions = "SAMLOptions" } } public struct AdvancedSecurityOptionsInput: AWSEncodableShape { /// True if advanced security is enabled. public let enabled: Bool? /// True if the internal user database is enabled. public let internalUserDatabaseEnabled: Bool? /// Credentials for the master user: username and password, ARN, or both. public let masterUserOptions: MasterUserOptions? /// The SAML application configuration for the domain. public let samlOptions: SAMLOptionsInput? public init(enabled: Bool? = nil, internalUserDatabaseEnabled: Bool? = nil, masterUserOptions: MasterUserOptions? = nil, samlOptions: SAMLOptionsInput? = nil) { self.enabled = enabled self.internalUserDatabaseEnabled = internalUserDatabaseEnabled self.masterUserOptions = masterUserOptions self.samlOptions = samlOptions } public func validate(name: String) throws { try self.masterUserOptions?.validate(name: "\(name).masterUserOptions") try self.samlOptions?.validate(name: "\(name).samlOptions") } private enum CodingKeys: String, CodingKey { case enabled = "Enabled" case internalUserDatabaseEnabled = "InternalUserDatabaseEnabled" case masterUserOptions = "MasterUserOptions" case samlOptions = "SAMLOptions" } } public struct AdvancedSecurityOptionsStatus: AWSDecodableShape { /// Advanced security options for the specified domain. public let options: AdvancedSecurityOptions /// Status of the advanced security options for the specified domain. public let status: OptionStatus public init(options: AdvancedSecurityOptions, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct AssociatePackageRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri("DomainName")), AWSMemberEncoding(label: "packageID", location: .uri("PackageID")) ] /// The name of the domain to associate the package with. public let domainName: String /// Internal ID of the package to associate with a domain. Use DescribePackages to find this value. public let packageID: String public init(domainName: String, packageID: String) { self.domainName = domainName self.packageID = packageID } public func validate(name: String) throws { try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") } private enum CodingKeys: CodingKey {} } public struct AssociatePackageResponse: AWSDecodableShape { /// DomainPackageDetails public let domainPackageDetails: DomainPackageDetails? public init(domainPackageDetails: DomainPackageDetails? = nil) { self.domainPackageDetails = domainPackageDetails } private enum CodingKeys: String, CodingKey { case domainPackageDetails = "DomainPackageDetails" } } public struct AutoTune: AWSDecodableShape { /// Specifies details about the Auto-Tune action. See Auto-Tune for Amazon OpenSearch Service for more information. public let autoTuneDetails: AutoTuneDetails? /// Specifies the Auto-Tune type. Valid value is SCHEDULED_ACTION. public let autoTuneType: AutoTuneType? public init(autoTuneDetails: AutoTuneDetails? = nil, autoTuneType: AutoTuneType? = nil) { self.autoTuneDetails = autoTuneDetails self.autoTuneType = autoTuneType } private enum CodingKeys: String, CodingKey { case autoTuneDetails = "AutoTuneDetails" case autoTuneType = "AutoTuneType" } } public struct AutoTuneDetails: AWSDecodableShape { public let scheduledAutoTuneDetails: ScheduledAutoTuneDetails? public init(scheduledAutoTuneDetails: ScheduledAutoTuneDetails? = nil) { self.scheduledAutoTuneDetails = scheduledAutoTuneDetails } private enum CodingKeys: String, CodingKey { case scheduledAutoTuneDetails = "ScheduledAutoTuneDetails" } } public struct AutoTuneMaintenanceSchedule: AWSEncodableShape & AWSDecodableShape { /// A cron expression for a recurring maintenance schedule. See Auto-Tune for Amazon OpenSearch Service for more information. public let cronExpressionForRecurrence: String? /// Specifies maintenance schedule duration: duration value and duration unit. See Auto-Tune for Amazon OpenSearch Service for more information. public let duration: Duration? /// The timestamp at which the Auto-Tune maintenance schedule starts. public let startAt: Date? public init(cronExpressionForRecurrence: String? = nil, duration: Duration? = nil, startAt: Date? = nil) { self.cronExpressionForRecurrence = cronExpressionForRecurrence self.duration = duration self.startAt = startAt } public func validate(name: String) throws { try self.duration?.validate(name: "\(name).duration") } private enum CodingKeys: String, CodingKey { case cronExpressionForRecurrence = "CronExpressionForRecurrence" case duration = "Duration" case startAt = "StartAt" } } public struct AutoTuneOptions: AWSEncodableShape & AWSDecodableShape { /// The Auto-Tune desired state. Valid values are ENABLED and DISABLED. public let desiredState: AutoTuneDesiredState? /// A list of maintenance schedules. See Auto-Tune for Amazon OpenSearch Service for more information. public let maintenanceSchedules: [AutoTuneMaintenanceSchedule]? /// The rollback state while disabling Auto-Tune for the domain. Valid values are NO_ROLLBACK and DEFAULT_ROLLBACK. public let rollbackOnDisable: RollbackOnDisable? public init(desiredState: AutoTuneDesiredState? = nil, maintenanceSchedules: [AutoTuneMaintenanceSchedule]? = nil, rollbackOnDisable: RollbackOnDisable? = nil) { self.desiredState = desiredState self.maintenanceSchedules = maintenanceSchedules self.rollbackOnDisable = rollbackOnDisable } public func validate(name: String) throws { try self.maintenanceSchedules?.forEach { try $0.validate(name: "\(name).maintenanceSchedules[]") } try self.validate(self.maintenanceSchedules, name: "maintenanceSchedules", parent: name, max: 100) } private enum CodingKeys: String, CodingKey { case desiredState = "DesiredState" case maintenanceSchedules = "MaintenanceSchedules" case rollbackOnDisable = "RollbackOnDisable" } } public struct AutoTuneOptionsInput: AWSEncodableShape { /// The Auto-Tune desired state. Valid values are ENABLED and DISABLED. public let desiredState: AutoTuneDesiredState? /// A list of maintenance schedules. See Auto-Tune for Amazon OpenSearch Service for more information. public let maintenanceSchedules: [AutoTuneMaintenanceSchedule]? public init(desiredState: AutoTuneDesiredState? = nil, maintenanceSchedules: [AutoTuneMaintenanceSchedule]? = nil) { self.desiredState = desiredState self.maintenanceSchedules = maintenanceSchedules } public func validate(name: String) throws { try self.maintenanceSchedules?.forEach { try $0.validate(name: "\(name).maintenanceSchedules[]") } try self.validate(self.maintenanceSchedules, name: "maintenanceSchedules", parent: name, max: 100) } private enum CodingKeys: String, CodingKey { case desiredState = "DesiredState" case maintenanceSchedules = "MaintenanceSchedules" } } public struct AutoTuneOptionsOutput: AWSDecodableShape { /// The error message while enabling or disabling Auto-Tune. public let errorMessage: String? /// The AutoTuneState for the domain. public let state: AutoTuneState? public init(errorMessage: String? = nil, state: AutoTuneState? = nil) { self.errorMessage = errorMessage self.state = state } private enum CodingKeys: String, CodingKey { case errorMessage = "ErrorMessage" case state = "State" } } public struct AutoTuneOptionsStatus: AWSDecodableShape { /// Specifies Auto-Tune options for the domain. public let options: AutoTuneOptions? /// The status of the Auto-Tune options for the domain. public let status: AutoTuneStatus? public init(options: AutoTuneOptions? = nil, status: AutoTuneStatus? = nil) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct AutoTuneStatus: AWSDecodableShape { /// The timestamp of the Auto-Tune options creation date. public let creationDate: Date /// The error message while enabling or disabling Auto-Tune. public let errorMessage: String? /// Indicates whether the domain is being deleted. public let pendingDeletion: Bool? /// The AutoTuneState for the domain. public let state: AutoTuneState /// The timestamp of when the Auto-Tune options were last updated. public let updateDate: Date /// The latest version of the Auto-Tune options. public let updateVersion: Int? public init(creationDate: Date, errorMessage: String? = nil, pendingDeletion: Bool? = nil, state: AutoTuneState, updateDate: Date, updateVersion: Int? = nil) { self.creationDate = creationDate self.errorMessage = errorMessage self.pendingDeletion = pendingDeletion self.state = state self.updateDate = updateDate self.updateVersion = updateVersion } private enum CodingKeys: String, CodingKey { case creationDate = "CreationDate" case errorMessage = "ErrorMessage" case pendingDeletion = "PendingDeletion" case state = "State" case updateDate = "UpdateDate" case updateVersion = "UpdateVersion" } } public struct CancelServiceSoftwareUpdateRequest: AWSEncodableShape { /// The name of the domain that you want to stop the latest service software update on. public let domainName: String public init(domainName: String) { self.domainName = domainName } public func validate(name: String) throws { try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") } private enum CodingKeys: String, CodingKey { case domainName = "DomainName" } } public struct CancelServiceSoftwareUpdateResponse: AWSDecodableShape { /// The current status of the OpenSearch service software update. public let serviceSoftwareOptions: ServiceSoftwareOptions? public init(serviceSoftwareOptions: ServiceSoftwareOptions? = nil) { self.serviceSoftwareOptions = serviceSoftwareOptions } private enum CodingKeys: String, CodingKey { case serviceSoftwareOptions = "ServiceSoftwareOptions" } } public struct ClusterConfig: AWSEncodableShape & AWSDecodableShape { /// Specifies the ColdStorageOptions config for a Domain public let coldStorageOptions: ColdStorageOptions? /// Total number of dedicated master nodes, active and on standby, for the cluster. public let dedicatedMasterCount: Int? /// A boolean value to indicate whether a dedicated master node is enabled. See Dedicated master nodes in Amazon OpenSearch Service for more information. public let dedicatedMasterEnabled: Bool? /// The instance type for a dedicated master node. public let dedicatedMasterType: OpenSearchPartitionInstanceType? /// The number of instances in the specified domain cluster. public let instanceCount: Int? /// The instance type for an OpenSearch cluster. UltraWarm instance types are not supported for data instances. public let instanceType: OpenSearchPartitionInstanceType? /// The number of UltraWarm nodes in the cluster. public let warmCount: Int? /// True to enable UltraWarm storage. public let warmEnabled: Bool? /// The instance type for the OpenSearch cluster's warm nodes. public let warmType: OpenSearchWarmPartitionInstanceType? /// The zone awareness configuration for a domain when zone awareness is enabled. public let zoneAwarenessConfig: ZoneAwarenessConfig? /// A boolean value to indicate whether zone awareness is enabled. See Configuring a multi-AZ domain in Amazon OpenSearch Service for more information. public let zoneAwarenessEnabled: Bool? public init(coldStorageOptions: ColdStorageOptions? = nil, dedicatedMasterCount: Int? = nil, dedicatedMasterEnabled: Bool? = nil, dedicatedMasterType: OpenSearchPartitionInstanceType? = nil, instanceCount: Int? = nil, instanceType: OpenSearchPartitionInstanceType? = nil, warmCount: Int? = nil, warmEnabled: Bool? = nil, warmType: OpenSearchWarmPartitionInstanceType? = nil, zoneAwarenessConfig: ZoneAwarenessConfig? = nil, zoneAwarenessEnabled: Bool? = nil) { self.coldStorageOptions = coldStorageOptions self.dedicatedMasterCount = dedicatedMasterCount self.dedicatedMasterEnabled = dedicatedMasterEnabled self.dedicatedMasterType = dedicatedMasterType self.instanceCount = instanceCount self.instanceType = instanceType self.warmCount = warmCount self.warmEnabled = warmEnabled self.warmType = warmType self.zoneAwarenessConfig = zoneAwarenessConfig self.zoneAwarenessEnabled = zoneAwarenessEnabled } private enum CodingKeys: String, CodingKey { case coldStorageOptions = "ColdStorageOptions" case dedicatedMasterCount = "DedicatedMasterCount" case dedicatedMasterEnabled = "DedicatedMasterEnabled" case dedicatedMasterType = "DedicatedMasterType" case instanceCount = "InstanceCount" case instanceType = "InstanceType" case warmCount = "WarmCount" case warmEnabled = "WarmEnabled" case warmType = "WarmType" case zoneAwarenessConfig = "ZoneAwarenessConfig" case zoneAwarenessEnabled = "ZoneAwarenessEnabled" } } public struct ClusterConfigStatus: AWSDecodableShape { /// The cluster configuration for the specified domain. public let options: ClusterConfig /// The cluster configuration status for the specified domain. public let status: OptionStatus public init(options: ClusterConfig, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct CognitoOptions: AWSEncodableShape & AWSDecodableShape { /// The option to enable Cognito for OpenSearch Dashboards authentication. public let enabled: Bool? /// The Cognito identity pool ID for OpenSearch Dashboards authentication. public let identityPoolId: String? /// The role ARN that provides OpenSearch permissions for accessing Cognito resources. public let roleArn: String? /// The Cognito user pool ID for OpenSearch Dashboards authentication. public let userPoolId: String? public init(enabled: Bool? = nil, identityPoolId: String? = nil, roleArn: String? = nil, userPoolId: String? = nil) { self.enabled = enabled self.identityPoolId = identityPoolId self.roleArn = roleArn self.userPoolId = userPoolId } public func validate(name: String) throws { try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "^[\\w-]+:[0-9a-f-]+$") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 20) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:(aws|aws\\-cn|aws\\-us\\-gov|aws\\-iso|aws\\-iso\\-b):iam::[0-9]+:role\\/") try self.validate(self.userPoolId, name: "userPoolId", parent: name, max: 55) try self.validate(self.userPoolId, name: "userPoolId", parent: name, min: 1) try self.validate(self.userPoolId, name: "userPoolId", parent: name, pattern: "^[\\w-]+_[0-9a-zA-Z]+$") } private enum CodingKeys: String, CodingKey { case enabled = "Enabled" case identityPoolId = "IdentityPoolId" case roleArn = "RoleArn" case userPoolId = "UserPoolId" } } public struct CognitoOptionsStatus: AWSDecodableShape { /// Cognito options for the specified domain. public let options: CognitoOptions /// The status of the Cognito options for the specified domain. public let status: OptionStatus public init(options: CognitoOptions, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct ColdStorageOptions: AWSEncodableShape & AWSDecodableShape { /// Enable cold storage option. Accepted values true or false public let enabled: Bool public init(enabled: Bool) { self.enabled = enabled } private enum CodingKeys: String, CodingKey { case enabled = "Enabled" } } public struct CompatibleVersionsMap: AWSDecodableShape { /// The current version of OpenSearch a domain is on. public let sourceVersion: String? public let targetVersions: [String]? public init(sourceVersion: String? = nil, targetVersions: [String]? = nil) { self.sourceVersion = sourceVersion self.targetVersions = targetVersions } private enum CodingKeys: String, CodingKey { case sourceVersion = "SourceVersion" case targetVersions = "TargetVersions" } } public struct CreateDomainRequest: AWSEncodableShape { /// IAM access policy as a JSON-formatted string. public let accessPolicies: String? /// Option to allow references to indices in an HTTP request body. Must be false when configuring access to individual sub-resources. By default, the value is true. See Advanced cluster parameters for more information. public let advancedOptions: [String: String]? /// Specifies advanced security options. public let advancedSecurityOptions: AdvancedSecurityOptionsInput? /// Specifies Auto-Tune options. public let autoTuneOptions: AutoTuneOptionsInput? /// Configuration options for a domain. Specifies the instance type and number of instances in the domain. public let clusterConfig: ClusterConfig? /// Options to specify the Cognito user and identity pools for OpenSearch Dashboards authentication. For more information, see Configuring Amazon Cognito authentication for OpenSearch Dashboards. public let cognitoOptions: CognitoOptions? /// Options to specify configurations that will be applied to the domain endpoint. public let domainEndpointOptions: DomainEndpointOptions? /// The name of the Amazon OpenSearch Service domain you're creating. Domain names are unique across the domains owned by an account within an AWS region. Domain names must start with a lowercase letter and can contain the following characters: a-z (lowercase), 0-9, and - (hyphen). public let domainName: String /// Options to enable, disable, and specify the type and size of EBS storage volumes. public let ebsOptions: EBSOptions? /// Options for encryption of data at rest. public let encryptionAtRestOptions: EncryptionAtRestOptions? /// String of format Elasticsearch_X.Y or OpenSearch_X.Y to specify the engine version for the Amazon OpenSearch Service domain. For example, "OpenSearch_1.0" or "Elasticsearch_7.9". For more information, see Creating and managing Amazon OpenSearch Service domains . public let engineVersion: String? /// Map of LogType and LogPublishingOption, each containing options to publish a given type of OpenSearch log. public let logPublishingOptions: [LogType: LogPublishingOption]? /// Node-to-node encryption options. public let nodeToNodeEncryptionOptions: NodeToNodeEncryptionOptions? /// Option to set time, in UTC format, of the daily automated snapshot. Default value is 0 hours. public let snapshotOptions: SnapshotOptions? /// A list of Tag added during domain creation. public let tagList: [Tag]? /// Options to specify the subnets and security groups for a VPC endpoint. For more information, see Launching your Amazon OpenSearch Service domains using a VPC . public let vpcOptions: VPCOptions? public init(accessPolicies: String? = nil, advancedOptions: [String: String]? = nil, advancedSecurityOptions: AdvancedSecurityOptionsInput? = nil, autoTuneOptions: AutoTuneOptionsInput? = nil, clusterConfig: ClusterConfig? = nil, cognitoOptions: CognitoOptions? = nil, domainEndpointOptions: DomainEndpointOptions? = nil, domainName: String, ebsOptions: EBSOptions? = nil, encryptionAtRestOptions: EncryptionAtRestOptions? = nil, engineVersion: String? = nil, logPublishingOptions: [LogType: LogPublishingOption]? = nil, nodeToNodeEncryptionOptions: NodeToNodeEncryptionOptions? = nil, snapshotOptions: SnapshotOptions? = nil, tagList: [Tag]? = nil, vpcOptions: VPCOptions? = nil) { self.accessPolicies = accessPolicies self.advancedOptions = advancedOptions self.advancedSecurityOptions = advancedSecurityOptions self.autoTuneOptions = autoTuneOptions self.clusterConfig = clusterConfig self.cognitoOptions = cognitoOptions self.domainEndpointOptions = domainEndpointOptions self.domainName = domainName self.ebsOptions = ebsOptions self.encryptionAtRestOptions = encryptionAtRestOptions self.engineVersion = engineVersion self.logPublishingOptions = logPublishingOptions self.nodeToNodeEncryptionOptions = nodeToNodeEncryptionOptions self.snapshotOptions = snapshotOptions self.tagList = tagList self.vpcOptions = vpcOptions } public func validate(name: String) throws { try self.validate(self.accessPolicies, name: "accessPolicies", parent: name, max: 102_400) try self.validate(self.accessPolicies, name: "accessPolicies", parent: name, pattern: ".*") try self.advancedSecurityOptions?.validate(name: "\(name).advancedSecurityOptions") try self.autoTuneOptions?.validate(name: "\(name).autoTuneOptions") try self.cognitoOptions?.validate(name: "\(name).cognitoOptions") try self.domainEndpointOptions?.validate(name: "\(name).domainEndpointOptions") try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") try self.encryptionAtRestOptions?.validate(name: "\(name).encryptionAtRestOptions") try self.validate(self.engineVersion, name: "engineVersion", parent: name, max: 18) try self.validate(self.engineVersion, name: "engineVersion", parent: name, min: 14) try self.validate(self.engineVersion, name: "engineVersion", parent: name, pattern: "^Elasticsearch_[0-9]{1}\\.[0-9]{1,2}$|^OpenSearch_[0-9]{1,2}\\.[0-9]{1,2}$") try self.logPublishingOptions?.forEach { try $0.value.validate(name: "\(name).logPublishingOptions[\"\($0.key)\"]") } try self.tagList?.forEach { try $0.validate(name: "\(name).tagList[]") } } private enum CodingKeys: String, CodingKey { case accessPolicies = "AccessPolicies" case advancedOptions = "AdvancedOptions" case advancedSecurityOptions = "AdvancedSecurityOptions" case autoTuneOptions = "AutoTuneOptions" case clusterConfig = "ClusterConfig" case cognitoOptions = "CognitoOptions" case domainEndpointOptions = "DomainEndpointOptions" case domainName = "DomainName" case ebsOptions = "EBSOptions" case encryptionAtRestOptions = "EncryptionAtRestOptions" case engineVersion = "EngineVersion" case logPublishingOptions = "LogPublishingOptions" case nodeToNodeEncryptionOptions = "NodeToNodeEncryptionOptions" case snapshotOptions = "SnapshotOptions" case tagList = "TagList" case vpcOptions = "VPCOptions" } } public struct CreateDomainResponse: AWSDecodableShape { /// The status of the newly created domain. public let domainStatus: DomainStatus? public init(domainStatus: DomainStatus? = nil) { self.domainStatus = domainStatus } private enum CodingKeys: String, CodingKey { case domainStatus = "DomainStatus" } } public struct CreateOutboundConnectionRequest: AWSEncodableShape { /// The connection alias used used by the customer for this cross-cluster connection. public let connectionAlias: String /// The AWSDomainInformation for the local OpenSearch domain. public let localDomainInfo: DomainInformationContainer /// The AWSDomainInformation for the remote OpenSearch domain. public let remoteDomainInfo: DomainInformationContainer public init(connectionAlias: String, localDomainInfo: DomainInformationContainer, remoteDomainInfo: DomainInformationContainer) { self.connectionAlias = connectionAlias self.localDomainInfo = localDomainInfo self.remoteDomainInfo = remoteDomainInfo } public func validate(name: String) throws { try self.validate(self.connectionAlias, name: "connectionAlias", parent: name, max: 100) try self.validate(self.connectionAlias, name: "connectionAlias", parent: name, min: 2) try self.validate(self.connectionAlias, name: "connectionAlias", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9\\-\\_]+$") try self.localDomainInfo.validate(name: "\(name).localDomainInfo") try self.remoteDomainInfo.validate(name: "\(name).remoteDomainInfo") } private enum CodingKeys: String, CodingKey { case connectionAlias = "ConnectionAlias" case localDomainInfo = "LocalDomainInfo" case remoteDomainInfo = "RemoteDomainInfo" } } public struct CreateOutboundConnectionResponse: AWSDecodableShape { /// The connection alias provided during the create connection request. public let connectionAlias: String? /// The unique ID for the created outbound connection, which is used for subsequent operations on the connection. public let connectionId: String? /// The OutboundConnectionStatus for the newly created connection. public let connectionStatus: OutboundConnectionStatus? /// The AWSDomainInformation for the local OpenSearch domain. public let localDomainInfo: DomainInformationContainer? /// The AWSDomainInformation for the remote OpenSearch domain. public let remoteDomainInfo: DomainInformationContainer? public init(connectionAlias: String? = nil, connectionId: String? = nil, connectionStatus: OutboundConnectionStatus? = nil, localDomainInfo: DomainInformationContainer? = nil, remoteDomainInfo: DomainInformationContainer? = nil) { self.connectionAlias = connectionAlias self.connectionId = connectionId self.connectionStatus = connectionStatus self.localDomainInfo = localDomainInfo self.remoteDomainInfo = remoteDomainInfo } private enum CodingKeys: String, CodingKey { case connectionAlias = "ConnectionAlias" case connectionId = "ConnectionId" case connectionStatus = "ConnectionStatus" case localDomainInfo = "LocalDomainInfo" case remoteDomainInfo = "RemoteDomainInfo" } } public struct CreatePackageRequest: AWSEncodableShape { /// Description of the package. public let packageDescription: String? /// Unique identifier for the package. public let packageName: String /// The Amazon S3 location from which to import the package. public let packageSource: PackageSource /// Type of package. Currently supports only TXT-DICTIONARY. public let packageType: PackageType public init(packageDescription: String? = nil, packageName: String, packageSource: PackageSource, packageType: PackageType) { self.packageDescription = packageDescription self.packageName = packageName self.packageSource = packageSource self.packageType = packageType } public func validate(name: String) throws { try self.validate(self.packageDescription, name: "packageDescription", parent: name, max: 1024) try self.validate(self.packageName, name: "packageName", parent: name, max: 28) try self.validate(self.packageName, name: "packageName", parent: name, min: 3) try self.validate(self.packageName, name: "packageName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") try self.packageSource.validate(name: "\(name).packageSource") } private enum CodingKeys: String, CodingKey { case packageDescription = "PackageDescription" case packageName = "PackageName" case packageSource = "PackageSource" case packageType = "PackageType" } } public struct CreatePackageResponse: AWSDecodableShape { /// Information about the package. public let packageDetails: PackageDetails? public init(packageDetails: PackageDetails? = nil) { self.packageDetails = packageDetails } private enum CodingKeys: String, CodingKey { case packageDetails = "PackageDetails" } } public struct DeleteDomainRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri("DomainName")) ] /// The name of the domain you want to permanently delete. public let domainName: String public init(domainName: String) { self.domainName = domainName } public func validate(name: String) throws { try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") } private enum CodingKeys: CodingKey {} } public struct DeleteDomainResponse: AWSDecodableShape { /// The status of the domain being deleted. public let domainStatus: DomainStatus? public init(domainStatus: DomainStatus? = nil) { self.domainStatus = domainStatus } private enum CodingKeys: String, CodingKey { case domainStatus = "DomainStatus" } } public struct DeleteInboundConnectionRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "connectionId", location: .uri("ConnectionId")) ] /// The ID of the inbound connection to permanently delete. public let connectionId: String public init(connectionId: String) { self.connectionId = connectionId } public func validate(name: String) throws { try self.validate(self.connectionId, name: "connectionId", parent: name, max: 256) try self.validate(self.connectionId, name: "connectionId", parent: name, min: 10) try self.validate(self.connectionId, name: "connectionId", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") } private enum CodingKeys: CodingKey {} } public struct DeleteInboundConnectionResponse: AWSDecodableShape { /// The InboundConnection of the deleted inbound connection. public let connection: InboundConnection? public init(connection: InboundConnection? = nil) { self.connection = connection } private enum CodingKeys: String, CodingKey { case connection = "Connection" } } public struct DeleteOutboundConnectionRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "connectionId", location: .uri("ConnectionId")) ] /// The ID of the outbound connection you want to permanently delete. public let connectionId: String public init(connectionId: String) { self.connectionId = connectionId } public func validate(name: String) throws { try self.validate(self.connectionId, name: "connectionId", parent: name, max: 256) try self.validate(self.connectionId, name: "connectionId", parent: name, min: 10) try self.validate(self.connectionId, name: "connectionId", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") } private enum CodingKeys: CodingKey {} } public struct DeleteOutboundConnectionResponse: AWSDecodableShape { /// The OutboundConnection of the deleted outbound connection. public let connection: OutboundConnection? public init(connection: OutboundConnection? = nil) { self.connection = connection } private enum CodingKeys: String, CodingKey { case connection = "Connection" } } public struct DeletePackageRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "packageID", location: .uri("PackageID")) ] /// The internal ID of the package you want to delete. Use DescribePackages to find this value. public let packageID: String public init(packageID: String) { self.packageID = packageID } private enum CodingKeys: CodingKey {} } public struct DeletePackageResponse: AWSDecodableShape { /// PackageDetails public let packageDetails: PackageDetails? public init(packageDetails: PackageDetails? = nil) { self.packageDetails = packageDetails } private enum CodingKeys: String, CodingKey { case packageDetails = "PackageDetails" } } public struct DescribeDomainAutoTunesRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri("DomainName")) ] /// The domain name for which you want Auto-Tune action details. public let domainName: String /// Set this value to limit the number of results returned. If not specified, defaults to 100. public let maxResults: Int? /// NextToken is sent in case the earlier API call results contain the NextToken. Used for pagination. public let nextToken: String? public init(domainName: String, maxResults: Int? = nil, nextToken: String? = nil) { self.domainName = domainName self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: String, CodingKey { case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct DescribeDomainAutoTunesResponse: AWSDecodableShape { /// The list of setting adjustments that Auto-Tune has made to the domain. See Auto-Tune for Amazon OpenSearch Service for more information. public let autoTunes: [AutoTune]? /// An identifier to allow retrieval of paginated results. public let nextToken: String? public init(autoTunes: [AutoTune]? = nil, nextToken: String? = nil) { self.autoTunes = autoTunes self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case autoTunes = "AutoTunes" case nextToken = "NextToken" } } public struct DescribeDomainConfigRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri("DomainName")) ] /// The domain you want to get information about. public let domainName: String public init(domainName: String) { self.domainName = domainName } public func validate(name: String) throws { try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") } private enum CodingKeys: CodingKey {} } public struct DescribeDomainConfigResponse: AWSDecodableShape { /// The configuration information of the domain requested in the DescribeDomainConfig request. public let domainConfig: DomainConfig public init(domainConfig: DomainConfig) { self.domainConfig = domainConfig } private enum CodingKeys: String, CodingKey { case domainConfig = "DomainConfig" } } public struct DescribeDomainRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri("DomainName")) ] /// The name of the domain for which you want information. public let domainName: String public init(domainName: String) { self.domainName = domainName } public func validate(name: String) throws { try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") } private enum CodingKeys: CodingKey {} } public struct DescribeDomainResponse: AWSDecodableShape { /// The current status of the domain. public let domainStatus: DomainStatus public init(domainStatus: DomainStatus) { self.domainStatus = domainStatus } private enum CodingKeys: String, CodingKey { case domainStatus = "DomainStatus" } } public struct DescribeDomainsRequest: AWSEncodableShape { /// The domains for which you want information. public let domainNames: [String] public init(domainNames: [String]) { self.domainNames = domainNames } public func validate(name: String) throws { try self.domainNames.forEach { try validate($0, name: "domainNames[]", parent: name, max: 28) try validate($0, name: "domainNames[]", parent: name, min: 3) try validate($0, name: "domainNames[]", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") } } private enum CodingKeys: String, CodingKey { case domainNames = "DomainNames" } } public struct DescribeDomainsResponse: AWSDecodableShape { /// The status of the domains requested in the DescribeDomains request. public let domainStatusList: [DomainStatus] public init(domainStatusList: [DomainStatus]) { self.domainStatusList = domainStatusList } private enum CodingKeys: String, CodingKey { case domainStatusList = "DomainStatusList" } } public struct DescribeInboundConnectionsRequest: AWSEncodableShape { /// A list of filters used to match properties for inbound cross-cluster connections. Available Filter values are: connection-id local-domain-info.domain-name local-domain-info.owner-id local-domain-info.region remote-domain-info.domain-name public let filters: [Filter]? /// Set this value to limit the number of results returned. If not specified, defaults to 100. public let maxResults: Int? /// If more results are available and NextToken is present, make the next request to the same API with the received NextToken to paginate the remaining results. public let nextToken: String? public init(filters: [Filter]? = nil, maxResults: Int? = nil, nextToken: String? = nil) { self.filters = filters self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.filters?.forEach { try $0.validate(name: "\(name).filters[]") } try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: String, CodingKey { case filters = "Filters" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct DescribeInboundConnectionsResponse: AWSDecodableShape { /// A list of InboundConnection matching the specified filter criteria. public let connections: [InboundConnection]? /// If more results are available and NextToken is present, make the next request to the same API with the received NextToken to paginate the remaining results. public let nextToken: String? public init(connections: [InboundConnection]? = nil, nextToken: String? = nil) { self.connections = connections self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case connections = "Connections" case nextToken = "NextToken" } } public struct DescribeInstanceTypeLimitsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .querystring("domainName")), AWSMemberEncoding(label: "engineVersion", location: .uri("EngineVersion")), AWSMemberEncoding(label: "instanceType", location: .uri("InstanceType")) ] /// The name of the domain you want to modify. Only include this value if you're querying OpenSearch Limits for an existing domain. public let domainName: String? /// Version of OpenSearch for which Limits are needed. public let engineVersion: String /// The instance type for an OpenSearch cluster for which OpenSearch Limits are needed. public let instanceType: OpenSearchPartitionInstanceType public init(domainName: String? = nil, engineVersion: String, instanceType: OpenSearchPartitionInstanceType) { self.domainName = domainName self.engineVersion = engineVersion self.instanceType = instanceType } public func validate(name: String) throws { try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") try self.validate(self.engineVersion, name: "engineVersion", parent: name, max: 18) try self.validate(self.engineVersion, name: "engineVersion", parent: name, min: 14) try self.validate(self.engineVersion, name: "engineVersion", parent: name, pattern: "^Elasticsearch_[0-9]{1}\\.[0-9]{1,2}$|^OpenSearch_[0-9]{1,2}\\.[0-9]{1,2}$") } private enum CodingKeys: CodingKey {} } public struct DescribeInstanceTypeLimitsResponse: AWSDecodableShape { public let limitsByRole: [String: Limits]? public init(limitsByRole: [String: Limits]? = nil) { self.limitsByRole = limitsByRole } private enum CodingKeys: String, CodingKey { case limitsByRole = "LimitsByRole" } } public struct DescribeOutboundConnectionsRequest: AWSEncodableShape { /// A list of filters used to match properties for outbound cross-cluster connections. Available Filter names for this operation are: connection-id remote-domain-info.domain-name remote-domain-info.owner-id remote-domain-info.region local-domain-info.domain-name public let filters: [Filter]? /// Set this value to limit the number of results returned. If not specified, defaults to 100. public let maxResults: Int? /// NextToken is sent in case the earlier API call results contain the NextToken parameter. Used for pagination. public let nextToken: String? public init(filters: [Filter]? = nil, maxResults: Int? = nil, nextToken: String? = nil) { self.filters = filters self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.filters?.forEach { try $0.validate(name: "\(name).filters[]") } try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: String, CodingKey { case filters = "Filters" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct DescribeOutboundConnectionsResponse: AWSDecodableShape { /// A list of OutboundConnection matching the specified filter criteria. public let connections: [OutboundConnection]? /// If more results are available and NextToken is present, make the next request to the same API with the received NextToken to paginate the remaining results. public let nextToken: String? public init(connections: [OutboundConnection]? = nil, nextToken: String? = nil) { self.connections = connections self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case connections = "Connections" case nextToken = "NextToken" } } public struct DescribePackagesFilter: AWSEncodableShape { /// Any field from PackageDetails. public let name: DescribePackagesFilterName? /// A list of values for the specified field. public let value: [String]? public init(name: DescribePackagesFilterName? = nil, value: [String]? = nil) { self.name = name self.value = value } public func validate(name: String) throws { try self.value?.forEach { try validate($0, name: "value[]", parent: name, pattern: "^[0-9a-zA-Z\\*\\.\\\\/\\?-]*$") } } private enum CodingKeys: String, CodingKey { case name = "Name" case value = "Value" } } public struct DescribePackagesRequest: AWSEncodableShape { /// Only returns packages that match the DescribePackagesFilterList values. public let filters: [DescribePackagesFilter]? /// Limits results to a maximum number of packages. public let maxResults: Int? /// Used for pagination. Only necessary if a previous API call includes a non-null NextToken value. If provided, returns results for the next page. public let nextToken: String? public init(filters: [DescribePackagesFilter]? = nil, maxResults: Int? = nil, nextToken: String? = nil) { self.filters = filters self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.filters?.forEach { try $0.validate(name: "\(name).filters[]") } try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: String, CodingKey { case filters = "Filters" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct DescribePackagesResponse: AWSDecodableShape { public let nextToken: String? /// List of PackageDetails objects. public let packageDetailsList: [PackageDetails]? public init(nextToken: String? = nil, packageDetailsList: [PackageDetails]? = nil) { self.nextToken = nextToken self.packageDetailsList = packageDetailsList } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case packageDetailsList = "PackageDetailsList" } } public struct DescribeReservedInstanceOfferingsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring("maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring("nextToken")), AWSMemberEncoding(label: "reservedInstanceOfferingId", location: .querystring("offeringId")) ] /// Set this value to limit the number of results returned. If not specified, defaults to 100. public let maxResults: Int? /// Provides an identifier to allow retrieval of paginated results. public let nextToken: String? /// The offering identifier filter value. Use this parameter to show only the available offering that matches the specified reservation identifier. public let reservedInstanceOfferingId: String? public init(maxResults: Int? = nil, nextToken: String? = nil, reservedInstanceOfferingId: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken self.reservedInstanceOfferingId = reservedInstanceOfferingId } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.reservedInstanceOfferingId, name: "reservedInstanceOfferingId", parent: name, max: 36) try self.validate(self.reservedInstanceOfferingId, name: "reservedInstanceOfferingId", parent: name, min: 36) try self.validate(self.reservedInstanceOfferingId, name: "reservedInstanceOfferingId", parent: name, pattern: "^\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12}$") } private enum CodingKeys: CodingKey {} } public struct DescribeReservedInstanceOfferingsResponse: AWSDecodableShape { /// Provides an identifier to allow retrieval of paginated results. public let nextToken: String? /// List of reserved OpenSearch instance offerings public let reservedInstanceOfferings: [ReservedInstanceOffering]? public init(nextToken: String? = nil, reservedInstanceOfferings: [ReservedInstanceOffering]? = nil) { self.nextToken = nextToken self.reservedInstanceOfferings = reservedInstanceOfferings } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case reservedInstanceOfferings = "ReservedInstanceOfferings" } } public struct DescribeReservedInstancesRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring("maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring("nextToken")), AWSMemberEncoding(label: "reservedInstanceId", location: .querystring("reservationId")) ] /// Set this value to limit the number of results returned. If not specified, defaults to 100. public let maxResults: Int? /// Provides an identifier to allow retrieval of paginated results. public let nextToken: String? /// The reserved instance identifier filter value. Use this parameter to show only the reservation that matches the specified reserved OpenSearch instance ID. public let reservedInstanceId: String? public init(maxResults: Int? = nil, nextToken: String? = nil, reservedInstanceId: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken self.reservedInstanceId = reservedInstanceId } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.reservedInstanceId, name: "reservedInstanceId", parent: name, max: 36) try self.validate(self.reservedInstanceId, name: "reservedInstanceId", parent: name, min: 36) try self.validate(self.reservedInstanceId, name: "reservedInstanceId", parent: name, pattern: "^\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12}$") } private enum CodingKeys: CodingKey {} } public struct DescribeReservedInstancesResponse: AWSDecodableShape { /// Provides an identifier to allow retrieval of paginated results. public let nextToken: String? /// List of reserved OpenSearch instances. public let reservedInstances: [ReservedInstance]? public init(nextToken: String? = nil, reservedInstances: [ReservedInstance]? = nil) { self.nextToken = nextToken self.reservedInstances = reservedInstances } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case reservedInstances = "ReservedInstances" } } public struct DissociatePackageRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri("DomainName")), AWSMemberEncoding(label: "packageID", location: .uri("PackageID")) ] /// The name of the domain to associate the package with. public let domainName: String /// The internal ID of the package to associate with a domain. Use DescribePackages to find this value. public let packageID: String public init(domainName: String, packageID: String) { self.domainName = domainName self.packageID = packageID } public func validate(name: String) throws { try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") } private enum CodingKeys: CodingKey {} } public struct DissociatePackageResponse: AWSDecodableShape { /// DomainPackageDetails public let domainPackageDetails: DomainPackageDetails? public init(domainPackageDetails: DomainPackageDetails? = nil) { self.domainPackageDetails = domainPackageDetails } private enum CodingKeys: String, CodingKey { case domainPackageDetails = "DomainPackageDetails" } } public struct DomainConfig: AWSDecodableShape { /// IAM access policy as a JSON-formatted string. public let accessPolicies: AccessPoliciesStatus? /// The AdvancedOptions for the domain. See Advanced options for more information. public let advancedOptions: AdvancedOptionsStatus? /// Specifies AdvancedSecurityOptions for the domain. public let advancedSecurityOptions: AdvancedSecurityOptionsStatus? /// Specifies AutoTuneOptions for the domain. public let autoTuneOptions: AutoTuneOptionsStatus? /// The ClusterConfig for the domain. public let clusterConfig: ClusterConfigStatus? /// The CognitoOptions for the specified domain. For more information, see Configuring Amazon Cognito authentication for OpenSearch Dashboards. public let cognitoOptions: CognitoOptionsStatus? /// The DomainEndpointOptions for the domain. public let domainEndpointOptions: DomainEndpointOptionsStatus? /// The EBSOptions for the domain. public let ebsOptions: EBSOptionsStatus? /// The EncryptionAtRestOptions for the domain. public let encryptionAtRestOptions: EncryptionAtRestOptionsStatus? /// String of format Elasticsearch_X.Y or OpenSearch_X.Y to specify the engine version for the OpenSearch or Elasticsearch domain. public let engineVersion: VersionStatus? /// Log publishing options for the given domain. public let logPublishingOptions: LogPublishingOptionsStatus? /// The NodeToNodeEncryptionOptions for the domain. public let nodeToNodeEncryptionOptions: NodeToNodeEncryptionOptionsStatus? /// The SnapshotOptions for the domain. public let snapshotOptions: SnapshotOptionsStatus? /// The VPCOptions for the specified domain. For more information, see Launching your Amazon OpenSearch Service domains using a VPC. public let vpcOptions: VPCDerivedInfoStatus? public init(accessPolicies: AccessPoliciesStatus? = nil, advancedOptions: AdvancedOptionsStatus? = nil, advancedSecurityOptions: AdvancedSecurityOptionsStatus? = nil, autoTuneOptions: AutoTuneOptionsStatus? = nil, clusterConfig: ClusterConfigStatus? = nil, cognitoOptions: CognitoOptionsStatus? = nil, domainEndpointOptions: DomainEndpointOptionsStatus? = nil, ebsOptions: EBSOptionsStatus? = nil, encryptionAtRestOptions: EncryptionAtRestOptionsStatus? = nil, engineVersion: VersionStatus? = nil, logPublishingOptions: LogPublishingOptionsStatus? = nil, nodeToNodeEncryptionOptions: NodeToNodeEncryptionOptionsStatus? = nil, snapshotOptions: SnapshotOptionsStatus? = nil, vpcOptions: VPCDerivedInfoStatus? = nil) { self.accessPolicies = accessPolicies self.advancedOptions = advancedOptions self.advancedSecurityOptions = advancedSecurityOptions self.autoTuneOptions = autoTuneOptions self.clusterConfig = clusterConfig self.cognitoOptions = cognitoOptions self.domainEndpointOptions = domainEndpointOptions self.ebsOptions = ebsOptions self.encryptionAtRestOptions = encryptionAtRestOptions self.engineVersion = engineVersion self.logPublishingOptions = logPublishingOptions self.nodeToNodeEncryptionOptions = nodeToNodeEncryptionOptions self.snapshotOptions = snapshotOptions self.vpcOptions = vpcOptions } private enum CodingKeys: String, CodingKey { case accessPolicies = "AccessPolicies" case advancedOptions = "AdvancedOptions" case advancedSecurityOptions = "AdvancedSecurityOptions" case autoTuneOptions = "AutoTuneOptions" case clusterConfig = "ClusterConfig" case cognitoOptions = "CognitoOptions" case domainEndpointOptions = "DomainEndpointOptions" case ebsOptions = "EBSOptions" case encryptionAtRestOptions = "EncryptionAtRestOptions" case engineVersion = "EngineVersion" case logPublishingOptions = "LogPublishingOptions" case nodeToNodeEncryptionOptions = "NodeToNodeEncryptionOptions" case snapshotOptions = "SnapshotOptions" case vpcOptions = "VPCOptions" } } public struct DomainEndpointOptions: AWSEncodableShape & AWSDecodableShape { /// The fully qualified domain for your custom endpoint. public let customEndpoint: String? /// The ACM certificate ARN for your custom endpoint. public let customEndpointCertificateArn: String? /// Whether to enable a custom endpoint for the domain. public let customEndpointEnabled: Bool? /// Whether only HTTPS endpoint should be enabled for the domain. public let enforceHTTPS: Bool? /// Specify the TLS security policy to apply to the HTTPS endpoint of the domain. Can be one of the following values: Policy-Min-TLS-1-0-2019-07: TLS security policy which supports TLSv1.0 and higher. Policy-Min-TLS-1-2-2019-07: TLS security policy which supports only TLSv1.2 public let tlsSecurityPolicy: TLSSecurityPolicy? public init(customEndpoint: String? = nil, customEndpointCertificateArn: String? = nil, customEndpointEnabled: Bool? = nil, enforceHTTPS: Bool? = nil, tlsSecurityPolicy: TLSSecurityPolicy? = nil) { self.customEndpoint = customEndpoint self.customEndpointCertificateArn = customEndpointCertificateArn self.customEndpointEnabled = customEndpointEnabled self.enforceHTTPS = enforceHTTPS self.tlsSecurityPolicy = tlsSecurityPolicy } public func validate(name: String) throws { try self.validate(self.customEndpoint, name: "customEndpoint", parent: name, max: 255) try self.validate(self.customEndpoint, name: "customEndpoint", parent: name, min: 1) try self.validate(self.customEndpoint, name: "customEndpoint", parent: name, pattern: "^(((?!-)[A-Za-z0-9-]{0,62}[A-Za-z0-9])\\.)+((?!-)[A-Za-z0-9-]{1,62}[A-Za-z0-9])$") try self.validate(self.customEndpointCertificateArn, name: "customEndpointCertificateArn", parent: name, max: 2048) try self.validate(self.customEndpointCertificateArn, name: "customEndpointCertificateArn", parent: name, min: 20) try self.validate(self.customEndpointCertificateArn, name: "customEndpointCertificateArn", parent: name, pattern: ".*") } private enum CodingKeys: String, CodingKey { case customEndpoint = "CustomEndpoint" case customEndpointCertificateArn = "CustomEndpointCertificateArn" case customEndpointEnabled = "CustomEndpointEnabled" case enforceHTTPS = "EnforceHTTPS" case tlsSecurityPolicy = "TLSSecurityPolicy" } } public struct DomainEndpointOptionsStatus: AWSDecodableShape { /// Options to configure the endpoint for the domain. public let options: DomainEndpointOptions /// The status of the endpoint options for the domain. See OptionStatus for the status information that's included. public let status: OptionStatus public init(options: DomainEndpointOptions, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct DomainInfo: AWSDecodableShape { /// The DomainName. public let domainName: String? /// Specifies the EngineType of the domain. public let engineType: EngineType? public init(domainName: String? = nil, engineType: EngineType? = nil) { self.domainName = domainName self.engineType = engineType } private enum CodingKeys: String, CodingKey { case domainName = "DomainName" case engineType = "EngineType" } } public struct DomainInformationContainer: AWSEncodableShape & AWSDecodableShape { public let awsDomainInformation: AWSDomainInformation? public init(awsDomainInformation: AWSDomainInformation? = nil) { self.awsDomainInformation = awsDomainInformation } public func validate(name: String) throws { try self.awsDomainInformation?.validate(name: "\(name).awsDomainInformation") } private enum CodingKeys: String, CodingKey { case awsDomainInformation = "AWSDomainInformation" } } public struct DomainPackageDetails: AWSDecodableShape { /// The name of the domain you've associated a package with. public let domainName: String? /// State of the association. Values are ASSOCIATING, ASSOCIATION_FAILED, ACTIVE, DISSOCIATING, and DISSOCIATION_FAILED. public let domainPackageStatus: DomainPackageStatus? /// Additional information if the package is in an error state. Null otherwise. public let errorDetails: ErrorDetails? /// The timestamp of the most recent update to the package association status. public let lastUpdated: Date? /// The internal ID of the package. public let packageID: String? /// User-specified name of the package. public let packageName: String? /// Currently supports only TXT-DICTIONARY. public let packageType: PackageType? public let packageVersion: String? /// The relative path on Amazon OpenSearch Service nodes, which can be used as synonym_path when the package is a synonym file. public let referencePath: String? public init(domainName: String? = nil, domainPackageStatus: DomainPackageStatus? = nil, errorDetails: ErrorDetails? = nil, lastUpdated: Date? = nil, packageID: String? = nil, packageName: String? = nil, packageType: PackageType? = nil, packageVersion: String? = nil, referencePath: String? = nil) { self.domainName = domainName self.domainPackageStatus = domainPackageStatus self.errorDetails = errorDetails self.lastUpdated = lastUpdated self.packageID = packageID self.packageName = packageName self.packageType = packageType self.packageVersion = packageVersion self.referencePath = referencePath } private enum CodingKeys: String, CodingKey { case domainName = "DomainName" case domainPackageStatus = "DomainPackageStatus" case errorDetails = "ErrorDetails" case lastUpdated = "LastUpdated" case packageID = "PackageID" case packageName = "PackageName" case packageType = "PackageType" case packageVersion = "PackageVersion" case referencePath = "ReferencePath" } } public struct DomainStatus: AWSDecodableShape { /// IAM access policy as a JSON-formatted string. public let accessPolicies: String? /// The status of the AdvancedOptions. public let advancedOptions: [String: String]? /// The current status of the domain's advanced security options. public let advancedSecurityOptions: AdvancedSecurityOptions? /// The Amazon Resource Name (ARN) of a domain. See IAM identifiers in the AWS Identity and Access Management User Guide for more information. public let arn: String /// The current status of the domain's Auto-Tune options. public let autoTuneOptions: AutoTuneOptionsOutput? /// The type and number of instances in the domain. public let clusterConfig: ClusterConfig /// The CognitoOptions for the specified domain. For more information, see Configuring Amazon Cognito authentication for OpenSearch Dashboards. public let cognitoOptions: CognitoOptions? /// The domain creation status. True if the creation of a domain is complete. False if domain creation is still in progress. public let created: Bool? /// The domain deletion status. True if a delete request has been received for the domain but resource cleanup is still in progress. False if the domain has not been deleted. Once domain deletion is complete, the status of the domain is no longer returned. public let deleted: Bool? /// The current status of the domain's endpoint options. public let domainEndpointOptions: DomainEndpointOptions? /// The unique identifier for the specified domain. public let domainId: String /// The name of a domain. Domain names are unique across the domains owned by an account within an AWS region. Domain names start with a letter or number and can contain the following characters: a-z (lowercase), 0-9, and - (hyphen). public let domainName: String /// The EBSOptions for the specified domain. public let ebsOptions: EBSOptions? /// The status of the EncryptionAtRestOptions. public let encryptionAtRestOptions: EncryptionAtRestOptions? /// The domain endpoint that you use to submit index and search requests. public let endpoint: String? /// Map containing the domain endpoints used to submit index and search requests. Example key, value: 'vpc','vpc-endpoint-h2dsd34efgyghrtguk5gt6j2foh4.us-east-1.es.amazonaws.com'. public let endpoints: [String: String]? public let engineVersion: String? /// Log publishing options for the given domain. public let logPublishingOptions: [LogType: LogPublishingOption]? /// The status of the NodeToNodeEncryptionOptions. public let nodeToNodeEncryptionOptions: NodeToNodeEncryptionOptions? /// The status of the domain configuration. True if Amazon OpenSearch Service is processing configuration changes. False if the configuration is active. public let processing: Bool? /// The current status of the domain's service software. public let serviceSoftwareOptions: ServiceSoftwareOptions? /// The status of the SnapshotOptions. public let snapshotOptions: SnapshotOptions? /// The status of a domain version upgrade. True if Amazon OpenSearch Service is undergoing a version upgrade. False if the configuration is active. public let upgradeProcessing: Bool? /// The VPCOptions for the specified domain. For more information, see Launching your Amazon OpenSearch Service domains using a VPC. public let vpcOptions: VPCDerivedInfo? public init(accessPolicies: String? = nil, advancedOptions: [String: String]? = nil, advancedSecurityOptions: AdvancedSecurityOptions? = nil, arn: String, autoTuneOptions: AutoTuneOptionsOutput? = nil, clusterConfig: ClusterConfig, cognitoOptions: CognitoOptions? = nil, created: Bool? = nil, deleted: Bool? = nil, domainEndpointOptions: DomainEndpointOptions? = nil, domainId: String, domainName: String, ebsOptions: EBSOptions? = nil, encryptionAtRestOptions: EncryptionAtRestOptions? = nil, endpoint: String? = nil, endpoints: [String: String]? = nil, engineVersion: String? = nil, logPublishingOptions: [LogType: LogPublishingOption]? = nil, nodeToNodeEncryptionOptions: NodeToNodeEncryptionOptions? = nil, processing: Bool? = nil, serviceSoftwareOptions: ServiceSoftwareOptions? = nil, snapshotOptions: SnapshotOptions? = nil, upgradeProcessing: Bool? = nil, vpcOptions: VPCDerivedInfo? = nil) { self.accessPolicies = accessPolicies self.advancedOptions = advancedOptions self.advancedSecurityOptions = advancedSecurityOptions self.arn = arn self.autoTuneOptions = autoTuneOptions self.clusterConfig = clusterConfig self.cognitoOptions = cognitoOptions self.created = created self.deleted = deleted self.domainEndpointOptions = domainEndpointOptions self.domainId = domainId self.domainName = domainName self.ebsOptions = ebsOptions self.encryptionAtRestOptions = encryptionAtRestOptions self.endpoint = endpoint self.endpoints = endpoints self.engineVersion = engineVersion self.logPublishingOptions = logPublishingOptions self.nodeToNodeEncryptionOptions = nodeToNodeEncryptionOptions self.processing = processing self.serviceSoftwareOptions = serviceSoftwareOptions self.snapshotOptions = snapshotOptions self.upgradeProcessing = upgradeProcessing self.vpcOptions = vpcOptions } private enum CodingKeys: String, CodingKey { case accessPolicies = "AccessPolicies" case advancedOptions = "AdvancedOptions" case advancedSecurityOptions = "AdvancedSecurityOptions" case arn = "ARN" case autoTuneOptions = "AutoTuneOptions" case clusterConfig = "ClusterConfig" case cognitoOptions = "CognitoOptions" case created = "Created" case deleted = "Deleted" case domainEndpointOptions = "DomainEndpointOptions" case domainId = "DomainId" case domainName = "DomainName" case ebsOptions = "EBSOptions" case encryptionAtRestOptions = "EncryptionAtRestOptions" case endpoint = "Endpoint" case endpoints = "Endpoints" case engineVersion = "EngineVersion" case logPublishingOptions = "LogPublishingOptions" case nodeToNodeEncryptionOptions = "NodeToNodeEncryptionOptions" case processing = "Processing" case serviceSoftwareOptions = "ServiceSoftwareOptions" case snapshotOptions = "SnapshotOptions" case upgradeProcessing = "UpgradeProcessing" case vpcOptions = "VPCOptions" } } public struct DryRunResults: AWSDecodableShape { /// Specifies the way in which Amazon OpenSearch Service applies the update. Possible responses are Blue/Green (the update requires a blue/green deployment), DynamicUpdate (no blue/green required), Undetermined (the domain is undergoing an update and can't predict the deployment type; try again after the update is complete), and None (the request doesn't include any configuration changes). public let deploymentType: String? /// Contains an optional message associated with the DryRunResults. public let message: String? public init(deploymentType: String? = nil, message: String? = nil) { self.deploymentType = deploymentType self.message = message } private enum CodingKeys: String, CodingKey { case deploymentType = "DeploymentType" case message = "Message" } } public struct Duration: AWSEncodableShape & AWSDecodableShape { /// The unit of a maintenance schedule duration. Valid value is HOURS. See Auto-Tune for Amazon OpenSearch Service for more information. public let unit: TimeUnit? /// Integer to specify the value of a maintenance schedule duration. See Auto-Tune for Amazon OpenSearch Service for more information. public let value: Int64? public init(unit: TimeUnit? = nil, value: Int64? = nil) { self.unit = unit self.value = value } public func validate(name: String) throws { try self.validate(self.value, name: "value", parent: name, max: 24) try self.validate(self.value, name: "value", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case unit = "Unit" case value = "Value" } } public struct EBSOptions: AWSEncodableShape & AWSDecodableShape { /// Whether EBS-based storage is enabled. public let ebsEnabled: Bool? /// The IOPD for a Provisioned IOPS EBS volume (SSD). public let iops: Int? /// Integer to specify the size of an EBS volume. public let volumeSize: Int? /// The volume type for EBS-based storage. public let volumeType: VolumeType? public init(ebsEnabled: Bool? = nil, iops: Int? = nil, volumeSize: Int? = nil, volumeType: VolumeType? = nil) { self.ebsEnabled = ebsEnabled self.iops = iops self.volumeSize = volumeSize self.volumeType = volumeType } private enum CodingKeys: String, CodingKey { case ebsEnabled = "EBSEnabled" case iops = "Iops" case volumeSize = "VolumeSize" case volumeType = "VolumeType" } } public struct EBSOptionsStatus: AWSDecodableShape { /// The EBS options for the specified domain. public let options: EBSOptions /// The status of the EBS options for the specified domain. public let status: OptionStatus public init(options: EBSOptions, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct EncryptionAtRestOptions: AWSEncodableShape & AWSDecodableShape { /// The option to enable encryption at rest. public let enabled: Bool? /// The KMS key ID for encryption at rest options. public let kmsKeyId: String? public init(enabled: Bool? = nil, kmsKeyId: String? = nil) { self.enabled = enabled self.kmsKeyId = kmsKeyId } public func validate(name: String) throws { try self.validate(self.kmsKeyId, name: "kmsKeyId", parent: name, max: 500) try self.validate(self.kmsKeyId, name: "kmsKeyId", parent: name, min: 1) try self.validate(self.kmsKeyId, name: "kmsKeyId", parent: name, pattern: ".*") } private enum CodingKeys: String, CodingKey { case enabled = "Enabled" case kmsKeyId = "KmsKeyId" } } public struct EncryptionAtRestOptionsStatus: AWSDecodableShape { /// The Encryption At Rest options for the specified domain. public let options: EncryptionAtRestOptions /// The status of the Encryption At Rest options for the specified domain. public let status: OptionStatus public init(options: EncryptionAtRestOptions, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct ErrorDetails: AWSDecodableShape { public let errorMessage: String? public let errorType: String? public init(errorMessage: String? = nil, errorType: String? = nil) { self.errorMessage = errorMessage self.errorType = errorType } private enum CodingKeys: String, CodingKey { case errorMessage = "ErrorMessage" case errorType = "ErrorType" } } public struct Filter: AWSEncodableShape { /// The name of the filter. public let name: String? /// Contains one or more values for the filter. public let values: [String]? public init(name: String? = nil, values: [String]? = nil) { self.name = name self.values = values } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[a-zA-Z0-9\\-\\_\\.]+$") try self.values?.forEach { try validate($0, name: "values[]", parent: name, max: 100) try validate($0, name: "values[]", parent: name, min: 1) try validate($0, name: "values[]", parent: name, pattern: "^[a-zA-Z0-9\\-\\_\\.]+$") } try self.validate(self.values, name: "values", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case name = "Name" case values = "Values" } } public struct GetCompatibleVersionsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .querystring("domainName")) ] public let domainName: String? public init(domainName: String? = nil) { self.domainName = domainName } public func validate(name: String) throws { try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") } private enum CodingKeys: CodingKey {} } public struct GetCompatibleVersionsResponse: AWSDecodableShape { /// A map of compatible OpenSearch versions returned as part of the GetCompatibleVersions operation. public let compatibleVersions: [CompatibleVersionsMap]? public init(compatibleVersions: [CompatibleVersionsMap]? = nil) { self.compatibleVersions = compatibleVersions } private enum CodingKeys: String, CodingKey { case compatibleVersions = "CompatibleVersions" } } public struct GetPackageVersionHistoryRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring("maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring("nextToken")), AWSMemberEncoding(label: "packageID", location: .uri("PackageID")) ] /// Limits results to a maximum number of package versions. public let maxResults: Int? /// Used for pagination. Only necessary if a previous API call includes a non-null NextToken value. If provided, returns results for the next page. public let nextToken: String? /// Returns an audit history of package versions. public let packageID: String public init(maxResults: Int? = nil, nextToken: String? = nil, packageID: String) { self.maxResults = maxResults self.nextToken = nextToken self.packageID = packageID } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: CodingKey {} } public struct GetPackageVersionHistoryResponse: AWSDecodableShape { public let nextToken: String? public let packageID: String? /// List of PackageVersionHistory objects. public let packageVersionHistoryList: [PackageVersionHistory]? public init(nextToken: String? = nil, packageID: String? = nil, packageVersionHistoryList: [PackageVersionHistory]? = nil) { self.nextToken = nextToken self.packageID = packageID self.packageVersionHistoryList = packageVersionHistoryList } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case packageID = "PackageID" case packageVersionHistoryList = "PackageVersionHistoryList" } } public struct GetUpgradeHistoryRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri("DomainName")), AWSMemberEncoding(label: "maxResults", location: .querystring("maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring("nextToken")) ] public let domainName: String public let maxResults: Int? public let nextToken: String? public init(domainName: String, maxResults: Int? = nil, nextToken: String? = nil) { self.domainName = domainName self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: CodingKey {} } public struct GetUpgradeHistoryResponse: AWSDecodableShape { /// Pagination token that needs to be supplied to the next call to get the next page of results. public let nextToken: String? /// A list of UpgradeHistory objects corresponding to each upgrade or upgrade eligibility check performed on a domain returned as part of the GetUpgradeHistoryResponse object. public let upgradeHistories: [UpgradeHistory]? public init(nextToken: String? = nil, upgradeHistories: [UpgradeHistory]? = nil) { self.nextToken = nextToken self.upgradeHistories = upgradeHistories } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case upgradeHistories = "UpgradeHistories" } } public struct GetUpgradeStatusRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri("DomainName")) ] public let domainName: String public init(domainName: String) { self.domainName = domainName } public func validate(name: String) throws { try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") } private enum CodingKeys: CodingKey {} } public struct GetUpgradeStatusResponse: AWSDecodableShape { /// One of four statuses an upgrade have, returned as part of the GetUpgradeStatusResponse object. The status can take one of the following values: In Progress Succeeded Succeeded with Issues Failed public let stepStatus: UpgradeStatus? /// A string that briefly describes the update. public let upgradeName: String? /// One of three steps an upgrade or upgrade eligibility check goes through: PreUpgradeCheck Snapshot Upgrade public let upgradeStep: UpgradeStep? public init(stepStatus: UpgradeStatus? = nil, upgradeName: String? = nil, upgradeStep: UpgradeStep? = nil) { self.stepStatus = stepStatus self.upgradeName = upgradeName self.upgradeStep = upgradeStep } private enum CodingKeys: String, CodingKey { case stepStatus = "StepStatus" case upgradeName = "UpgradeName" case upgradeStep = "UpgradeStep" } } public struct InboundConnection: AWSDecodableShape { /// The connection ID for the inbound cross-cluster connection. public let connectionId: String? /// The InboundConnectionStatus for the outbound connection. public let connectionStatus: InboundConnectionStatus? /// The AWSDomainInformation for the local OpenSearch domain. public let localDomainInfo: DomainInformationContainer? /// The AWSDomainInformation for the remote OpenSearch domain. public let remoteDomainInfo: DomainInformationContainer? public init(connectionId: String? = nil, connectionStatus: InboundConnectionStatus? = nil, localDomainInfo: DomainInformationContainer? = nil, remoteDomainInfo: DomainInformationContainer? = nil) { self.connectionId = connectionId self.connectionStatus = connectionStatus self.localDomainInfo = localDomainInfo self.remoteDomainInfo = remoteDomainInfo } private enum CodingKeys: String, CodingKey { case connectionId = "ConnectionId" case connectionStatus = "ConnectionStatus" case localDomainInfo = "LocalDomainInfo" case remoteDomainInfo = "RemoteDomainInfo" } } public struct InboundConnectionStatus: AWSDecodableShape { /// Verbose information for the inbound connection status. public let message: String? /// The state code for the inbound connection. Can be one of the following: PENDING_ACCEPTANCE: Inbound connection is not yet accepted by the remote domain owner. APPROVED: Inbound connection is pending acceptance by the remote domain owner. PROVISIONING: Inbound connection provisioning is in progress. ACTIVE: Inbound connection is active and ready to use. REJECTING: Inbound connection rejection is in process. REJECTED: Inbound connection is rejected. DELETING: Inbound connection deletion is in progress. DELETED: Inbound connection is deleted and can no longer be used. public let statusCode: InboundConnectionStatusCode? public init(message: String? = nil, statusCode: InboundConnectionStatusCode? = nil) { self.message = message self.statusCode = statusCode } private enum CodingKeys: String, CodingKey { case message = "Message" case statusCode = "StatusCode" } } public struct InstanceCountLimits: AWSDecodableShape { public let maximumInstanceCount: Int? public let minimumInstanceCount: Int? public init(maximumInstanceCount: Int? = nil, minimumInstanceCount: Int? = nil) { self.maximumInstanceCount = maximumInstanceCount self.minimumInstanceCount = minimumInstanceCount } private enum CodingKeys: String, CodingKey { case maximumInstanceCount = "MaximumInstanceCount" case minimumInstanceCount = "MinimumInstanceCount" } } public struct InstanceLimits: AWSDecodableShape { public let instanceCountLimits: InstanceCountLimits? public init(instanceCountLimits: InstanceCountLimits? = nil) { self.instanceCountLimits = instanceCountLimits } private enum CodingKeys: String, CodingKey { case instanceCountLimits = "InstanceCountLimits" } } public struct InstanceTypeDetails: AWSDecodableShape { public let advancedSecurityEnabled: Bool? public let appLogsEnabled: Bool? public let cognitoEnabled: Bool? public let encryptionEnabled: Bool? public let instanceRole: [String]? public let instanceType: OpenSearchPartitionInstanceType? public let warmEnabled: Bool? public init(advancedSecurityEnabled: Bool? = nil, appLogsEnabled: Bool? = nil, cognitoEnabled: Bool? = nil, encryptionEnabled: Bool? = nil, instanceRole: [String]? = nil, instanceType: OpenSearchPartitionInstanceType? = nil, warmEnabled: Bool? = nil) { self.advancedSecurityEnabled = advancedSecurityEnabled self.appLogsEnabled = appLogsEnabled self.cognitoEnabled = cognitoEnabled self.encryptionEnabled = encryptionEnabled self.instanceRole = instanceRole self.instanceType = instanceType self.warmEnabled = warmEnabled } private enum CodingKeys: String, CodingKey { case advancedSecurityEnabled = "AdvancedSecurityEnabled" case appLogsEnabled = "AppLogsEnabled" case cognitoEnabled = "CognitoEnabled" case encryptionEnabled = "EncryptionEnabled" case instanceRole = "InstanceRole" case instanceType = "InstanceType" case warmEnabled = "WarmEnabled" } } public struct Limits: AWSDecodableShape { /// List of additional limits that are specific to a given InstanceType and for each of its InstanceRole . public let additionalLimits: [AdditionalLimit]? public let instanceLimits: InstanceLimits? /// Storage-related types and attributes that are available for a given InstanceType. public let storageTypes: [StorageType]? public init(additionalLimits: [AdditionalLimit]? = nil, instanceLimits: InstanceLimits? = nil, storageTypes: [StorageType]? = nil) { self.additionalLimits = additionalLimits self.instanceLimits = instanceLimits self.storageTypes = storageTypes } private enum CodingKeys: String, CodingKey { case additionalLimits = "AdditionalLimits" case instanceLimits = "InstanceLimits" case storageTypes = "StorageTypes" } } public struct ListDomainNamesRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "engineType", location: .querystring("engineType")) ] /// Optional parameter to filter the output by domain engine type. Acceptable values are 'Elasticsearch' and 'OpenSearch'. public let engineType: EngineType? public init(engineType: EngineType? = nil) { self.engineType = engineType } private enum CodingKeys: CodingKey {} } public struct ListDomainNamesResponse: AWSDecodableShape { /// List of domain names and respective engine types. public let domainNames: [DomainInfo]? public init(domainNames: [DomainInfo]? = nil) { self.domainNames = domainNames } private enum CodingKeys: String, CodingKey { case domainNames = "DomainNames" } } public struct ListDomainsForPackageRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring("maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring("nextToken")), AWSMemberEncoding(label: "packageID", location: .uri("PackageID")) ] /// Limits the results to a maximum number of domains. public let maxResults: Int? /// Used for pagination. Only necessary if a previous API call includes a non-null NextToken value. If provided, returns results for the next page. public let nextToken: String? /// The package for which to list associated domains. public let packageID: String public init(maxResults: Int? = nil, nextToken: String? = nil, packageID: String) { self.maxResults = maxResults self.nextToken = nextToken self.packageID = packageID } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: CodingKey {} } public struct ListDomainsForPackageResponse: AWSDecodableShape { /// List of DomainPackageDetails objects. public let domainPackageDetailsList: [DomainPackageDetails]? public let nextToken: String? public init(domainPackageDetailsList: [DomainPackageDetails]? = nil, nextToken: String? = nil) { self.domainPackageDetailsList = domainPackageDetailsList self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case domainPackageDetailsList = "DomainPackageDetailsList" case nextToken = "NextToken" } } public struct ListInstanceTypeDetailsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .querystring("domainName")), AWSMemberEncoding(label: "engineVersion", location: .uri("EngineVersion")), AWSMemberEncoding(label: "maxResults", location: .querystring("maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring("nextToken")) ] public let domainName: String? public let engineVersion: String public let maxResults: Int? public let nextToken: String? public init(domainName: String? = nil, engineVersion: String, maxResults: Int? = nil, nextToken: String? = nil) { self.domainName = domainName self.engineVersion = engineVersion self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") try self.validate(self.engineVersion, name: "engineVersion", parent: name, max: 18) try self.validate(self.engineVersion, name: "engineVersion", parent: name, min: 14) try self.validate(self.engineVersion, name: "engineVersion", parent: name, pattern: "^Elasticsearch_[0-9]{1}\\.[0-9]{1,2}$|^OpenSearch_[0-9]{1,2}\\.[0-9]{1,2}$") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: CodingKey {} } public struct ListInstanceTypeDetailsResponse: AWSDecodableShape { public let instanceTypeDetails: [InstanceTypeDetails]? public let nextToken: String? public init(instanceTypeDetails: [InstanceTypeDetails]? = nil, nextToken: String? = nil) { self.instanceTypeDetails = instanceTypeDetails self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case instanceTypeDetails = "InstanceTypeDetails" case nextToken = "NextToken" } } public struct ListPackagesForDomainRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri("DomainName")), AWSMemberEncoding(label: "maxResults", location: .querystring("maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring("nextToken")) ] /// The name of the domain for which you want to list associated packages. public let domainName: String /// Limits results to a maximum number of packages. public let maxResults: Int? /// Used for pagination. Only necessary if a previous API call includes a non-null NextToken value. If provided, returns results for the next page. public let nextToken: String? public init(domainName: String, maxResults: Int? = nil, nextToken: String? = nil) { self.domainName = domainName self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: CodingKey {} } public struct ListPackagesForDomainResponse: AWSDecodableShape { /// List of DomainPackageDetails objects. public let domainPackageDetailsList: [DomainPackageDetails]? /// Pagination token to supply to the next call to get the next page of results. public let nextToken: String? public init(domainPackageDetailsList: [DomainPackageDetails]? = nil, nextToken: String? = nil) { self.domainPackageDetailsList = domainPackageDetailsList self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case domainPackageDetailsList = "DomainPackageDetailsList" case nextToken = "NextToken" } } public struct ListTagsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "arn", location: .querystring("arn")) ] /// Specify the ARN of the domain that the tags you want to view are attached to. public let arn: String public init(arn: String) { self.arn = arn } public func validate(name: String) throws { try self.validate(self.arn, name: "arn", parent: name, max: 2048) try self.validate(self.arn, name: "arn", parent: name, min: 20) try self.validate(self.arn, name: "arn", parent: name, pattern: ".*") } private enum CodingKeys: CodingKey {} } public struct ListTagsResponse: AWSDecodableShape { /// List of Tag for the requested domain. public let tagList: [Tag]? public init(tagList: [Tag]? = nil) { self.tagList = tagList } private enum CodingKeys: String, CodingKey { case tagList = "TagList" } } public struct ListVersionsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring("maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring("nextToken")) ] /// Set this value to limit the number of results returned. Value must be greater than 10 or it won't be honored. public let maxResults: Int? 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 self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: CodingKey {} } public struct ListVersionsResponse: AWSDecodableShape { public let nextToken: String? public let versions: [String]? public init(nextToken: String? = nil, versions: [String]? = nil) { self.nextToken = nextToken self.versions = versions } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case versions = "Versions" } } public struct LogPublishingOption: AWSEncodableShape & AWSDecodableShape { public let cloudWatchLogsLogGroupArn: String? /// Whether the given log publishing option is enabled or not. public let enabled: Bool? public init(cloudWatchLogsLogGroupArn: String? = nil, enabled: Bool? = nil) { self.cloudWatchLogsLogGroupArn = cloudWatchLogsLogGroupArn self.enabled = enabled } public func validate(name: String) throws { try self.validate(self.cloudWatchLogsLogGroupArn, name: "cloudWatchLogsLogGroupArn", parent: name, max: 2048) try self.validate(self.cloudWatchLogsLogGroupArn, name: "cloudWatchLogsLogGroupArn", parent: name, min: 20) try self.validate(self.cloudWatchLogsLogGroupArn, name: "cloudWatchLogsLogGroupArn", parent: name, pattern: ".*") } private enum CodingKeys: String, CodingKey { case cloudWatchLogsLogGroupArn = "CloudWatchLogsLogGroupArn" case enabled = "Enabled" } } public struct LogPublishingOptionsStatus: AWSDecodableShape { /// The log publishing options configured for the domain. public let options: [LogType: LogPublishingOption]? /// The status of the log publishing options for the domain. See OptionStatus for the status information that's included. public let status: OptionStatus? public init(options: [LogType: LogPublishingOption]? = nil, status: OptionStatus? = nil) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct MasterUserOptions: AWSEncodableShape { /// ARN for the master user (if IAM is enabled). public let masterUserARN: String? /// The master user's username, which is stored in the Amazon OpenSearch Service domain's internal database. public let masterUserName: String? /// The master user's password, which is stored in the Amazon OpenSearch Service domain's internal database. public let masterUserPassword: String? public init(masterUserARN: String? = nil, masterUserName: String? = nil, masterUserPassword: String? = nil) { self.masterUserARN = masterUserARN self.masterUserName = masterUserName self.masterUserPassword = masterUserPassword } public func validate(name: String) throws { try self.validate(self.masterUserARN, name: "masterUserARN", parent: name, max: 2048) try self.validate(self.masterUserARN, name: "masterUserARN", parent: name, min: 20) try self.validate(self.masterUserARN, name: "masterUserARN", parent: name, pattern: ".*") try self.validate(self.masterUserName, name: "masterUserName", parent: name, max: 64) try self.validate(self.masterUserName, name: "masterUserName", parent: name, min: 1) try self.validate(self.masterUserName, name: "masterUserName", parent: name, pattern: ".*") try self.validate(self.masterUserPassword, name: "masterUserPassword", parent: name, max: 128) try self.validate(self.masterUserPassword, name: "masterUserPassword", parent: name, min: 8) try self.validate(self.masterUserPassword, name: "masterUserPassword", parent: name, pattern: ".*") } private enum CodingKeys: String, CodingKey { case masterUserARN = "MasterUserARN" case masterUserName = "MasterUserName" case masterUserPassword = "MasterUserPassword" } } public struct NodeToNodeEncryptionOptions: AWSEncodableShape & AWSDecodableShape { /// True to enable node-to-node encryption. public let enabled: Bool? public init(enabled: Bool? = nil) { self.enabled = enabled } private enum CodingKeys: String, CodingKey { case enabled = "Enabled" } } public struct NodeToNodeEncryptionOptionsStatus: AWSDecodableShape { /// The node-to-node encryption options for the specified domain. public let options: NodeToNodeEncryptionOptions /// The status of the node-to-node encryption options for the specified domain. public let status: OptionStatus public init(options: NodeToNodeEncryptionOptions, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct OptionStatus: AWSDecodableShape { /// The timestamp of when the entity was created. public let creationDate: Date /// Indicates whether the domain is being deleted. public let pendingDeletion: Bool? /// Provides the OptionState for the domain. public let state: OptionState /// The timestamp of the last time the entity was updated. public let updateDate: Date /// The latest version of the entity. public let updateVersion: Int? public init(creationDate: Date, pendingDeletion: Bool? = nil, state: OptionState, updateDate: Date, updateVersion: Int? = nil) { self.creationDate = creationDate self.pendingDeletion = pendingDeletion self.state = state self.updateDate = updateDate self.updateVersion = updateVersion } private enum CodingKeys: String, CodingKey { case creationDate = "CreationDate" case pendingDeletion = "PendingDeletion" case state = "State" case updateDate = "UpdateDate" case updateVersion = "UpdateVersion" } } public struct OutboundConnection: AWSDecodableShape { /// The connection alias for the outbound cross-cluster connection. public let connectionAlias: String? /// The connection ID for the outbound cross-cluster connection. public let connectionId: String? /// The OutboundConnectionStatus for the outbound connection. public let connectionStatus: OutboundConnectionStatus? /// The DomainInformation for the local OpenSearch domain. public let localDomainInfo: DomainInformationContainer? /// The DomainInformation for the remote OpenSearch domain. public let remoteDomainInfo: DomainInformationContainer? public init(connectionAlias: String? = nil, connectionId: String? = nil, connectionStatus: OutboundConnectionStatus? = nil, localDomainInfo: DomainInformationContainer? = nil, remoteDomainInfo: DomainInformationContainer? = nil) { self.connectionAlias = connectionAlias self.connectionId = connectionId self.connectionStatus = connectionStatus self.localDomainInfo = localDomainInfo self.remoteDomainInfo = remoteDomainInfo } private enum CodingKeys: String, CodingKey { case connectionAlias = "ConnectionAlias" case connectionId = "ConnectionId" case connectionStatus = "ConnectionStatus" case localDomainInfo = "LocalDomainInfo" case remoteDomainInfo = "RemoteDomainInfo" } } public struct OutboundConnectionStatus: AWSDecodableShape { /// Verbose information for the outbound connection status. public let message: String? /// The state code for the outbound connection. Can be one of the following: VALIDATING: The outbound connection request is being validated. VALIDATION_FAILED: Validation failed for the connection request. PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by the remote domain owner. APPROVED: Outbound connection has been approved by the remote domain owner for getting provisioned. PROVISIONING: Outbound connection request is in process. ACTIVE: Outbound connection is active and ready to use. REJECTING: Outbound connection rejection by remote domain owner is in progress. REJECTED: Outbound connection request is rejected by remote domain owner. DELETING: Outbound connection deletion is in progress. DELETED: Outbound connection is deleted and can no longer be used. public let statusCode: OutboundConnectionStatusCode? public init(message: String? = nil, statusCode: OutboundConnectionStatusCode? = nil) { self.message = message self.statusCode = statusCode } private enum CodingKeys: String, CodingKey { case message = "Message" case statusCode = "StatusCode" } } public struct PackageDetails: AWSDecodableShape { public let availablePackageVersion: String? /// The timestamp of when the package was created. public let createdAt: Date? /// Additional information if the package is in an error state. Null otherwise. public let errorDetails: ErrorDetails? public let lastUpdatedAt: Date? /// User-specified description of the package. public let packageDescription: String? /// Internal ID of the package. public let packageID: String? /// User-specified name of the package. public let packageName: String? /// Current state of the package. Values are COPYING, COPY_FAILED, AVAILABLE, DELETING, and DELETE_FAILED. public let packageStatus: PackageStatus? /// Currently supports only TXT-DICTIONARY. public let packageType: PackageType? public init(availablePackageVersion: String? = nil, createdAt: Date? = nil, errorDetails: ErrorDetails? = nil, lastUpdatedAt: Date? = nil, packageDescription: String? = nil, packageID: String? = nil, packageName: String? = nil, packageStatus: PackageStatus? = nil, packageType: PackageType? = nil) { self.availablePackageVersion = availablePackageVersion self.createdAt = createdAt self.errorDetails = errorDetails self.lastUpdatedAt = lastUpdatedAt self.packageDescription = packageDescription self.packageID = packageID self.packageName = packageName self.packageStatus = packageStatus self.packageType = packageType } private enum CodingKeys: String, CodingKey { case availablePackageVersion = "AvailablePackageVersion" case createdAt = "CreatedAt" case errorDetails = "ErrorDetails" case lastUpdatedAt = "LastUpdatedAt" case packageDescription = "PackageDescription" case packageID = "PackageID" case packageName = "PackageName" case packageStatus = "PackageStatus" case packageType = "PackageType" } } public struct PackageSource: AWSEncodableShape { /// The name of the Amazon S3 bucket containing the package. public let s3BucketName: String? /// Key (file name) of the package. public let s3Key: String? public init(s3BucketName: String? = nil, s3Key: String? = nil) { self.s3BucketName = s3BucketName self.s3Key = s3Key } public func validate(name: String) throws { try self.validate(self.s3BucketName, name: "s3BucketName", parent: name, max: 63) try self.validate(self.s3BucketName, name: "s3BucketName", parent: name, min: 3) try self.validate(self.s3Key, name: "s3Key", parent: name, max: 1024) try self.validate(self.s3Key, name: "s3Key", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case s3BucketName = "S3BucketName" case s3Key = "S3Key" } } public struct PackageVersionHistory: AWSDecodableShape { /// A message associated with the package version. public let commitMessage: String? /// The timestamp of when the package was created. public let createdAt: Date? /// The package version. public let packageVersion: String? public init(commitMessage: String? = nil, createdAt: Date? = nil, packageVersion: String? = nil) { self.commitMessage = commitMessage self.createdAt = createdAt self.packageVersion = packageVersion } private enum CodingKeys: String, CodingKey { case commitMessage = "CommitMessage" case createdAt = "CreatedAt" case packageVersion = "PackageVersion" } } public struct PurchaseReservedInstanceOfferingRequest: AWSEncodableShape { /// The number of OpenSearch instances to reserve. public let instanceCount: Int? /// A customer-specified identifier to track this reservation. public let reservationName: String /// The ID of the reserved OpenSearch instance offering to purchase. public let reservedInstanceOfferingId: String public init(instanceCount: Int? = nil, reservationName: String, reservedInstanceOfferingId: String) { self.instanceCount = instanceCount self.reservationName = reservationName self.reservedInstanceOfferingId = reservedInstanceOfferingId } public func validate(name: String) throws { try self.validate(self.instanceCount, name: "instanceCount", parent: name, min: 1) try self.validate(self.reservationName, name: "reservationName", parent: name, max: 64) try self.validate(self.reservationName, name: "reservationName", parent: name, min: 5) try self.validate(self.reservationName, name: "reservationName", parent: name, pattern: ".*") try self.validate(self.reservedInstanceOfferingId, name: "reservedInstanceOfferingId", parent: name, max: 36) try self.validate(self.reservedInstanceOfferingId, name: "reservedInstanceOfferingId", parent: name, min: 36) try self.validate(self.reservedInstanceOfferingId, name: "reservedInstanceOfferingId", parent: name, pattern: "^\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12}$") } private enum CodingKeys: String, CodingKey { case instanceCount = "InstanceCount" case reservationName = "ReservationName" case reservedInstanceOfferingId = "ReservedInstanceOfferingId" } } public struct PurchaseReservedInstanceOfferingResponse: AWSDecodableShape { /// The customer-specified identifier used to track this reservation. public let reservationName: String? /// Details of the reserved OpenSearch instance which was purchased. public let reservedInstanceId: String? public init(reservationName: String? = nil, reservedInstanceId: String? = nil) { self.reservationName = reservationName self.reservedInstanceId = reservedInstanceId } private enum CodingKeys: String, CodingKey { case reservationName = "ReservationName" case reservedInstanceId = "ReservedInstanceId" } } public struct RecurringCharge: AWSDecodableShape { /// The monetary amount of the recurring charge. public let recurringChargeAmount: Double? /// The frequency of the recurring charge. public let recurringChargeFrequency: String? public init(recurringChargeAmount: Double? = nil, recurringChargeFrequency: String? = nil) { self.recurringChargeAmount = recurringChargeAmount self.recurringChargeFrequency = recurringChargeFrequency } private enum CodingKeys: String, CodingKey { case recurringChargeAmount = "RecurringChargeAmount" case recurringChargeFrequency = "RecurringChargeFrequency" } } public struct RejectInboundConnectionRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "connectionId", location: .uri("ConnectionId")) ] /// The ID of the inbound connection to reject. public let connectionId: String public init(connectionId: String) { self.connectionId = connectionId } public func validate(name: String) throws { try self.validate(self.connectionId, name: "connectionId", parent: name, max: 256) try self.validate(self.connectionId, name: "connectionId", parent: name, min: 10) try self.validate(self.connectionId, name: "connectionId", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") } private enum CodingKeys: CodingKey {} } public struct RejectInboundConnectionResponse: AWSDecodableShape { /// The InboundConnection of the rejected inbound connection. public let connection: InboundConnection? public init(connection: InboundConnection? = nil) { self.connection = connection } private enum CodingKeys: String, CodingKey { case connection = "Connection" } } public struct RemoveTagsRequest: AWSEncodableShape { /// The ARN of the domain from which you want to delete the specified tags. public let arn: String /// The TagKey list you want to remove from the domain. public let tagKeys: [String] public init(arn: String, tagKeys: [String]) { self.arn = arn self.tagKeys = tagKeys } public func validate(name: String) throws { try self.validate(self.arn, name: "arn", parent: name, max: 2048) try self.validate(self.arn, name: "arn", parent: name, min: 20) try self.validate(self.arn, name: "arn", parent: name, pattern: ".*") } private enum CodingKeys: String, CodingKey { case arn = "ARN" case tagKeys = "TagKeys" } } public struct ReservedInstance: AWSDecodableShape { public let billingSubscriptionId: Int64? /// The currency code for the reserved OpenSearch instance offering. public let currencyCode: String? /// The duration, in seconds, for which the OpenSearch instance is reserved. public let duration: Int? /// The upfront fixed charge you will paid to purchase the specific reserved OpenSearch instance offering. public let fixedPrice: Double? /// The number of OpenSearch instances that have been reserved. public let instanceCount: Int? /// The OpenSearch instance type offered by the reserved instance offering. public let instanceType: OpenSearchPartitionInstanceType? /// The payment option as defined in the reserved OpenSearch instance offering. public let paymentOption: ReservedInstancePaymentOption? /// The charge to your account regardless of whether you are creating any domains using the instance offering. public let recurringCharges: [RecurringCharge]? /// The customer-specified identifier to track this reservation. public let reservationName: String? /// The unique identifier for the reservation. public let reservedInstanceId: String? /// The offering identifier. public let reservedInstanceOfferingId: String? /// The time the reservation started. public let startTime: Date? /// The state of the reserved OpenSearch instance. public let state: String? /// The rate you are charged for each hour for the domain that is using this reserved instance. public let usagePrice: Double? public init(billingSubscriptionId: Int64? = nil, currencyCode: String? = nil, duration: Int? = nil, fixedPrice: Double? = nil, instanceCount: Int? = nil, instanceType: OpenSearchPartitionInstanceType? = nil, paymentOption: ReservedInstancePaymentOption? = nil, recurringCharges: [RecurringCharge]? = nil, reservationName: String? = nil, reservedInstanceId: String? = nil, reservedInstanceOfferingId: String? = nil, startTime: Date? = nil, state: String? = nil, usagePrice: Double? = nil) { self.billingSubscriptionId = billingSubscriptionId self.currencyCode = currencyCode self.duration = duration self.fixedPrice = fixedPrice self.instanceCount = instanceCount self.instanceType = instanceType self.paymentOption = paymentOption self.recurringCharges = recurringCharges self.reservationName = reservationName self.reservedInstanceId = reservedInstanceId self.reservedInstanceOfferingId = reservedInstanceOfferingId self.startTime = startTime self.state = state self.usagePrice = usagePrice } private enum CodingKeys: String, CodingKey { case billingSubscriptionId = "BillingSubscriptionId" case currencyCode = "CurrencyCode" case duration = "Duration" case fixedPrice = "FixedPrice" case instanceCount = "InstanceCount" case instanceType = "InstanceType" case paymentOption = "PaymentOption" case recurringCharges = "RecurringCharges" case reservationName = "ReservationName" case reservedInstanceId = "ReservedInstanceId" case reservedInstanceOfferingId = "ReservedInstanceOfferingId" case startTime = "StartTime" case state = "State" case usagePrice = "UsagePrice" } } public struct ReservedInstanceOffering: AWSDecodableShape { /// The currency code for the reserved OpenSearch instance offering. public let currencyCode: String? /// The duration, in seconds, for which the offering will reserve the OpenSearch instance. public let duration: Int? /// The upfront fixed charge you will pay to purchase the specific reserved OpenSearch instance offering. public let fixedPrice: Double? /// The OpenSearch instance type offered by the reserved instance offering. public let instanceType: OpenSearchPartitionInstanceType? /// Payment option for the reserved OpenSearch instance offering public let paymentOption: ReservedInstancePaymentOption? /// The charge to your account regardless of whether you are creating any domains using the instance offering. public let recurringCharges: [RecurringCharge]? /// The OpenSearch reserved instance offering identifier. public let reservedInstanceOfferingId: String? /// The rate you are charged for each hour the domain that is using the offering is running. public let usagePrice: Double? public init(currencyCode: String? = nil, duration: Int? = nil, fixedPrice: Double? = nil, instanceType: OpenSearchPartitionInstanceType? = nil, paymentOption: ReservedInstancePaymentOption? = nil, recurringCharges: [RecurringCharge]? = nil, reservedInstanceOfferingId: String? = nil, usagePrice: Double? = nil) { self.currencyCode = currencyCode self.duration = duration self.fixedPrice = fixedPrice self.instanceType = instanceType self.paymentOption = paymentOption self.recurringCharges = recurringCharges self.reservedInstanceOfferingId = reservedInstanceOfferingId self.usagePrice = usagePrice } private enum CodingKeys: String, CodingKey { case currencyCode = "CurrencyCode" case duration = "Duration" case fixedPrice = "FixedPrice" case instanceType = "InstanceType" case paymentOption = "PaymentOption" case recurringCharges = "RecurringCharges" case reservedInstanceOfferingId = "ReservedInstanceOfferingId" case usagePrice = "UsagePrice" } } public struct SAMLIdp: AWSEncodableShape & AWSDecodableShape { /// The unique entity ID of the application in SAML identity provider. public let entityId: String /// The metadata of the SAML application in XML format. public let metadataContent: String public init(entityId: String, metadataContent: String) { self.entityId = entityId self.metadataContent = metadataContent } public func validate(name: String) throws { try self.validate(self.entityId, name: "entityId", parent: name, max: 512) try self.validate(self.entityId, name: "entityId", parent: name, min: 8) try self.validate(self.metadataContent, name: "metadataContent", parent: name, max: 1_048_576) try self.validate(self.metadataContent, name: "metadataContent", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case entityId = "EntityId" case metadataContent = "MetadataContent" } } public struct SAMLOptionsInput: AWSEncodableShape { /// True if SAML is enabled. public let enabled: Bool? /// The SAML Identity Provider's information. public let idp: SAMLIdp? /// The backend role that the SAML master user is mapped to. public let masterBackendRole: String? /// The SAML master username, which is stored in the Amazon OpenSearch Service domain's internal database. public let masterUserName: String? /// Element of the SAML assertion to use for backend roles. Default is roles. public let rolesKey: String? /// The duration, in minutes, after which a user session becomes inactive. Acceptable values are between 1 and 1440, and the default value is 60. public let sessionTimeoutMinutes: Int? /// Element of the SAML assertion to use for username. Default is NameID. public let subjectKey: String? public init(enabled: Bool? = nil, idp: SAMLIdp? = nil, masterBackendRole: String? = nil, masterUserName: String? = nil, rolesKey: String? = nil, sessionTimeoutMinutes: Int? = nil, subjectKey: String? = nil) { self.enabled = enabled self.idp = idp self.masterBackendRole = masterBackendRole self.masterUserName = masterUserName self.rolesKey = rolesKey self.sessionTimeoutMinutes = sessionTimeoutMinutes self.subjectKey = subjectKey } public func validate(name: String) throws { try self.idp?.validate(name: "\(name).idp") try self.validate(self.masterBackendRole, name: "masterBackendRole", parent: name, max: 256) try self.validate(self.masterBackendRole, name: "masterBackendRole", parent: name, min: 1) try self.validate(self.masterUserName, name: "masterUserName", parent: name, max: 64) try self.validate(self.masterUserName, name: "masterUserName", parent: name, min: 1) try self.validate(self.masterUserName, name: "masterUserName", parent: name, pattern: ".*") } private enum CodingKeys: String, CodingKey { case enabled = "Enabled" case idp = "Idp" case masterBackendRole = "MasterBackendRole" case masterUserName = "MasterUserName" case rolesKey = "RolesKey" case sessionTimeoutMinutes = "SessionTimeoutMinutes" case subjectKey = "SubjectKey" } } public struct SAMLOptionsOutput: AWSDecodableShape { /// True if SAML is enabled. public let enabled: Bool? /// Describes the SAML identity provider's information. public let idp: SAMLIdp? /// The key used for matching the SAML roles attribute. public let rolesKey: String? /// The duration, in minutes, after which a user session becomes inactive. public let sessionTimeoutMinutes: Int? /// The key used for matching the SAML subject attribute. public let subjectKey: String? public init(enabled: Bool? = nil, idp: SAMLIdp? = nil, rolesKey: String? = nil, sessionTimeoutMinutes: Int? = nil, subjectKey: String? = nil) { self.enabled = enabled self.idp = idp self.rolesKey = rolesKey self.sessionTimeoutMinutes = sessionTimeoutMinutes self.subjectKey = subjectKey } private enum CodingKeys: String, CodingKey { case enabled = "Enabled" case idp = "Idp" case rolesKey = "RolesKey" case sessionTimeoutMinutes = "SessionTimeoutMinutes" case subjectKey = "SubjectKey" } } public struct ScheduledAutoTuneDetails: AWSDecodableShape { /// The Auto-Tune action description. public let action: String? /// The Auto-Tune action type. Valid values are JVM_HEAP_SIZE_TUNING and JVM_YOUNG_GEN_TUNING. public let actionType: ScheduledAutoTuneActionType? /// The timestamp of the Auto-Tune action scheduled for the domain. public let date: Date? /// The Auto-Tune action severity. Valid values are LOW, MEDIUM, and HIGH. public let severity: ScheduledAutoTuneSeverityType? public init(action: String? = nil, actionType: ScheduledAutoTuneActionType? = nil, date: Date? = nil, severity: ScheduledAutoTuneSeverityType? = nil) { self.action = action self.actionType = actionType self.date = date self.severity = severity } private enum CodingKeys: String, CodingKey { case action = "Action" case actionType = "ActionType" case date = "Date" case severity = "Severity" } } public struct ServiceSoftwareOptions: AWSDecodableShape { /// The timestamp, in Epoch time, until which you can manually request a service software update. After this date, we automatically update your service software. public let automatedUpdateDate: Date? /// True if you're able to cancel your service software version update. False if you can't cancel your service software update. public let cancellable: Bool? /// The current service software version present on the domain. public let currentVersion: String? /// The description of the UpdateStatus. public let description: String? /// The new service software version if one is available. public let newVersion: String? /// True if a service software is never automatically updated. False if a service software is automatically updated after AutomatedUpdateDate. public let optionalDeployment: Bool? /// True if you're able to update your service software version. False if you can't update your service software version. public let updateAvailable: Bool? /// The status of your service software update. This field can take the following values: ELIGIBLE, PENDING_UPDATE, IN_PROGRESS, COMPLETED, and NOT_ELIGIBLE. public let updateStatus: DeploymentStatus? public init(automatedUpdateDate: Date? = nil, cancellable: Bool? = nil, currentVersion: String? = nil, description: String? = nil, newVersion: String? = nil, optionalDeployment: Bool? = nil, updateAvailable: Bool? = nil, updateStatus: DeploymentStatus? = nil) { self.automatedUpdateDate = automatedUpdateDate self.cancellable = cancellable self.currentVersion = currentVersion self.description = description self.newVersion = newVersion self.optionalDeployment = optionalDeployment self.updateAvailable = updateAvailable self.updateStatus = updateStatus } private enum CodingKeys: String, CodingKey { case automatedUpdateDate = "AutomatedUpdateDate" case cancellable = "Cancellable" case currentVersion = "CurrentVersion" case description = "Description" case newVersion = "NewVersion" case optionalDeployment = "OptionalDeployment" case updateAvailable = "UpdateAvailable" case updateStatus = "UpdateStatus" } } public struct SnapshotOptions: AWSEncodableShape & AWSDecodableShape { /// The time, in UTC format, when the service takes a daily automated snapshot of the specified domain. Default is 0 hours. public let automatedSnapshotStartHour: Int? public init(automatedSnapshotStartHour: Int? = nil) { self.automatedSnapshotStartHour = automatedSnapshotStartHour } private enum CodingKeys: String, CodingKey { case automatedSnapshotStartHour = "AutomatedSnapshotStartHour" } } public struct SnapshotOptionsStatus: AWSDecodableShape { /// The daily snapshot options specified for the domain. public let options: SnapshotOptions /// The status of a daily automated snapshot. public let status: OptionStatus public init(options: SnapshotOptions, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct StartServiceSoftwareUpdateRequest: AWSEncodableShape { /// The name of the domain that you want to update to the latest service software. public let domainName: String public init(domainName: String) { self.domainName = domainName } public func validate(name: String) throws { try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") } private enum CodingKeys: String, CodingKey { case domainName = "DomainName" } } public struct StartServiceSoftwareUpdateResponse: AWSDecodableShape { /// The current status of the OpenSearch service software update. public let serviceSoftwareOptions: ServiceSoftwareOptions? public init(serviceSoftwareOptions: ServiceSoftwareOptions? = nil) { self.serviceSoftwareOptions = serviceSoftwareOptions } private enum CodingKeys: String, CodingKey { case serviceSoftwareOptions = "ServiceSoftwareOptions" } } public struct StorageType: AWSDecodableShape { public let storageSubTypeName: String? /// Limits that are applicable for the given storage type. public let storageTypeLimits: [StorageTypeLimit]? public let storageTypeName: String? public init(storageSubTypeName: String? = nil, storageTypeLimits: [StorageTypeLimit]? = nil, storageTypeName: String? = nil) { self.storageSubTypeName = storageSubTypeName self.storageTypeLimits = storageTypeLimits self.storageTypeName = storageTypeName } private enum CodingKeys: String, CodingKey { case storageSubTypeName = "StorageSubTypeName" case storageTypeLimits = "StorageTypeLimits" case storageTypeName = "StorageTypeName" } } public struct StorageTypeLimit: AWSDecodableShape { /// Name of storage limits that are applicable for the given storage type. If StorageType is "ebs", the following storage options are applicable: MinimumVolumeSize Minimum amount of volume size that is applicable for the given storage type. Can be empty if not applicable. MaximumVolumeSize Maximum amount of volume size that is applicable for the given storage type. Can be empty if not applicable. MaximumIops Maximum amount of Iops that is applicable for given the storage type. Can be empty if not applicable. MinimumIops Minimum amount of Iops that is applicable for given the storage type. Can be empty if not applicable. public let limitName: String? /// Values for the StorageTypeLimit$LimitName . public let limitValues: [String]? public init(limitName: String? = nil, limitValues: [String]? = nil) { self.limitName = limitName self.limitValues = limitValues } private enum CodingKeys: String, CodingKey { case limitName = "LimitName" case limitValues = "LimitValues" } } public struct Tag: AWSEncodableShape & AWSDecodableShape { /// The TagKey, the name of the tag. Tag keys must be unique for the domain to which they are attached. public let key: String /// The TagValue, the value assigned to the corresponding tag key. Tag values can be null and don't have to be unique in a tag set. For example, you can have a key value pair in a tag set of project : Trinity and cost-center : Trinity public let value: String public init(key: String, value: String) { self.key = key self.value = value } public func validate(name: String) throws { try self.validate(self.key, name: "key", parent: name, max: 128) try self.validate(self.key, name: "key", parent: name, min: 1) try self.validate(self.key, name: "key", parent: name, pattern: ".*") try self.validate(self.value, name: "value", parent: name, max: 256) try self.validate(self.value, name: "value", parent: name, pattern: ".*") } private enum CodingKeys: String, CodingKey { case key = "Key" case value = "Value" } } public struct UpdateDomainConfigRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri("DomainName")) ] /// IAM access policy as a JSON-formatted string. public let accessPolicies: String? /// Modifies the advanced option to allow references to indices in an HTTP request body. Must be false when configuring access to individual sub-resources. By default, the value is true. See Advanced options for more information. public let advancedOptions: [String: String]? /// Specifies advanced security options. public let advancedSecurityOptions: AdvancedSecurityOptionsInput? /// Specifies Auto-Tune options. public let autoTuneOptions: AutoTuneOptions? /// The type and number of instances to instantiate for the domain cluster. public let clusterConfig: ClusterConfig? /// Options to specify the Cognito user and identity pools for OpenSearch Dashboards authentication. For more information, see Configuring Amazon Cognito authentication for OpenSearch Dashboards. public let cognitoOptions: CognitoOptions? /// Options to specify configuration that will be applied to the domain endpoint. public let domainEndpointOptions: DomainEndpointOptions? /// The name of the domain you're updating. public let domainName: String /// This flag, when set to True, specifies whether the UpdateDomain request should return the results of validation checks (DryRunResults) without actually applying the change. public let dryRun: Bool? /// Specify the type and size of the EBS volume to use. public let ebsOptions: EBSOptions? /// Specifies encryption of data at rest options. public let encryptionAtRestOptions: EncryptionAtRestOptions? /// Map of LogType and LogPublishingOption, each containing options to publish a given type of OpenSearch log. public let logPublishingOptions: [LogType: LogPublishingOption]? /// Specifies node-to-node encryption options. public let nodeToNodeEncryptionOptions: NodeToNodeEncryptionOptions? /// Option to set the time, in UTC format, for the daily automated snapshot. Default value is 0 hours. public let snapshotOptions: SnapshotOptions? /// Options to specify the subnets and security groups for the VPC endpoint. For more information, see Launching your Amazon OpenSearch Service domains using a VPC . public let vpcOptions: VPCOptions? public init(accessPolicies: String? = nil, advancedOptions: [String: String]? = nil, advancedSecurityOptions: AdvancedSecurityOptionsInput? = nil, autoTuneOptions: AutoTuneOptions? = nil, clusterConfig: ClusterConfig? = nil, cognitoOptions: CognitoOptions? = nil, domainEndpointOptions: DomainEndpointOptions? = nil, domainName: String, dryRun: Bool? = nil, ebsOptions: EBSOptions? = nil, encryptionAtRestOptions: EncryptionAtRestOptions? = nil, logPublishingOptions: [LogType: LogPublishingOption]? = nil, nodeToNodeEncryptionOptions: NodeToNodeEncryptionOptions? = nil, snapshotOptions: SnapshotOptions? = nil, vpcOptions: VPCOptions? = nil) { self.accessPolicies = accessPolicies self.advancedOptions = advancedOptions self.advancedSecurityOptions = advancedSecurityOptions self.autoTuneOptions = autoTuneOptions self.clusterConfig = clusterConfig self.cognitoOptions = cognitoOptions self.domainEndpointOptions = domainEndpointOptions self.domainName = domainName self.dryRun = dryRun self.ebsOptions = ebsOptions self.encryptionAtRestOptions = encryptionAtRestOptions self.logPublishingOptions = logPublishingOptions self.nodeToNodeEncryptionOptions = nodeToNodeEncryptionOptions self.snapshotOptions = snapshotOptions self.vpcOptions = vpcOptions } public func validate(name: String) throws { try self.validate(self.accessPolicies, name: "accessPolicies", parent: name, max: 102_400) try self.validate(self.accessPolicies, name: "accessPolicies", parent: name, pattern: ".*") try self.advancedSecurityOptions?.validate(name: "\(name).advancedSecurityOptions") try self.autoTuneOptions?.validate(name: "\(name).autoTuneOptions") try self.cognitoOptions?.validate(name: "\(name).cognitoOptions") try self.domainEndpointOptions?.validate(name: "\(name).domainEndpointOptions") try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") try self.encryptionAtRestOptions?.validate(name: "\(name).encryptionAtRestOptions") try self.logPublishingOptions?.forEach { try $0.value.validate(name: "\(name).logPublishingOptions[\"\($0.key)\"]") } } private enum CodingKeys: String, CodingKey { case accessPolicies = "AccessPolicies" case advancedOptions = "AdvancedOptions" case advancedSecurityOptions = "AdvancedSecurityOptions" case autoTuneOptions = "AutoTuneOptions" case clusterConfig = "ClusterConfig" case cognitoOptions = "CognitoOptions" case domainEndpointOptions = "DomainEndpointOptions" case dryRun = "DryRun" case ebsOptions = "EBSOptions" case encryptionAtRestOptions = "EncryptionAtRestOptions" case logPublishingOptions = "LogPublishingOptions" case nodeToNodeEncryptionOptions = "NodeToNodeEncryptionOptions" case snapshotOptions = "SnapshotOptions" case vpcOptions = "VPCOptions" } } public struct UpdateDomainConfigResponse: AWSDecodableShape { /// The status of the updated domain. public let domainConfig: DomainConfig /// Contains result of DryRun. public let dryRunResults: DryRunResults? public init(domainConfig: DomainConfig, dryRunResults: DryRunResults? = nil) { self.domainConfig = domainConfig self.dryRunResults = dryRunResults } private enum CodingKeys: String, CodingKey { case domainConfig = "DomainConfig" case dryRunResults = "DryRunResults" } } public struct UpdatePackageRequest: AWSEncodableShape { /// A commit message for the new version which is shown as part of GetPackageVersionHistoryResponse. public let commitMessage: String? /// A new description of the package. public let packageDescription: String? /// The unique identifier for the package. public let packageID: String public let packageSource: PackageSource public init(commitMessage: String? = nil, packageDescription: String? = nil, packageID: String, packageSource: PackageSource) { self.commitMessage = commitMessage self.packageDescription = packageDescription self.packageID = packageID self.packageSource = packageSource } public func validate(name: String) throws { try self.validate(self.commitMessage, name: "commitMessage", parent: name, max: 160) try self.validate(self.packageDescription, name: "packageDescription", parent: name, max: 1024) try self.packageSource.validate(name: "\(name).packageSource") } private enum CodingKeys: String, CodingKey { case commitMessage = "CommitMessage" case packageDescription = "PackageDescription" case packageID = "PackageID" case packageSource = "PackageSource" } } public struct UpdatePackageResponse: AWSDecodableShape { /// Information about the package. public let packageDetails: PackageDetails? public init(packageDetails: PackageDetails? = nil) { self.packageDetails = packageDetails } private enum CodingKeys: String, CodingKey { case packageDetails = "PackageDetails" } } public struct UpgradeDomainRequest: AWSEncodableShape { public let advancedOptions: [String: String]? public let domainName: String /// When true, indicates that an upgrade eligibility check needs to be performed. Does not actually perform the upgrade. public let performCheckOnly: Bool? /// The version of OpenSearch you intend to upgrade the domain to. public let targetVersion: String public init(advancedOptions: [String: String]? = nil, domainName: String, performCheckOnly: Bool? = nil, targetVersion: String) { self.advancedOptions = advancedOptions self.domainName = domainName self.performCheckOnly = performCheckOnly self.targetVersion = targetVersion } public func validate(name: String) throws { try self.validate(self.domainName, name: "domainName", parent: name, max: 28) try self.validate(self.domainName, name: "domainName", parent: name, min: 3) try self.validate(self.domainName, name: "domainName", parent: name, pattern: "^[a-z][a-z0-9\\-]+$") try self.validate(self.targetVersion, name: "targetVersion", parent: name, max: 18) try self.validate(self.targetVersion, name: "targetVersion", parent: name, min: 14) try self.validate(self.targetVersion, name: "targetVersion", parent: name, pattern: "^Elasticsearch_[0-9]{1}\\.[0-9]{1,2}$|^OpenSearch_[0-9]{1,2}\\.[0-9]{1,2}$") } private enum CodingKeys: String, CodingKey { case advancedOptions = "AdvancedOptions" case domainName = "DomainName" case performCheckOnly = "PerformCheckOnly" case targetVersion = "TargetVersion" } } public struct UpgradeDomainResponse: AWSDecodableShape { public let advancedOptions: [String: String]? public let domainName: String? /// When true, indicates that an upgrade eligibility check needs to be performed. Does not actually perform the upgrade. public let performCheckOnly: Bool? /// The version of OpenSearch that you intend to upgrade the domain to. public let targetVersion: String? public let upgradeId: String? public init(advancedOptions: [String: String]? = nil, domainName: String? = nil, performCheckOnly: Bool? = nil, targetVersion: String? = nil, upgradeId: String? = nil) { self.advancedOptions = advancedOptions self.domainName = domainName self.performCheckOnly = performCheckOnly self.targetVersion = targetVersion self.upgradeId = upgradeId } private enum CodingKeys: String, CodingKey { case advancedOptions = "AdvancedOptions" case domainName = "DomainName" case performCheckOnly = "PerformCheckOnly" case targetVersion = "TargetVersion" case upgradeId = "UpgradeId" } } public struct UpgradeHistory: AWSDecodableShape { /// UTC timestamp at which the upgrade API call was made in "yyyy-MM-ddTHH:mm:ssZ" format. public let startTimestamp: Date? /// A list of UpgradeStepItem s representing information about each step performed as part of a specific upgrade or upgrade eligibility check. public let stepsList: [UpgradeStepItem]? /// A string that briefly describes the upgrade. public let upgradeName: String? /// The current status of the upgrade. The status can take one of the following values: In Progress Succeeded Succeeded with Issues Failed public let upgradeStatus: UpgradeStatus? public init(startTimestamp: Date? = nil, stepsList: [UpgradeStepItem]? = nil, upgradeName: String? = nil, upgradeStatus: UpgradeStatus? = nil) { self.startTimestamp = startTimestamp self.stepsList = stepsList self.upgradeName = upgradeName self.upgradeStatus = upgradeStatus } private enum CodingKeys: String, CodingKey { case startTimestamp = "StartTimestamp" case stepsList = "StepsList" case upgradeName = "UpgradeName" case upgradeStatus = "UpgradeStatus" } } public struct UpgradeStepItem: AWSDecodableShape { /// A list of strings containing detailed information about the errors encountered in a particular step. public let issues: [String]? /// The floating point value representing the progress percentage of a particular step. public let progressPercent: Double? /// One of three steps an upgrade or upgrade eligibility check goes through: PreUpgradeCheck Snapshot Upgrade public let upgradeStep: UpgradeStep? /// The current status of the upgrade. The status can take one of the following values: In Progress Succeeded Succeeded with Issues Failed public let upgradeStepStatus: UpgradeStatus? public init(issues: [String]? = nil, progressPercent: Double? = nil, upgradeStep: UpgradeStep? = nil, upgradeStepStatus: UpgradeStatus? = nil) { self.issues = issues self.progressPercent = progressPercent self.upgradeStep = upgradeStep self.upgradeStepStatus = upgradeStepStatus } private enum CodingKeys: String, CodingKey { case issues = "Issues" case progressPercent = "ProgressPercent" case upgradeStep = "UpgradeStep" case upgradeStepStatus = "UpgradeStepStatus" } } public struct VPCDerivedInfo: AWSDecodableShape { /// The Availability Zones for the domain. Exists only if the domain was created with VPCOptions. public let availabilityZones: [String]? /// The security groups for the VPC endpoint. public let securityGroupIds: [String]? /// The subnets for the VPC endpoint. public let subnetIds: [String]? /// The VPC ID for the domain. Exists only if the domain was created with VPCOptions. public let vpcId: String? public init(availabilityZones: [String]? = nil, securityGroupIds: [String]? = nil, subnetIds: [String]? = nil, vpcId: String? = nil) { self.availabilityZones = availabilityZones self.securityGroupIds = securityGroupIds self.subnetIds = subnetIds self.vpcId = vpcId } private enum CodingKeys: String, CodingKey { case availabilityZones = "AvailabilityZones" case securityGroupIds = "SecurityGroupIds" case subnetIds = "SubnetIds" case vpcId = "VPCId" } } public struct VPCDerivedInfoStatus: AWSDecodableShape { /// The VPC options for the specified domain. public let options: VPCDerivedInfo /// The status of the VPC options for the specified domain. public let status: OptionStatus public init(options: VPCDerivedInfo, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct VPCOptions: AWSEncodableShape { /// The security groups for the VPC endpoint. public let securityGroupIds: [String]? /// The subnets for the VPC endpoint. public let subnetIds: [String]? public init(securityGroupIds: [String]? = nil, subnetIds: [String]? = nil) { self.securityGroupIds = securityGroupIds self.subnetIds = subnetIds } private enum CodingKeys: String, CodingKey { case securityGroupIds = "SecurityGroupIds" case subnetIds = "SubnetIds" } } public struct VersionStatus: AWSDecodableShape { /// The OpenSearch version for the specified OpenSearch domain. public let options: String /// The status of the OpenSearch version options for the specified OpenSearch domain. public let status: OptionStatus public init(options: String, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct ZoneAwarenessConfig: AWSEncodableShape & AWSDecodableShape { /// An integer value to indicate the number of availability zones for a domain when zone awareness is enabled. This should be equal to number of subnets if VPC endpoints is enabled. public let availabilityZoneCount: Int? public init(availabilityZoneCount: Int? = nil) { self.availabilityZoneCount = availabilityZoneCount } private enum CodingKeys: String, CodingKey { case availabilityZoneCount = "AvailabilityZoneCount" } } }
47.025228
908
0.659187
1ab37c2333b326ea56cfe5ae33204aa2fde677c7
3,019
// Copyright © 2019 hipolabs. All rights reserved. /// <warning> There are some additional steps to be completed in order to integrate `Zendesk Support`successfully. /// /// 1. Create a new "Run Scripts Phase" in your app's target's "Build Phases". /// This script should be the last step in your projects "Build Phases". Paste the following snippet into the script text field: /// /// `bash "${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}/SupportSDK.framework/strip-frameworks.sh"` /// /// Please ensure your project's VALID_ARCHS build setting does not contain i386 or x86_64 for release configuration. /// /// 2. The Support SDK uses the camera and photo library in iOS to allow end users to add image attachments to tickets /// If your app doesn't already request permissions for these features, update your info.plist file with a usage description for NSPhotoLibraryUsageDescription and NSCameraUsageDescription /// /// 3. To allow your users to attach files to support requests from their iCloud account, you must enable iCloud Documents in your apps Capabilities. (Optional) import Foundation import ZendeskCoreSDK import SupportSDK open class ZendeskHandler: DevToolConvertible { public let config: Config public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let appId = try container.decodeIfPresent(String.self, forKey: .appId) ?? "" let clientId = try container.decodeIfPresent(String.self, forKey: .clientId) ?? "" let deskUrl = try container.decodeIfPresent(String.self, forKey: .deskUrl) ?? "" config = Config(appId: appId, clientId: clientId, deskUrl: deskUrl) initialize() } public required init(nilLiteral: ()) { config = Config(appId: "", clientId: "", deskUrl: "") } open func makeScreen(_ identity: ZendeskIdentity?) -> UIViewController { let identity = Identity.createAnonymous(name: identity?.fullName, email: identity?.email) Zendesk.instance?.setIdentity(identity) return RequestUi.buildRequestUi(with: []) } } extension ZendeskHandler { private func initialize() { if config.isValid { Zendesk.initialize(appId: config.appId, clientId: config.clientId, zendeskUrl: config.deskUrl) Support.initialize(withZendesk: Zendesk.instance) debug { CoreLogger.logLevel = .debug CoreLogger.enabled = true } } } } extension ZendeskHandler { enum CodingKeys: String, CodingKey { case appId = "app_id" case clientId = "client_id" case deskUrl = "desk_url" } } extension ZendeskHandler { public struct Config { public let appId: String public let clientId: String public let deskUrl: String var isValid: Bool { return !appId.isEmpty && !clientId.isEmpty && !deskUrl.isEmpty } } }
36.817073
188
0.677708
dbd0103c48382b35998314a5ccde57eeb0709d23
2,000
// // ViewController.swift // Concentration // // Created by Kora on 10/02/2020. // Copyright © 2020 kbisewska. All rights reserved. // import UIKit class ViewController: UIViewController { private lazy var game = Concentration(numberOfPairsOfCards: (cardButtons.count + 1) / 2) private(set) var flipCount = 0 { didSet { flipCountLabel.text = "Flips: \(flipCount)" } } @IBOutlet private weak var flipCountLabel: UILabel! @IBOutlet private var cardButtons: [UIButton]! @IBAction private func touchCard(_ sender: UIButton) { flipCount += 1 if let cardNumber = cardButtons.firstIndex(of: sender) { game.chooseCard(at: cardNumber) updateViewFromModel() } } private func updateViewFromModel() { for index in cardButtons.indices { let button = cardButtons[index] let card = game.cards[index] if card.isFaceUp { button.setTitle(emoji(for: card), for: .normal) button.backgroundColor = .white } else { button.setTitle("", for: .normal) button.backgroundColor = card.isMatched ? .clear : .orange } } } private var emojiChoices = ["🦇", "😱", "🙀", "😈", "🎃", "👻", "🍭", "🍬", "🍎", "🕷"] private var emoji: [Card: String] = [:] private func emoji(for card: Card) -> String { if emoji[card] == nil, emojiChoices.count > 0 { emoji[card] = emojiChoices.remove(at: emojiChoices.count.arc4random) } return emoji[card] ?? "?" } override func viewDidLoad() { super.viewDidLoad() } } extension Int { var arc4random: Int { if self > 0 { return Int(arc4random_uniform(UInt32(self))) } else if self < 0 { return -Int(arc4random_uniform(UInt32(abs(self)))) } else { return 0 } } }
27.39726
92
0.5495
21c4ec2f76668a72410ec0bd6c25ffd7ea2091c1
1,264
// // EventStoreTestCase.swift // // // Created by Peter Eymann on 01/02/22. // import XCTest @testable import EventSourcing class EventStoreTestCase: XCTestCase { func testExample() throws { var registry = AggregateRegistry() registry.addAggregate(topic: "BankAccount", aggregateClass: BankAccount.self) InjectedValues[\.aggregateRegistry] = registry let mapper = Mapper() let recorder = InMemoryApplicationRecorder() let store = EventStore(recorder: recorder, mapper: mapper) let account = BankAccount.open(fullName: "Alice", emailAddress: "[email protected]") try account.appendTransaction(amount: 10.00) try account.appendTransaction(amount: 25.00) try account.appendTransaction(amount: 30.00) let pending = account.collect() try store.put(pending) let domainEvents = try store.get(originatorId: account.id) var newAccount: BankAccount? = nil for de in domainEvents { if let aggregateEvent = de as? AggregateEvent { try aggregateEvent.mutate(obj: &newAccount) } } XCTAssertEqual(newAccount!.id, account.id) XCTAssertEqual(newAccount!.state.balance, 65.00) } }
33.263158
92
0.65981
e56fb5d78facb3620fcabd229e2032eefc5feb44
567
// // CacheImage.swift // Fakestagram-Xcode10 // // Created by Alejandro Leon D4 on 11/9/19. // Copyright © 2019 unam. All rights reserved. // import Foundation import UIKit class CacheImage { static let shared = CacheImage() private var memCache = NSCache<NSString, UIImage>() func read(key: String) -> UIImage? { return memCache.object(forKey: key as NSString) } func write(key: String, value: UIImage?) { guard let value = value else { return } memCache.setObject(value, forKey: key as NSString) } }
22.68
58
0.647266
fc6980540bd9102ff366b3e4ae7327254a547329
5,241
// // TreeViewItem.swift // Graphnote // // Created by Hayden Pennington on 1/22/22. // import SwiftUI import CoreData import Combine enum TreeViewItemDimensions: CGFloat { case arrowWidthHeight = 16 case rowPadding = 4 } fileprivate let color = Color.gray enum FocusField: Hashable { case field } struct TreeViewItem: View, Identifiable { @Environment(\.colorScheme) var colorScheme @State private var toggle = false @State private var editable = false @FocusState private var focusedField: FocusField? let moc: NSManagedObjectContext let id: UUID let workspace: Binding<Workspace> var selected: Binding<DocumentIdentifier> let refresh: () -> () @ObservedObject private var viewModel: TreeViewItemViewModel init(moc: NSManagedObjectContext, id: UUID, workspace: Binding<Workspace>, selected: Binding<DocumentIdentifier>, refresh: @escaping () -> () ) { self.moc = moc self.id = id self.workspace = workspace self.selected = selected self.refresh = refresh self.viewModel = TreeViewItemViewModel(moc: moc, workspaceId: id) } func refreshDocuments() { self.viewModel.fetchDocuments(workspaceId: self.workspace.id.wrappedValue) } var body: some View { VStack(alignment: .leading) { ZStack(alignment: .leading) { EffectView() HStack { if toggle { ArrowView(color: color) .frame(width: TreeViewItemDimensions.arrowWidthHeight.rawValue, height: TreeViewItemDimensions.arrowWidthHeight.rawValue) .rotationEffect(Angle(degrees: 90)) .onTapGesture { toggle.toggle() } } else { ArrowView(color: color) .frame(width: TreeViewItemDimensions.arrowWidthHeight.rawValue, height: TreeViewItemDimensions.arrowWidthHeight.rawValue) .onTapGesture { toggle.toggle() } } if editable { CheckmarkView() .contentShape(Rectangle()) .padding(TreeViewItemDimensions.rowPadding.rawValue) .onTapGesture { editable = false } TextField("", text: workspace.title) .onSubmit { editable = false focusedField = nil } .focused($focusedField, equals: .field) .onAppear { if editable { focusedField = .field } } .padding(TreeViewItemDimensions.rowPadding.rawValue) } else { FileIconView() .padding(TreeViewItemDimensions.rowPadding.rawValue) Text(workspace.title.wrappedValue) .bold() .padding(TreeViewItemDimensions.rowPadding.rawValue) } } .padding(TreeViewItemDimensions.rowPadding.rawValue) } .contextMenu { Button { editable = true } label: { Text("Rename workspace") } Button { print("Delete workspace \(id)") viewModel.deleteWorkspace(workspaceId: id) refresh() } label: { Text("Delete workspace") } } } if toggle { VStack(alignment: .leading) { if let _ = viewModel.documents { ForEach(0..<viewModel.documents.count, id: \.self) { index in TreeViewSubItem(title: $viewModel.documents[index].title, documentId: viewModel.documents[index].id, workspaceId: viewModel.documents[index].workspace.id, selected: selected, deleteDocument: viewModel.deleteDocument, refresh: refreshDocuments) } } TreeViewAddView() .padding(.top, 10) .onTapGesture { if let newDocumentId = viewModel.addDocument(workspaceId: id) { selected.wrappedValue = DocumentIdentifier(workspaceId: workspace.id.wrappedValue, documentId: newDocumentId) } } } .padding([.leading], 40) } } }
34.032468
267
0.464224
defca59b70b393514c98857010d10eb7364297a4
1,166
// // Storyboard+SwizzlingSpec.swift // Swinject // // Created by Yoichi Tagaya on 10/10/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // import Quick import Nimble @testable import SwinjectStoryboard #if os(iOS) || os(tvOS) private typealias Storyboard = UIStoryboard private typealias Name = String #elseif os(OSX) private typealias Storyboard = NSStoryboard private typealias Name = NSStoryboard.Name #endif #if os(iOS) || os(OSX) || os(tvOS) class Storyboard_SwizzlingSpec: QuickSpec { override func spec() { let bundle = Bundle(for: Storyboard_SwizzlingSpec.self) it("instantiates SwinjectStoryboard when UIStoryboard/NSStoryboard is tried to be instantiated.") { let storyboard = Storyboard(name: Name("Animals"), bundle: bundle) expect(storyboard).to(beAnInstanceOf(SwinjectStoryboard.self)) } it("does not have infinite calls of swizzled methods to explicitly instantiate SwinjectStoryboard.") { let storyboard = SwinjectStoryboard.create(name: Name("Animals"), bundle: bundle) expect(storyboard).notTo(beNil()) } } } #endif
29.15
110
0.704117
6480c9fecf90af40bb25dbaebabe7cb46a69dc3e
11,638
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation public struct ASCBetaTester: AppStoreConnectBaseModel { public enum ASCType: String, Codable, Equatable, CaseIterable { case betaTesters = "betaTesters" } public var links: ASCResourceLinks public var _id: String public var type: ASCType public var attributes: Attributes? public var relationships: Relationships? public struct Attributes: AppStoreConnectBaseModel { public var email: String? public var firstName: String? public var inviteType: ASCBetaInviteType? public var lastName: String? public init( email: String? = nil, firstName: String? = nil, inviteType: ASCBetaInviteType? = nil, lastName: String? = nil ) { self.email = email self.firstName = firstName self.inviteType = inviteType self.lastName = lastName } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) email = try container.decodeIfPresent("email") firstName = try container.decodeIfPresent("firstName") inviteType = try container.decodeIfPresent("inviteType") lastName = try container.decodeIfPresent("lastName") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(email, forKey: "email") try container.encodeIfPresent(firstName, forKey: "firstName") try container.encodeIfPresent(inviteType, forKey: "inviteType") try container.encodeIfPresent(lastName, forKey: "lastName") } } public struct Relationships: AppStoreConnectBaseModel { public var apps: Apps? public var betaGroups: BetaGroups? public var builds: Builds? public struct Apps: AppStoreConnectBaseModel { public var data: [DataType]? public var links: Links? public var meta: ASCPagingInformation? public struct DataType: AppStoreConnectBaseModel { public enum ASCType: String, Codable, Equatable, CaseIterable { case apps = "apps" } public var _id: String public var type: ASCType public init(_id: String, type: ASCType) { self._id = _id self.type = type } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) _id = try container.decode("id") type = try container.decode("type") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(_id, forKey: "id") try container.encode(type, forKey: "type") } } public struct Links: AppStoreConnectBaseModel { public var related: String? public var _self: String? public init(related: String? = nil, _self: String? = nil) { self.related = related self._self = _self } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) related = try container.decodeIfPresent("related") _self = try container.decodeIfPresent("self") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(related, forKey: "related") try container.encodeIfPresent(_self, forKey: "self") } } public init(data: [DataType]? = nil, links: Links? = nil, meta: ASCPagingInformation? = nil) { self.data = data self.links = links self.meta = meta } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) data = try container.decodeArrayIfPresent("data") links = try container.decodeIfPresent("links") meta = try container.decodeIfPresent("meta") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(data, forKey: "data") try container.encodeIfPresent(links, forKey: "links") try container.encodeIfPresent(meta, forKey: "meta") } } public struct BetaGroups: AppStoreConnectBaseModel { public var data: [DataType]? public var links: Links? public var meta: ASCPagingInformation? public struct DataType: AppStoreConnectBaseModel { public enum ASCType: String, Codable, Equatable, CaseIterable { case betaGroups = "betaGroups" } public var _id: String public var type: ASCType public init(_id: String, type: ASCType) { self._id = _id self.type = type } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) _id = try container.decode("id") type = try container.decode("type") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(_id, forKey: "id") try container.encode(type, forKey: "type") } } public struct Links: AppStoreConnectBaseModel { public var related: String? public var _self: String? public init(related: String? = nil, _self: String? = nil) { self.related = related self._self = _self } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) related = try container.decodeIfPresent("related") _self = try container.decodeIfPresent("self") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(related, forKey: "related") try container.encodeIfPresent(_self, forKey: "self") } } public init(data: [DataType]? = nil, links: Links? = nil, meta: ASCPagingInformation? = nil) { self.data = data self.links = links self.meta = meta } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) data = try container.decodeArrayIfPresent("data") links = try container.decodeIfPresent("links") meta = try container.decodeIfPresent("meta") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(data, forKey: "data") try container.encodeIfPresent(links, forKey: "links") try container.encodeIfPresent(meta, forKey: "meta") } } public struct Builds: AppStoreConnectBaseModel { public var data: [DataType]? public var links: Links? public var meta: ASCPagingInformation? public struct DataType: AppStoreConnectBaseModel { public enum ASCType: String, Codable, Equatable, CaseIterable { case builds = "builds" } public var _id: String public var type: ASCType public init(_id: String, type: ASCType) { self._id = _id self.type = type } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) _id = try container.decode("id") type = try container.decode("type") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(_id, forKey: "id") try container.encode(type, forKey: "type") } } public struct Links: AppStoreConnectBaseModel { public var related: String? public var _self: String? public init(related: String? = nil, _self: String? = nil) { self.related = related self._self = _self } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) related = try container.decodeIfPresent("related") _self = try container.decodeIfPresent("self") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(related, forKey: "related") try container.encodeIfPresent(_self, forKey: "self") } } public init(data: [DataType]? = nil, links: Links? = nil, meta: ASCPagingInformation? = nil) { self.data = data self.links = links self.meta = meta } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) data = try container.decodeArrayIfPresent("data") links = try container.decodeIfPresent("links") meta = try container.decodeIfPresent("meta") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(data, forKey: "data") try container.encodeIfPresent(links, forKey: "links") try container.encodeIfPresent(meta, forKey: "meta") } } public init(apps: Apps? = nil, betaGroups: BetaGroups? = nil, builds: Builds? = nil) { self.apps = apps self.betaGroups = betaGroups self.builds = builds } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) apps = try container.decodeIfPresent("apps") betaGroups = try container.decodeIfPresent("betaGroups") builds = try container.decodeIfPresent("builds") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(apps, forKey: "apps") try container.encodeIfPresent(betaGroups, forKey: "betaGroups") try container.encodeIfPresent(builds, forKey: "builds") } } public init( links: ASCResourceLinks, _id: String, type: ASCType, attributes: Attributes? = nil, relationships: Relationships? = nil ) { self.links = links self._id = _id self.type = type self.attributes = attributes self.relationships = relationships } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) links = try container.decode("links") _id = try container.decode("id") type = try container.decode("type") attributes = try container.decodeIfPresent("attributes") relationships = try container.decodeIfPresent("relationships") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(links, forKey: "links") try container.encode(_id, forKey: "id") try container.encode(type, forKey: "type") try container.encodeIfPresent(attributes, forKey: "attributes") try container.encodeIfPresent(relationships, forKey: "relationships") } }
29.241206
100
0.647448
b9bf866041dbf90d8c49a30b4e03ad0a2b7a6f52
1,577
// // DocSpellError.swift // DocSpellFramework // // Copyright (c) 2020 Anodized Software, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // import Foundation public enum DocSpellError: Error, CustomStringConvertible { case docFailed case readFailed(path: String) public var description: String { switch self { case .docFailed: return "Unable to generate documentation" case .readFailed(let path): return "Unable to read file at \"\(path)\"" } } }
35.840909
79
0.717185
878e39b2d9900574a2e94c3728b7072a683679d7
2,577
// // Absolute+Day.swift // // // Created by Dave DeLong on 10/3/19. // import Foundation public extension Absolute where Smallest == Day, Largest == Era { func firstHour() -> Absolute<Hour> { return first() } func lastHour() -> Absolute<Hour> { return last() } func nthHour(_ ordinal: Int) throws -> Absolute<Hour> { return try nth(ordinal) } func hour(_ number: Int) -> Absolute<Hour>? { return numbered(number) } func hours() -> AbsoluteValueSequence<Hour> { return AbsoluteValueSequence(parent: self) } func minutes() -> AbsoluteValueSequence<Minute> { return AbsoluteValueSequence(parent: self) } func contains<U: LTOEHour>(_ value: Absolute<U>) -> Bool { return containsValue(value) } } public extension Absolute where Smallest: LTOEDay, Largest == Era { /// Returns `true` if the receiver is known to occur during the weekend. /// /// The definition of a "weekend" is supplied by the `Region`'s `Calendar`. var isWeekend: Bool { return calendar.isDateInWeekend(approximateMidPoint.date) } /// Returns `true` if the receiver is known to *not* occur during the weekend. /// /// The definition of a "weekend" is supplied by the `Region`'s `Calendar`. var isWeekday: Bool { return !isWeekend } /// Returns the numerical representation of the receiver's day of the week. /// /// For the Gregorian calendar, 1 = Sunday, 2 = Monday, ... 7 = Saturday var dayOfWeek: Int { return calendar.component(.weekday, from: approximateMidPoint.date) } /// Returns the day of the month on which the receiver occurs. /// /// For example, given a value that represents "Halloween" (October 31st) on the Gregorian calendar, /// this property returns "31". var dayOfMonth: Int { return day } /// Returns the day of the year on which the receiver occurs. /// /// For example, given a value that represents the first of February on the Gregorian calendar, /// this property returns "32". var dayOfYear: Int { return calendar.ordinality(of: .day, in: .year, for: approximateMidPoint.date)! } /// Returns the ordinal of the receiver's weekday within its month. /// /// For example, if the receiver falls on the second "Friday" of a month on the Gregorian calendar, /// then `dayOfWeek` returns `6` ("Friday"), and this property returns `2` (the second Friday). var dayOfWeekOrdinal: Int { return calendar.component(.weekdayOrdinal, from: approximateMidPoint.date) } }
39.646154
108
0.662786
03f3d99e3c6fcf7b32fcaed3efb5b32b8310f3b2
8,467
// // TextOutputCallback.swift // FRAuthTests // // Copyright (c) 2019 ForgeRock. All rights reserved. // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. // import XCTest class TextOutputCallbackTests: FRBaseTest { func test_01_CallbackConstruction_Successful() { // Given let message = "This is message" let messageType: String = "0" let jsonStr = """ { "type": "TextOutputCallback", "output": [{ "name": "message", "value": "\(message)" }, { "name": "messageType", "value": "\(messageType)" }] } """ let callbackResponse = self.parseStringToDictionary(jsonStr) // When do { let callback = try TextOutputCallback(json: callbackResponse) // Then XCTAssertEqual(callback.message, message) XCTAssertEqual(callback.messageType, MessageType.information) let requestPayload = callback.buildResponse() XCTAssertTrue(requestPayload == callbackResponse) } catch { XCTFail("Failed to construct callback: \(callbackResponse)") } } func test_02_CallbackConstruction_With_InputSection_Successful() { // Given let message = "This is message" let messageType: String = "0" let inputName = "IDToken1" let jsonStr = """ { "type": "TextOutputCallback", "output": [{ "name": "message", "value": "\(message)" }, { "name": "messageType", "value": "\(messageType)" }], "input": [{ "name": "\(inputName)", "value": "" }] } """ let callbackResponse = self.parseStringToDictionary(jsonStr) // When do { let callback = try TextOutputCallback(json: callbackResponse) // Then XCTAssertEqual(callback.message, message) XCTAssertEqual(callback.messageType.rawValue, Int(messageType)) let requestPayload = callback.buildResponse() XCTAssertTrue(requestPayload == callbackResponse) } catch { XCTFail("Failed to construct callback: \(callbackResponse)") } } func test_03_CallbackConstruction_Missing_Output() { // Given let jsonStr = """ { "type": "TextOutputCallback" } """ let callbackResponse = self.parseStringToDictionary(jsonStr) // Then do { let _ = try TextOutputCallback(json: callbackResponse) XCTFail("Failed to validate missing output section; succeed while expecting failure: \(callbackResponse)") } catch { } } func test_04_CallbackConstruction_Missing_Message() { // Given let messageType: String = "0" let jsonStr = """ { "type": "TextOutputCallback", "output": [{ "name": "messageType", "value": "\(messageType)" }] } """ let callbackResponse = self.parseStringToDictionary(jsonStr) // When do { let callback = try TextOutputCallback(json: callbackResponse) // Then XCTAssertEqual(callback.message.count, 0) XCTAssertEqual(callback.messageType.rawValue, Int(messageType)) let requestPayload = callback.buildResponse() XCTAssertTrue(requestPayload == callbackResponse) } catch { XCTFail("Failed to construct callback: \(callbackResponse)") } } func test_05_CallbackConstruction_Invalid_MessageType() { // Given let message = "This is message" let messageType: String = "5" let jsonStr = """ { "type": "TextOutputCallback", "output": [{ "name": "message", "value": "\(message)" }, { "name": "messageType", "value": "\(messageType)" }] } """ let callbackResponse = self.parseStringToDictionary(jsonStr) // When do { let callback = try TextOutputCallback(json: callbackResponse) // Then XCTAssertEqual(callback.message, message) XCTAssertEqual(callback.messageType, .unknown) let requestPayload = callback.buildResponse() XCTAssertTrue(requestPayload == callbackResponse) } catch { XCTFail("Failed to construct callback: \(callbackResponse)") } } func test_05_CallbackConstruction_Warning_MessageType() { // Given let message = "This is message" let messageType: String = "1" let jsonStr = """ { "type": "TextOutputCallback", "output": [{ "name": "message", "value": "\(message)" }, { "name": "messageType", "value": "\(messageType)" }] } """ let callbackResponse = self.parseStringToDictionary(jsonStr) // When do { let callback = try TextOutputCallback(json: callbackResponse) // Then XCTAssertEqual(callback.message, message) XCTAssertEqual(callback.messageType, MessageType.warning) let requestPayload = callback.buildResponse() XCTAssertTrue(requestPayload == callbackResponse) } catch { XCTFail("Failed to construct callback: \(callbackResponse)") } } func test_05_CallbackConstruction_Error_MessageType() { // Given let message = "This is message" let messageType: String = "2" let jsonStr = """ { "type": "TextOutputCallback", "output": [{ "name": "message", "value": "\(message)" }, { "name": "messageType", "value": "\(messageType)" }] } """ let callbackResponse = self.parseStringToDictionary(jsonStr) // When do { let callback = try TextOutputCallback(json: callbackResponse) // Then XCTAssertEqual(callback.message, message) XCTAssertEqual(callback.messageType, MessageType.error) let requestPayload = callback.buildResponse() XCTAssertTrue(requestPayload == callbackResponse) } catch { XCTFail("Failed to construct callback: \(callbackResponse)") } } } // Reference: https://stackoverflow.com/a/56773151 func areEqual (_ left: Any, _ right: Any) -> Bool { if type(of: left) == type(of: right) && String(describing: left) == String(describing: right) { return true } if let left = left as? [Any], let right = right as? [Any] { return left == right } if let left = left as? [AnyHashable: Any], let right = right as? [AnyHashable: Any] { return left == right } return false } extension Array where Element: Any { static func != (left: [Element], right: [Element]) -> Bool { return !(left == right) } static func == (left: [Element], right: [Element]) -> Bool { if left.count != right.count { return false } var right = right loop: for leftValue in left { for (rightIndex, rightValue) in right.enumerated() where areEqual(leftValue, rightValue) { right.remove(at: rightIndex) continue loop } return false } return true } } extension Dictionary where Value: Any { static func != (left: [Key : Value], right: [Key : Value]) -> Bool { return !(left == right) } static func == (left: [Key : Value], right: [Key : Value]) -> Bool { if left.count != right.count { return false } for element in left { guard let rightValue = right[element.key], areEqual(rightValue, element.value) else { return false } } return true } }
29.399306
118
0.533365
671a5a3c411c44220bde7193de3ae3b8e60ce249
33,749
// RUN: %target-swift-frontend -module-name builtins -assume-parsing-unqualified-ownership-sil -parse-stdlib -primary-file %s -emit-ir -o - -disable-objc-attr-requires-foundation-module | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime // REQUIRES: CPU=x86_64 import Swift // CHECK-DAG: [[REFCOUNT:%swift.refcounted.*]] = type // CHECK-DAG: [[X:%T8builtins1XC]] = type // CHECK-DAG: [[Y:%T8builtins1YC]] = type typealias Int = Builtin.Int32 typealias Bool = Builtin.Int1 // CHECK: call swiftcc void @swift_errorInMain( infix operator * infix operator / infix operator % infix operator + infix operator - infix operator << infix operator >> infix operator ... infix operator < infix operator <= infix operator > infix operator >= infix operator == infix operator != func * (lhs: Int, rhs: Int) -> Int { return Builtin.mul_Int32(lhs, rhs) // CHECK: mul i32 } func / (lhs: Int, rhs: Int) -> Int { return Builtin.sdiv_Int32(lhs, rhs) // CHECK: sdiv i32 } func % (lhs: Int, rhs: Int) -> Int { return Builtin.srem_Int32(lhs, rhs) // CHECK: srem i32 } func + (lhs: Int, rhs: Int) -> Int { return Builtin.add_Int32(lhs, rhs) // CHECK: add i32 } func - (lhs: Int, rhs: Int) -> Int { return Builtin.sub_Int32(lhs, rhs) // CHECK: sub i32 } // In C, 180 is <<, >> func < (lhs: Int, rhs: Int) -> Bool { return Builtin.cmp_slt_Int32(lhs, rhs) // CHECK: icmp slt i32 } func > (lhs: Int, rhs: Int) -> Bool { return Builtin.cmp_sgt_Int32(lhs, rhs) // CHECK: icmp sgt i32 } func <=(lhs: Int, rhs: Int) -> Bool { return Builtin.cmp_sle_Int32(lhs, rhs) // CHECK: icmp sle i32 } func >=(lhs: Int, rhs: Int) -> Bool { return Builtin.cmp_sge_Int32(lhs, rhs) // CHECK: icmp sge i32 } func ==(lhs: Int, rhs: Int) -> Bool { return Builtin.cmp_eq_Int32(lhs, rhs) // CHECK: icmp eq i32 } func !=(lhs: Int, rhs: Int) -> Bool { return Builtin.cmp_ne_Int32(lhs, rhs) // CHECK: icmp ne i32 } func gepRaw_test(_ ptr: Builtin.RawPointer, offset: Builtin.Int64) -> Builtin.RawPointer { return Builtin.gepRaw_Int64(ptr, offset) // CHECK: getelementptr inbounds i8, i8* } // CHECK: define hidden {{.*}}i64 @"$S8builtins9load_test{{[_0-9a-zA-Z]*}}F" func load_test(_ ptr: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[CASTPTR:%.*]] = bitcast i8* [[PTR:%.*]] to i64* // CHECK-NEXT: load i64, i64* [[CASTPTR]] // CHECK: ret return Builtin.load(ptr) } // CHECK: define hidden {{.*}}i64 @"$S8builtins13load_raw_test{{[_0-9a-zA-Z]*}}F" func load_raw_test(_ ptr: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[CASTPTR:%.*]] = bitcast i8* [[PTR:%.*]] to i64* // CHECK-NEXT: load i64, i64* [[CASTPTR]] // CHECK: ret return Builtin.loadRaw(ptr) } // CHECK: define hidden {{.*}}void @"$S8builtins11assign_test{{[_0-9a-zA-Z]*}}F" func assign_test(_ value: Builtin.Int64, ptr: Builtin.RawPointer) { Builtin.assign(value, ptr) // CHECK: ret } // CHECK: define hidden {{.*}}%swift.refcounted* @"$S8builtins16load_object_test{{[_0-9a-zA-Z]*}}F" func load_object_test(_ ptr: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[T0:%.*]] = load [[REFCOUNT]]*, [[REFCOUNT]]** // CHECK: call [[REFCOUNT]]* @swift_retain([[REFCOUNT]]* returned [[T0]]) // CHECK: ret [[REFCOUNT]]* [[T0]] return Builtin.load(ptr) } // CHECK: define hidden {{.*}}%swift.refcounted* @"$S8builtins20load_raw_object_test{{[_0-9a-zA-Z]*}}F" func load_raw_object_test(_ ptr: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[T0:%.*]] = load [[REFCOUNT]]*, [[REFCOUNT]]** // CHECK: call [[REFCOUNT]]* @swift_retain([[REFCOUNT]]* returned [[T0]]) // CHECK: ret [[REFCOUNT]]* [[T0]] return Builtin.loadRaw(ptr) } // CHECK: define hidden {{.*}}void @"$S8builtins18assign_object_test{{[_0-9a-zA-Z]*}}F" func assign_object_test(_ value: Builtin.NativeObject, ptr: Builtin.RawPointer) { Builtin.assign(value, ptr) } // CHECK: define hidden {{.*}}void @"$S8builtins16init_object_test{{[_0-9a-zA-Z]*}}F" func init_object_test(_ value: Builtin.NativeObject, ptr: Builtin.RawPointer) { // CHECK: [[DEST:%.*]] = bitcast i8* {{%.*}} to [[REFCOUNT]]** // CHECK-NEXT: call [[REFCOUNT]]* @swift_retain([[REFCOUNT]]* returned [[SRC:%.*]]) // CHECK-NEXT: store [[REFCOUNT]]* [[SRC]], [[REFCOUNT]]** [[DEST]] Builtin.initialize(value, ptr) } func cast_test(_ ptr: inout Builtin.RawPointer, i8: inout Builtin.Int8, i64: inout Builtin.Int64, f: inout Builtin.FPIEEE32, d: inout Builtin.FPIEEE64 ) { // CHECK: cast_test i8 = Builtin.trunc_Int64_Int8(i64) // CHECK: trunc i64 = Builtin.zext_Int8_Int64(i8) // CHECK: zext i64 = Builtin.sext_Int8_Int64(i8) // CHECK: sext i64 = Builtin.ptrtoint_Int64(ptr) // CHECK: ptrtoint ptr = Builtin.inttoptr_Int64(i64) // CHECK: inttoptr i64 = Builtin.fptoui_FPIEEE64_Int64(d) // CHECK: fptoui i64 = Builtin.fptosi_FPIEEE64_Int64(d) // CHECK: fptosi d = Builtin.uitofp_Int64_FPIEEE64(i64) // CHECK: uitofp d = Builtin.sitofp_Int64_FPIEEE64(i64) // CHECK: sitofp d = Builtin.fpext_FPIEEE32_FPIEEE64(f) // CHECK: fpext f = Builtin.fptrunc_FPIEEE64_FPIEEE32(d) // CHECK: fptrunc i64 = Builtin.bitcast_FPIEEE64_Int64(d) // CHECK: bitcast d = Builtin.bitcast_Int64_FPIEEE64(i64) // CHECK: bitcast } func intrinsic_test(_ i32: inout Builtin.Int32, i16: inout Builtin.Int16) { i32 = Builtin.int_bswap_Int32(i32) // CHECK: llvm.bswap.i32( i16 = Builtin.int_bswap_Int16(i16) // CHECK: llvm.bswap.i16( var x = Builtin.int_sadd_with_overflow_Int16(i16, i16) // CHECK: call { i16, i1 } @llvm.sadd.with.overflow.i16( Builtin.int_trap() // CHECK: llvm.trap() } // CHECK: define hidden {{.*}}void @"$S8builtins19sizeof_alignof_testyyF"() func sizeof_alignof_test() { // CHECK: store i64 4, i64* var xs = Builtin.sizeof(Int.self) // CHECK: store i64 4, i64* var xa = Builtin.alignof(Int.self) // CHECK: store i64 1, i64* var ys = Builtin.sizeof(Bool.self) // CHECK: store i64 1, i64* var ya = Builtin.alignof(Bool.self) } // CHECK: define hidden {{.*}}void @"$S8builtins27generic_sizeof_alignof_testyyxlF" func generic_sizeof_alignof_test<T>(_: T) { // CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 8 // CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]] // CHECK-NEXT: [[SIZE:%.*]] = ptrtoint i8* [[T1]] to i64 // CHECK-NEXT: store i64 [[SIZE]], i64* [[S:%.*]] var s = Builtin.sizeof(T.self) // CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 9 // CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]] // CHECK-NEXT: [[T2:%.*]] = ptrtoint i8* [[T1]] to i64 // CHECK-NEXT: [[T3:%.*]] = and i64 [[T2]], 65535 // CHECK-NEXT: [[ALIGN:%.*]] = add i64 [[T3]], 1 // CHECK-NEXT: store i64 [[ALIGN]], i64* [[A:%.*]] var a = Builtin.alignof(T.self) } // CHECK: define hidden {{.*}}void @"$S8builtins21generic_strideof_testyyxlF" func generic_strideof_test<T>(_: T) { // CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 10 // CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]] // CHECK-NEXT: [[STRIDE:%.*]] = ptrtoint i8* [[T1]] to i64 // CHECK-NEXT: store i64 [[STRIDE]], i64* [[S:%.*]] var s = Builtin.strideof(T.self) } class X {} class Y {} func move(_ ptr: Builtin.RawPointer) { var temp : Y = Builtin.take(ptr) // CHECK: define hidden {{.*}}void @"$S8builtins4move{{[_0-9a-zA-Z]*}}F" // CHECK: [[SRC:%.*]] = bitcast i8* {{%.*}} to [[Y]]** // CHECK-NEXT: [[VAL:%.*]] = load [[Y]]*, [[Y]]** [[SRC]] // CHECK-NEXT: store [[Y]]* [[VAL]], [[Y]]** {{%.*}} } func allocDealloc(_ size: Builtin.Word, align: Builtin.Word) { var ptr = Builtin.allocRaw(size, align) Builtin.deallocRaw(ptr, size, align) } func fence_test() { // CHECK: fence acquire Builtin.fence_acquire() // CHECK: fence syncscope("singlethread") acq_rel Builtin.fence_acqrel_singlethread() } func cmpxchg_test(_ ptr: Builtin.RawPointer, a: Builtin.Int32, b: Builtin.Int32) { // rdar://12939803 - ER: support atomic cmpxchg/xchg with pointers // CHECK: [[Z_RES:%.*]] = cmpxchg i32* {{.*}}, i32 {{.*}}, i32 {{.*}} acquire acquire // CHECK: [[Z_VAL:%.*]] = extractvalue { i32, i1 } [[Z_RES]], 0 // CHECK: [[Z_SUCCESS:%.*]] = extractvalue { i32, i1 } [[Z_RES]], 1 // CHECK: store i32 [[Z_VAL]], i32* {{.*}}, align 4 // CHECK: store i1 [[Z_SUCCESS]], i1* {{.*}}, align 1 var (z, zSuccess) = Builtin.cmpxchg_acquire_acquire_Int32(ptr, a, b) // CHECK: [[Y_RES:%.*]] = cmpxchg volatile i32* {{.*}}, i32 {{.*}}, i32 {{.*}} monotonic monotonic // CHECK: [[Y_VAL:%.*]] = extractvalue { i32, i1 } [[Y_RES]], 0 // CHECK: [[Y_SUCCESS:%.*]] = extractvalue { i32, i1 } [[Y_RES]], 1 // CHECK: store i32 [[Y_VAL]], i32* {{.*}}, align 4 // CHECK: store i1 [[Y_SUCCESS]], i1* {{.*}}, align 1 var (y, ySuccess) = Builtin.cmpxchg_monotonic_monotonic_volatile_Int32(ptr, a, b) // CHECK: [[X_RES:%.*]] = cmpxchg volatile i32* {{.*}}, i32 {{.*}}, i32 {{.*}} syncscope("singlethread") acquire monotonic // CHECK: [[X_VAL:%.*]] = extractvalue { i32, i1 } [[X_RES]], 0 // CHECK: [[X_SUCCESS:%.*]] = extractvalue { i32, i1 } [[X_RES]], 1 // CHECK: store i32 [[X_VAL]], i32* {{.*}}, align 4 // CHECK: store i1 [[X_SUCCESS]], i1* {{.*}}, align 1 var (x, xSuccess) = Builtin.cmpxchg_acquire_monotonic_volatile_singlethread_Int32(ptr, a, b) // CHECK: [[W_RES:%.*]] = cmpxchg volatile i64* {{.*}}, i64 {{.*}}, i64 {{.*}} seq_cst seq_cst // CHECK: [[W_VAL:%.*]] = extractvalue { i64, i1 } [[W_RES]], 0 // CHECK: [[W_SUCCESS:%.*]] = extractvalue { i64, i1 } [[W_RES]], 1 // CHECK: [[W_VAL_PTR:%.*]] = inttoptr i64 [[W_VAL]] to i8* // CHECK: store i8* [[W_VAL_PTR]], i8** {{.*}}, align 8 // CHECK: store i1 [[W_SUCCESS]], i1* {{.*}}, align 1 var (w, wSuccess) = Builtin.cmpxchg_seqcst_seqcst_volatile_singlethread_RawPointer(ptr, ptr, ptr) // CHECK: [[V_RES:%.*]] = cmpxchg weak volatile i64* {{.*}}, i64 {{.*}}, i64 {{.*}} seq_cst seq_cst // CHECK: [[V_VAL:%.*]] = extractvalue { i64, i1 } [[V_RES]], 0 // CHECK: [[V_SUCCESS:%.*]] = extractvalue { i64, i1 } [[V_RES]], 1 // CHECK: [[V_VAL_PTR:%.*]] = inttoptr i64 [[V_VAL]] to i8* // CHECK: store i8* [[V_VAL_PTR]], i8** {{.*}}, align 8 // CHECK: store i1 [[V_SUCCESS]], i1* {{.*}}, align 1 var (v, vSuccess) = Builtin.cmpxchg_seqcst_seqcst_weak_volatile_singlethread_RawPointer(ptr, ptr, ptr) } func atomicrmw_test(_ ptr: Builtin.RawPointer, a: Builtin.Int32, ptr2: Builtin.RawPointer) { // CHECK: atomicrmw add i32* {{.*}}, i32 {{.*}} acquire var z = Builtin.atomicrmw_add_acquire_Int32(ptr, a) // CHECK: atomicrmw volatile max i32* {{.*}}, i32 {{.*}} monotonic var y = Builtin.atomicrmw_max_monotonic_volatile_Int32(ptr, a) // CHECK: atomicrmw volatile xchg i32* {{.*}}, i32 {{.*}} syncscope("singlethread") acquire var x = Builtin.atomicrmw_xchg_acquire_volatile_singlethread_Int32(ptr, a) // rdar://12939803 - ER: support atomic cmpxchg/xchg with pointers // CHECK: atomicrmw volatile xchg i64* {{.*}}, i64 {{.*}} syncscope("singlethread") acquire var w = Builtin.atomicrmw_xchg_acquire_volatile_singlethread_RawPointer(ptr, ptr2) } func addressof_test(_ a: inout Int, b: inout Bool) { // CHECK: bitcast i32* {{.*}} to i8* var ap : Builtin.RawPointer = Builtin.addressof(&a) // CHECK: bitcast i1* {{.*}} to i8* var bp : Builtin.RawPointer = Builtin.addressof(&b) } func fneg_test(_ half: Builtin.FPIEEE16, single: Builtin.FPIEEE32, double: Builtin.FPIEEE64) -> (Builtin.FPIEEE16, Builtin.FPIEEE32, Builtin.FPIEEE64) { // CHECK: fsub half 0xH8000, {{%.*}} // CHECK: fsub float -0.000000e+00, {{%.*}} // CHECK: fsub double -0.000000e+00, {{%.*}} return (Builtin.fneg_FPIEEE16(half), Builtin.fneg_FPIEEE32(single), Builtin.fneg_FPIEEE64(double)) } // The call to the builtins should get removed before we reach IRGen. func testStaticReport(_ b: Bool, ptr: Builtin.RawPointer) -> () { Builtin.staticReport(b, b, ptr); return Builtin.staticReport(b, b, ptr); } // CHECK-LABEL: define hidden {{.*}}void @"$S8builtins12testCondFail{{[_0-9a-zA-Z]*}}F"(i1, i1) func testCondFail(_ b: Bool, c: Bool) { // CHECK: br i1 %0, label %[[FAIL:.*]], label %[[CONT:.*]] Builtin.condfail(b) // CHECK: <label>:[[CONT]] // CHECK: br i1 %1, label %[[FAIL2:.*]], label %[[CONT:.*]] Builtin.condfail(c) // CHECK: <label>:[[CONT]] // CHECK: ret void // CHECK: <label>:[[FAIL]] // CHECK: call void @llvm.trap() // CHECK: unreachable // CHECK: <label>:[[FAIL2]] // CHECK: call void @llvm.trap() // CHECK: unreachable } // CHECK-LABEL: define hidden {{.*}}void @"$S8builtins8testOnce{{[_0-9a-zA-Z]*}}F"(i8*, i8*) {{.*}} { // CHECK: [[PRED_PTR:%.*]] = bitcast i8* %0 to [[WORD:i64|i32]]* // CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]] // CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1 // CHECK-objc: br i1 [[IS_DONE]], label %[[DONE:.*]], label %[[NOT_DONE:.*]] // CHECK-objc: [[NOT_DONE]]: // CHECK: call void @swift_once([[WORD]]* [[PRED_PTR]], i8* %1, i8* undef) // CHECK-objc: br label %[[DONE]] // CHECK-objc: [[DONE]]: // CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]] // CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1 // CHECK-objc: call void @llvm.assume(i1 [[IS_DONE]]) func testOnce(_ p: Builtin.RawPointer, f: @escaping @convention(c) () -> ()) { Builtin.once(p, f) } // CHECK-LABEL: define hidden {{.*}}void @"$S8builtins19testOnceWithContext{{[_0-9a-zA-Z]*}}F"(i8*, i8*, i8*) {{.*}} { // CHECK: [[PRED_PTR:%.*]] = bitcast i8* %0 to [[WORD:i64|i32]]* // CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]] // CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1 // CHECK-objc: br i1 [[IS_DONE]], label %[[DONE:.*]], label %[[NOT_DONE:.*]] // CHECK-objc: [[NOT_DONE]]: // CHECK: call void @swift_once([[WORD]]* [[PRED_PTR]], i8* %1, i8* %2) // CHECK-objc: br label %[[DONE]] // CHECK-objc: [[DONE]]: // CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]] // CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1 // CHECK-objc: call void @llvm.assume(i1 [[IS_DONE]]) func testOnceWithContext(_ p: Builtin.RawPointer, f: @escaping @convention(c) (Builtin.RawPointer) -> (), k: Builtin.RawPointer) { Builtin.onceWithContext(p, f, k) } class C {} struct S {} #if _runtime(_ObjC) @objc class O {} @objc protocol OP1 {} @objc protocol OP2 {} #endif protocol P {} // CHECK-LABEL: define hidden {{.*}}void @"$S8builtins10canBeClass{{[_0-9a-zA-Z]*}}F" func canBeClass<T>(_ f: @escaping (Builtin.Int8) -> (), _: T) { #if _runtime(_ObjC) // CHECK-objc: call {{.*}}void {{%.*}}(i8 1 f(Builtin.canBeClass(O.self)) // CHECK-objc: call {{.*}}void {{%.*}}(i8 1 f(Builtin.canBeClass(OP1.self)) typealias ObjCCompo = OP1 & OP2 // CHECK-objc: call {{.*}}void {{%.*}}(i8 1 f(Builtin.canBeClass(ObjCCompo.self)) #endif // CHECK: call {{.*}}void {{%.*}}(i8 0 f(Builtin.canBeClass(S.self)) // CHECK: call {{.*}}void {{%.*}}(i8 1 f(Builtin.canBeClass(C.self)) // CHECK: call {{.*}}void {{%.*}}(i8 0 f(Builtin.canBeClass(P.self)) #if _runtime(_ObjC) typealias MixedCompo = OP1 & P // CHECK-objc: call {{.*}}void {{%.*}}(i8 0 f(Builtin.canBeClass(MixedCompo.self)) #endif // CHECK: call {{.*}}void {{%.*}}(i8 2 f(Builtin.canBeClass(T.self)) } // CHECK-LABEL: define hidden {{.*}}void @"$S8builtins15destroyPODArray{{[_0-9a-zA-Z]*}}F"(i8*, i64) // CHECK-NOT: loop: // CHECK: ret void func destroyPODArray(_ array: Builtin.RawPointer, count: Builtin.Word) { Builtin.destroyArray(Int.self, array, count) } // CHECK-LABEL: define hidden {{.*}}void @"$S8builtins18destroyNonPODArray{{[_0-9a-zA-Z]*}}F"(i8*, i64) {{.*}} { // CHECK-NOT: loop: // CHECK: call void @swift_arrayDestroy( func destroyNonPODArray(_ array: Builtin.RawPointer, count: Builtin.Word) { Builtin.destroyArray(C.self, array, count) } // CHECK-LABEL: define hidden {{.*}}void @"$S8builtins15destroyGenArray_5count_yBp_BwxtlF"(i8*, i64, %swift.opaque* noalias nocapture, %swift.type* %T) // CHECK-NOT: loop: // CHECK: call void @swift_arrayDestroy func destroyGenArray<T>(_ array: Builtin.RawPointer, count: Builtin.Word, _: T) { Builtin.destroyArray(T.self, array, count) } // CHECK-LABEL: define hidden {{.*}}void @"$S8builtins12copyPODArray{{[_0-9a-zA-Z]*}}F"(i8*, i8*, i64) // check: mul nuw i64 4, %2 // check: call void @llvm.memcpy.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false) // check: mul nuw i64 4, %2 // check: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false) // check: mul nuw i64 4, %2 // check: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false) // check: mul nuw i64 4, %2 // check: call void @llvm.memcpy.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false) // check: mul nuw i64 4, %2 // check: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false) // check: mul nuw i64 4, %2 // check: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false) // check: mul nuw i64 4, %2 // check: call void @llvm.memcpy.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false) func copyPODArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) { Builtin.copyArray(Int.self, dest, src, count) Builtin.takeArrayFrontToBack(Int.self, dest, src, count) Builtin.takeArrayBackToFront(Int.self, dest, src, count) Builtin.assignCopyArrayNoAlias(Int.self, dest, src, count) Builtin.assignCopyArrayFrontToBack(Int.self, dest, src, count) Builtin.assignCopyArrayBackToFront(Int.self, dest, src, count) Builtin.assignTakeArray(Int.self, dest, src, count) } // CHECK-LABEL: define hidden {{.*}}void @"$S8builtins11copyBTArray{{[_0-9a-zA-Z]*}}F"(i8*, i8*, i64) {{.*}} { // CHECK-NOT: loop: // CHECK: call void @swift_arrayInitWithCopy // CHECK: mul nuw i64 8, %2 // CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i1 false) // CHECK: mul nuw i64 8, %2 // CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i1 false) // CHECK: call void @swift_arrayAssignWithCopyNoAlias( // CHECK: call void @swift_arrayAssignWithCopyFrontToBack( // CHECK: call void @swift_arrayAssignWithCopyBackToFront( // CHECK: call void @swift_arrayAssignWithTake( func copyBTArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) { Builtin.copyArray(C.self, dest, src, count) Builtin.takeArrayFrontToBack(C.self, dest, src, count) Builtin.takeArrayBackToFront(C.self, dest, src, count) Builtin.assignCopyArrayNoAlias(C.self, dest, src, count) Builtin.assignCopyArrayFrontToBack(C.self, dest, src, count) Builtin.assignCopyArrayBackToFront(C.self, dest, src, count) Builtin.assignTakeArray(C.self, dest, src, count) } struct W { weak var c: C? } // CHECK-LABEL: define hidden {{.*}}void @"$S8builtins15copyNonPODArray{{[_0-9a-zA-Z]*}}F"(i8*, i8*, i64) {{.*}} { // CHECK-NOT: loop: // CHECK: call void @swift_arrayInitWithCopy( // CHECK-NOT: loop{{.*}}: // CHECK: call void @swift_arrayInitWithTakeFrontToBack( // CHECK-NOT: loop{{.*}}: // CHECK: call void @swift_arrayInitWithTakeBackToFront( // CHECK: call void @swift_arrayAssignWithCopyNoAlias( // CHECK: call void @swift_arrayAssignWithCopyFrontToBack( // CHECK: call void @swift_arrayAssignWithCopyBackToFront( // CHECK: call void @swift_arrayAssignWithTake( func copyNonPODArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) { Builtin.copyArray(W.self, dest, src, count) Builtin.takeArrayFrontToBack(W.self, dest, src, count) Builtin.takeArrayBackToFront(W.self, dest, src, count) Builtin.assignCopyArrayNoAlias(W.self, dest, src, count) Builtin.assignCopyArrayFrontToBack(W.self, dest, src, count) Builtin.assignCopyArrayBackToFront(W.self, dest, src, count) Builtin.assignTakeArray(W.self, dest, src, count) } // CHECK-LABEL: define hidden {{.*}}void @"$S8builtins12copyGenArray{{[_0-9a-zA-Z]*}}F"(i8*, i8*, i64, %swift.opaque* noalias nocapture, %swift.type* %T) // CHECK-NOT: loop: // CHECK: call void @swift_arrayInitWithCopy // CHECK-NOT: loop: // CHECK: call void @swift_arrayInitWithTakeFrontToBack( // CHECK-NOT: loop: // CHECK: call void @swift_arrayInitWithTakeBackToFront( // CHECK: call void @swift_arrayAssignWithCopyNoAlias( // CHECK: call void @swift_arrayAssignWithCopyFrontToBack( // CHECK: call void @swift_arrayAssignWithCopyBackToFront( // CHECK: call void @swift_arrayAssignWithTake( func copyGenArray<T>(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word, _: T) { Builtin.copyArray(T.self, dest, src, count) Builtin.takeArrayFrontToBack(T.self, dest, src, count) Builtin.takeArrayBackToFront(T.self, dest, src, count) Builtin.assignCopyArrayNoAlias(T.self, dest, src, count) Builtin.assignCopyArrayFrontToBack(T.self, dest, src, count) Builtin.assignCopyArrayBackToFront(T.self, dest, src, count) Builtin.assignTakeArray(T.self, dest, src, count) } // CHECK-LABEL: define hidden {{.*}}void @"$S8builtins24conditionallyUnreachableyyF" // CHECK-NEXT: entry // CHECK-NEXT: unreachable func conditionallyUnreachable() { Builtin.conditionallyUnreachable() } struct Abc { var value : Builtin.Word } // CHECK-LABEL: define hidden {{.*}}@"$S8builtins22assumeNonNegative_testyBwAA3AbcVzF" func assumeNonNegative_test(_ x: inout Abc) -> Builtin.Word { // CHECK: load {{.*}}, !range ![[R:[0-9]+]] return Builtin.assumeNonNegative_Word(x.value) } @inline(never) func return_word(_ x: Builtin.Word) -> Builtin.Word { return x } // CHECK-LABEL: define hidden {{.*}}@"$S8builtins23assumeNonNegative_test2yBwBwF" func assumeNonNegative_test2(_ x: Builtin.Word) -> Builtin.Word { // CHECK: call {{.*}}, !range ![[R]] return Builtin.assumeNonNegative_Word(return_word(x)) } struct Empty {} struct Pair { var i: Int, b: Bool } // CHECK-LABEL: define hidden {{.*}}i64 @"$S8builtins15zeroInitializerAA5EmptyV_AA4PairVtyF"() {{.*}} { // CHECK: [[ALLOCA:%.*]] = alloca { i64 } // CHECK: bitcast // CHECK: lifetime.start // CHECK: [[EMPTYPAIR:%.*]] = bitcast { i64 }* [[ALLOCA]] // CHECK: [[PAIR:%.*]] = getelementptr inbounds {{.*}} [[EMPTYPAIR]], i32 0, i32 0 // CHECK: [[FLDI:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 0 // CHECK: store i32 0, i32* [[FLDI]] // CHECK: [[FLDB:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 1 // CHECK: store i1 false, i1* [[FLDB]] // CHECK: [[RET:%.*]] = getelementptr inbounds {{.*}} [[ALLOCA]], i32 0, i32 0 // CHECK: [[RES:%.*]] = load i64, i64* [[RET]] // CHECK: ret i64 [[RES]] func zeroInitializer() -> (Empty, Pair) { return (Builtin.zeroInitializer(), Builtin.zeroInitializer()) } // CHECK-LABEL: define hidden {{.*}}i64 @"$S8builtins20zeroInitializerTupleAA5EmptyV_AA4PairVtyF"() {{.*}} { // CHECK: [[ALLOCA:%.*]] = alloca { i64 } // CHECK: bitcast // CHECK: lifetime.start // CHECK: [[EMPTYPAIR:%.*]] = bitcast { i64 }* [[ALLOCA]] // CHECK: [[PAIR:%.*]] = getelementptr inbounds {{.*}} [[EMPTYPAIR]], i32 0, i32 0 // CHECK: [[FLDI:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 0 // CHECK: store i32 0, i32* [[FLDI]] // CHECK: [[FLDB:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 1 // CHECK: store i1 false, i1* [[FLDB]] // CHECK: [[RET:%.*]] = getelementptr inbounds {{.*}} [[ALLOCA]], i32 0, i32 0 // CHECK: [[RES:%.*]] = load i64, i64* [[RET]] // CHECK: ret i64 [[RES]] func zeroInitializerTuple() -> (Empty, Pair) { return Builtin.zeroInitializer() } // CHECK-LABEL: define hidden {{.*}}void @"$S8builtins20zeroInitializerEmptyyyF"() {{.*}} { // CHECK: ret void func zeroInitializerEmpty() { return Builtin.zeroInitializer() } // ---------------------------------------------------------------------------- // isUnique variants // ---------------------------------------------------------------------------- // CHECK: define hidden {{.*}}void @"$S8builtins26acceptsBuiltinNativeObjectyyBoSgzF"([[BUILTIN_NATIVE_OBJECT_TY:%.*]]* nocapture dereferenceable({{.*}})) {{.*}} { func acceptsBuiltinNativeObject(_ ref: inout Builtin.NativeObject?) {} // native // CHECK-LABEL: define hidden {{.*}}i1 @"$S8builtins8isUniqueyBi1_BoSgzF"({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} { // CHECK-NEXT: entry: // CHECK-NEXT: bitcast [[BUILTIN_NATIVE_OBJECT_TY]]* %0 to %swift.refcounted** // CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1 // CHECK-NEXT: call i1 @swift_isUniquelyReferenced_native(%swift.refcounted* %2) // CHECK-NEXT: ret i1 %3 func isUnique(_ ref: inout Builtin.NativeObject?) -> Bool { return Builtin.isUnique(&ref) } // native nonNull // CHECK-LABEL: define hidden {{.*}}i1 @"$S8builtins8isUniqueyBi1_BozF"(%swift.refcounted** nocapture dereferenceable({{.*}})) {{.*}} { // CHECK-NEXT: entry: // CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %0 // CHECK-NEXT: call i1 @swift_isUniquelyReferenced_nonNull_native(%swift.refcounted* %1) // CHECK-NEXT: ret i1 %2 func isUnique(_ ref: inout Builtin.NativeObject) -> Bool { return Builtin.isUnique(&ref) } // CHECK: define hidden {{.*}}void @"$S8builtins27acceptsBuiltinUnknownObjectyyBOSgzF"([[BUILTIN_UNKNOWN_OBJECT_TY:%.*]]* nocapture dereferenceable({{.*}})) {{.*}} { func acceptsBuiltinUnknownObject(_ ref: inout Builtin.UnknownObject?) {} // ObjC // CHECK-LABEL: define hidden {{.*}}i1 @"$S8builtins8isUniqueyBi1_BOSgzF"({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} { // CHECK-NEXT: entry: // CHECK-NEXT: bitcast [[BUILTIN_UNKNOWN_OBJECT_TY]]* %0 to [[UNKNOWN_OBJECT:%objc_object|%swift\.refcounted]]** // CHECK-NEXT: load [[UNKNOWN_OBJECT]]*, [[UNKNOWN_OBJECT]]** %1 // CHECK-objc-NEXT: call i1 @swift_isUniquelyReferencedNonObjC([[UNKNOWN_OBJECT]]* %2) // CHECK-native-NEXT: call i1 @swift_isUniquelyReferenced_native([[UNKNOWN_OBJECT]]* %2) // CHECK-NEXT: ret i1 %3 func isUnique(_ ref: inout Builtin.UnknownObject?) -> Bool { return Builtin.isUnique(&ref) } // ObjC nonNull // CHECK-LABEL: define hidden {{.*}}i1 @"$S8builtins8isUniqueyBi1_BOzF" // CHECK-SAME: ([[UNKNOWN_OBJECT]]** nocapture dereferenceable({{.*}})) {{.*}} { // CHECK-NEXT: entry: // CHECK-NEXT: load [[UNKNOWN_OBJECT]]*, [[UNKNOWN_OBJECT]]** %0 // CHECK-objc-NEXT: call i1 @swift_isUniquelyReferencedNonObjC_nonNull([[UNKNOWN_OBJECT]]* %1) // CHECK-native-NEXT: call i1 @swift_isUniquelyReferenced_nonNull_native([[UNKNOWN_OBJECT]]* %1) // CHECK-NEXT: ret i1 %2 func isUnique(_ ref: inout Builtin.UnknownObject) -> Bool { return Builtin.isUnique(&ref) } // BridgeObject nonNull // CHECK-LABEL: define hidden {{.*}}i1 @"$S8builtins8isUniqueyBi1_BbzF"(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} { // CHECK-NEXT: entry: // CHECK-NEXT: load %swift.bridge*, %swift.bridge** %0 // CHECK-NEXT: call i1 @swift_isUniquelyReferencedNonObjC_nonNull_bridgeObject(%swift.bridge* %1) // CHECK-NEXT: ret i1 %2 func isUnique(_ ref: inout Builtin.BridgeObject) -> Bool { return Builtin.isUnique(&ref) } // BridgeObject nonNull // CHECK-LABEL: define hidden {{.*}}i1 @"$S8builtins15isUnique_nativeyBi1_BbzF"(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} { // CHECK-NEXT: entry: // CHECK-NEXT: bitcast %swift.bridge** %0 to %swift.refcounted** // CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1 // CHECK-NEXT: call i1 @swift_isUniquelyReferenced_nonNull_native(%swift.refcounted* %2) // CHECK-NEXT: ret i1 %3 func isUnique_native(_ ref: inout Builtin.BridgeObject) -> Bool { return Builtin.isUnique_native(&ref) } // ImplicitlyUnwrappedOptional argument to isUnique. // CHECK-LABEL: define hidden {{.*}}i1 @"$S8builtins11isUniqueIUOyBi1_BoSgzF"(%{{.*}}* nocapture dereferenceable({{.*}})) {{.*}} { // CHECK-NEXT: entry: // CHECK: call i1 @swift_isUniquelyReferenced_native(%swift.refcounted* // CHECK: ret i1 func isUniqueIUO(_ ref: inout Builtin.NativeObject?) -> Bool { var iuo : Builtin.NativeObject! = ref return Builtin.isUnique(&iuo) } // CHECK-LABEL: define {{.*}} @{{.*}}generic_ispod_test func generic_ispod_test<T>(_: T) { // CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 9 // CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]] // CHECK-NEXT: [[FLAGS:%.*]] = ptrtoint i8* [[T1]] to i64 // CHECK-NEXT: [[ISNOTPOD:%.*]] = and i64 [[FLAGS]], 65536 // CHECK-NEXT: [[ISPOD:%.*]] = icmp eq i64 [[ISNOTPOD]], 0 // CHECK-NEXT: store i1 [[ISPOD]], i1* [[S:%.*]] var s = Builtin.ispod(T.self) } // CHECK-LABEL: define {{.*}} @{{.*}}ispod_test func ispod_test() { // CHECK: store i1 true, i1* // CHECK: store i1 false, i1* var t = Builtin.ispod(Int.self) var f = Builtin.ispod(Builtin.NativeObject.self) } // CHECK-LABEL: define {{.*}} @{{.*}}generic_isbitwisetakable_test func generic_isbitwisetakable_test<T>(_: T) { // CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 9 // CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]] // CHECK-NEXT: [[FLAGS:%.*]] = ptrtoint i8* [[T1]] to i64 // CHECK-NEXT: [[ISNOTBITWISETAKABLE:%.*]] = and i64 [[FLAGS]], 1048576 // CHECK-NEXT: [[ISBITWISETAKABLE:%.*]] = icmp eq i64 [[ISNOTBITWISETAKABLE]], 0 // CHECK-NEXT: store i1 [[ISBITWISETAKABLE]], i1* [[S:%.*]] var s = Builtin.isbitwisetakable(T.self) } // CHECK-LABEL: define {{.*}} @{{.*}}isbitwisetakable_test func isbitwisetakable_test() { // CHECK: store i1 true, i1* // CHECK: store i1 true, i1* // CHECK: store i1 true, i1* // CHECK: store i1 true, i1* // CHECK: store i1 false, i1* var t1 = Builtin.isbitwisetakable(Int.self) var t2 = Builtin.isbitwisetakable(C.self) var t3 = Builtin.isbitwisetakable(Abc.self) var t4 = Builtin.isbitwisetakable(Empty.self) var f = Builtin.isbitwisetakable(W.self) } // CHECK-LABEL: define {{.*}} @{{.*}}is_same_metatype func is_same_metatype_test(_ t1: Any.Type, _ t2: Any.Type) { // CHECK: [[MT1_AS_PTR:%.*]] = bitcast %swift.type* %0 to i8* // CHECK: [[MT2_AS_PTR:%.*]] = bitcast %swift.type* %1 to i8* // CHECK: icmp eq i8* [[MT1_AS_PTR]], [[MT2_AS_PTR]] var t = Builtin.is_same_metatype(t1, t2) } // CHECK-LABEL: define {{.*}} @{{.*}}generic_unsafeGuaranteed_test // CHECK: call {{.*}}* @{{.*}}swift_{{.*}}etain({{.*}}* returned %0) // CHECK: ret {{.*}}* %0 func generic_unsafeGuaranteed_test<T: AnyObject>(_ t : T) -> T { let (g, _) = Builtin.unsafeGuaranteed(t) return g } // CHECK-LABEL: define {{.*}} @{{.*}}unsafeGuaranteed_test // CHECK: [[LOCAL:%.*]] = alloca %swift.refcounted* // CHECK: call %swift.refcounted* @swift_retain(%swift.refcounted* returned %0) // CHECK: store %swift.refcounted* %0, %swift.refcounted** [[LOCAL]] // CHECK-NOT: call void @swift_release(%swift.refcounted* %0) // CHECK: ret %swift.refcounted* %0 func unsafeGuaranteed_test(_ x: Builtin.NativeObject) -> Builtin.NativeObject { var (g,t) = Builtin.unsafeGuaranteed(x) Builtin.unsafeGuaranteedEnd(t) return g } // CHECK-LABEL: define {{.*}} @{{.*}}unsafeGuaranteedEnd_test // CHECK-NEXT: {{.*}}: // CHECK-NEXT: alloca // CHECK-NEXT: store // CHECK-NEXT: ret void func unsafeGuaranteedEnd_test(_ x: Builtin.Int8) { Builtin.unsafeGuaranteedEnd(x) } // CHECK-LABEL: define {{.*}} @{{.*}}atomicload func atomicload(_ p: Builtin.RawPointer) { // CHECK: [[A:%.*]] = load atomic i8*, i8** {{%.*}} unordered, align 8 let a: Builtin.RawPointer = Builtin.atomicload_unordered_RawPointer(p) // CHECK: [[B:%.*]] = load atomic i32, i32* {{%.*}} syncscope("singlethread") monotonic, align 4 let b: Builtin.Int32 = Builtin.atomicload_monotonic_singlethread_Int32(p) // CHECK: [[C:%.*]] = load atomic volatile i64, i64* {{%.*}} syncscope("singlethread") acquire, align 8 let c: Builtin.Int64 = Builtin.atomicload_acquire_volatile_singlethread_Int64(p) // CHECK: [[D0:%.*]] = load atomic volatile i32, i32* {{%.*}} seq_cst, align 4 // CHECK: [[D:%.*]] = bitcast i32 [[D0]] to float let d: Builtin.FPIEEE32 = Builtin.atomicload_seqcst_volatile_FPIEEE32(p) // CHECK: store atomic i8* [[A]], i8** {{%.*}} unordered, align 8 Builtin.atomicstore_unordered_RawPointer(p, a) // CHECK: store atomic i32 [[B]], i32* {{%.*}} syncscope("singlethread") monotonic, align 4 Builtin.atomicstore_monotonic_singlethread_Int32(p, b) // CHECK: store atomic volatile i64 [[C]], i64* {{%.*}} syncscope("singlethread") release, align 8 Builtin.atomicstore_release_volatile_singlethread_Int64(p, c) // CHECK: [[D1:%.*]] = bitcast float [[D]] to i32 // CHECK: store atomic volatile i32 [[D1]], i32* {{.*}} seq_cst, align 4 Builtin.atomicstore_seqcst_volatile_FPIEEE32(p, d) } // CHECK-LABEL: define {{.*}} @"$S8builtins14stringObjectOryS2u_SutF"(i64, i64) // CHECK: %4 = or i64 %0, %1 // CHECK-NEXT: ret i64 %4 func stringObjectOr(_ x: UInt, _ y: UInt) -> UInt { return UInt(Builtin.stringObjectOr_Int64( x._value, y._value)) } func createInt(_ fn: () -> ()) throws {} // CHECK-LABEL: define {{.*}}testForceTry // CHECK: call swiftcc void @swift_unexpectedError(%swift.error* func testForceTry(_ fn: () -> ()) { try! createInt(fn) } // CHECK-LABEL: declare{{( dllimport)?}} swiftcc void @swift_unexpectedError(%swift.error* enum MyError : Error { case A, B } throw MyError.A // CHECK: ![[R]] = !{i64 0, i64 9223372036854775807}
41.768564
259
0.637086
e5abc2ad353e6fb5b83bc91a6fdfcfa8a8185957
1,246
// // ViewController+STWPageViewController.swift // STWPageViewController // // Created by Steewe MacBook Pro on 14/09/17. // Copyright © 2017 Steewe. All rights reserved. // import Foundation import UIKit //MARK: UIViewController extension public extension UIViewController { private struct AssociatedKeys { static var displayed = "STWToolBarItem" } /// The Item that represents the view controller when added to a STWPageViewController /// - automatically created with the view controller's title if it's not set explicitly public var pageViewControllerToolBarItem:STWPageViewControllerToolBarItem! { get { guard let pageViewControllerToolBarItem = objc_getAssociatedObject(self, &AssociatedKeys.displayed) as? STWPageViewControllerToolBarItem else { let defaultButton = STWPageViewControllerToolBarItem(title: self.title, normalColor: .gray, selectedColor: .black) return defaultButton } return pageViewControllerToolBarItem } set(value) { objc_setAssociatedObject(self,&AssociatedKeys.displayed, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } }
33.675676
155
0.707865
dbd3a66c94073f20de21ed01c1ca42dc7efe8a51
6,162
// Copyright © 2020 Stormbird PTE. LTD. import UIKit import BigInt import StatefulViewController protocol ActivitiesViewControllerDelegate: AnyObject { func didPressActivity(activity: Activity, in viewController: ActivitiesViewController) func didPressTransaction(transaction: TransactionInstance, in viewController: ActivitiesViewController) } class ActivitiesViewController: UIViewController { private var viewModel: ActivitiesViewModel private let searchController: UISearchController private var isSearchBarConfigured = false private var bottomConstraint: NSLayoutConstraint! private lazy var keyboardChecker = KeyboardChecker(self, resetHeightDefaultValue: 0, ignoreBottomSafeArea: true) private var activitiesView: ActivitiesView weak var delegate: ActivitiesViewControllerDelegate? init(viewModel: ActivitiesViewModel, sessions: ServerDictionary<WalletSession>) { self.viewModel = viewModel searchController = UISearchController(searchResultsController: nil) activitiesView = ActivitiesView(viewModel: viewModel, sessions: sessions) super.init(nibName: nil, bundle: nil) title = R.string.localizable.activityTabbarItemTitle() activitiesView.delegate = self view.backgroundColor = viewModel.backgroundColor bottomConstraint = activitiesView.bottomAnchor.constraint(equalTo: view.bottomAnchor) keyboardChecker.constraints = [bottomConstraint] view.addSubview(activitiesView) NSLayoutConstraint.activate([ activitiesView.topAnchor.constraint(equalTo: view.topAnchor), activitiesView.leadingAnchor.constraint(equalTo: view.leadingAnchor), activitiesView.trailingAnchor.constraint(equalTo: view.trailingAnchor), bottomConstraint, ]) setupFilteringWithKeyword() configure(viewModel: viewModel) } deinit { activitiesView.resetStatefulStateToReleaseObjectToAvoidMemoryLeak() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) keyboardChecker.viewWillAppear() navigationItem.largeTitleDisplayMode = .always } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) //NOTE: we call it here to show empty view if needed, as the reason that we don't have manually called callback where we can handle that loaded activities //next time view will be updated when configure with viewModel method get called. activitiesView.endLoading() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) keyboardChecker.viewWillDisappear() } func configure(viewModel: ActivitiesViewModel) { self.viewModel = viewModel activitiesView.configure(viewModel: viewModel) activitiesView.applySearch(keyword: searchController.searchBar.text) activitiesView.endLoading() } required init?(coder aDecoder: NSCoder) { return nil } override func viewDidLayoutSubviews() { configureSearchBarOnce() } } extension ActivitiesViewController: ActivitiesViewDelegate { func didPressActivity(activity: Activity, in view: ActivitiesView) { delegate?.didPressActivity(activity: activity, in: self) } func didPressTransaction(transaction: TransactionInstance, in view: ActivitiesView) { delegate?.didPressTransaction(transaction: transaction, in: self) } } extension ActivitiesViewController: UISearchResultsUpdating { //At least on iOS 13 beta on a device. updateSearchResults(for:) is called when we set `searchController.isActive = false` to dismiss search (because user tapped on a filter), but the value of `searchController.isActive` remains `false` during the call, hence the async. //This behavior is not observed in iOS 12, simulator public func updateSearchResults(for searchController: UISearchController) { processSearchWithKeywords() } private func processSearchWithKeywords() { activitiesView.applySearch(keyword: searchController.searchBar.text) } } extension ActivitiesViewController { private func makeSwitchToAnotherTabWorkWhileFiltering() { definesPresentationContext = true } private func wireUpSearchController() { searchController.searchResultsUpdater = self navigationItem.searchController = searchController navigationItem.hidesSearchBarWhenScrolling = true } private func fixNavigationBarAndStatusBarBackgroundColorForiOS13Dot1() { view.superview?.backgroundColor = viewModel.backgroundColor } private func setupFilteringWithKeyword() { wireUpSearchController() doNotDimTableViewToReuseTableForFilteringResult() makeSwitchToAnotherTabWorkWhileFiltering() } private func doNotDimTableViewToReuseTableForFilteringResult() { searchController.obscuresBackgroundDuringPresentation = false } //Makes a difference where this is called from. Can't be too early private func configureSearchBarOnce() { guard !isSearchBarConfigured else { return } isSearchBarConfigured = true UISearchBar.configure(searchBar: searchController.searchBar) } } extension ActivitiesViewController { class functional {} } extension ActivitiesViewController.functional { static func headerView(for section: Int, viewModel: ActivitiesViewModel) -> UIView { let container = UIView() container.backgroundColor = viewModel.headerBackgroundColor let title = UILabel() title.text = viewModel.titleForHeader(in: section) title.sizeToFit() title.textColor = viewModel.headerTitleTextColor title.font = viewModel.headerTitleFont container.addSubview(title) title.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ title.anchorsConstraint(to: container, edgeInsets: .init(top: 18, left: 20, bottom: 16, right: 0)) ]) return container } }
36.678571
274
0.734826
9141c803927792e203f11abdce521f2aa172dfc0
4,385
import AVFoundation import RxSwift import RxCocoa // MARK: - KVO extension Reactive where Base: AVPlayerItem { public var asset: Observable<AVAsset?> { return self.observe( AVAsset.self, #keyPath(AVPlayerItem.asset) ) } public var duration: Observable<CMTime> { return self.observe( CMTime.self, #keyPath(AVPlayerItem.duration) ).map { $0 ?? kCMTimeZero } } public var error: Observable<NSError?> { return self.observe( NSError.self, #keyPath(AVPlayerItem.error) ) } public var loadedTimeRanges: Observable<[NSValue]> { return self.observe( [NSValue].self, #keyPath(AVPlayerItem.loadedTimeRanges) ).map { $0 ?? [] } } public var presentationSize: Observable<CMTime> { return self.observe( CMTime.self, #keyPath(AVPlayerItem.presentationSize) ).map { $0 ?? kCMTimeZero } } public var status: Observable<AVPlayerItemStatus> { return self.observe( AVPlayerItemStatus.self, #keyPath(AVPlayerItem.status) ).map { $0 ?? .unknown } } public var timebase: Observable<CMTimebase?> { return self.observe( CMTimebase.self, #keyPath(AVPlayerItem.timebase) ) } public var tracks: Observable<[AVPlayerItemTrack]> { return self.observe( [AVPlayerItemTrack].self, #keyPath(AVPlayerItem.tracks) ).map { $0 ?? [] } } // MARK: - Moving the Playhead public var seekableTimeRanges: Observable<[NSValue]> { return self.observe( [NSValue].self, #keyPath(AVPlayerItem.seekableTimeRanges) ).map { $0 ?? [] } } // MARK: - Information About Playback public var isPlaybackLikelyToKeepUp: Observable<Bool> { return self.observe( Bool.self, #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp) ).map { $0 ?? false } } public var isPlaybackBufferEmpty: Observable<Bool> { return self.observe( Bool.self, #keyPath(AVPlayerItem.isPlaybackBufferEmpty) ).map { $0 ?? false } } public var isPlaybackBufferFull: Observable<Bool> { return self.observe( Bool.self, #keyPath(AVPlayerItem.isPlaybackBufferFull) ).map { $0 ?? false } } } // MARK: - Notification extension Reactive where Base: AVPlayerItem { public var didPlayToEnd: Observable<Notification> { return NotificationCenter .default .rx .notification(.AVPlayerItemDidPlayToEndTime, object: base) .filter { notification in if let obj = notification.object as? Base, obj == self.base { return true } else { return false } } } public var timeJumped: Observable<Notification> { return NotificationCenter .default .rx .notification(.AVPlayerItemTimeJumped, object: base) .filter { notification in if let obj = notification.object as? Base, obj == self.base { return true } else { return false } } } public var failedToPlayToEndTime: Observable<Notification> { return NotificationCenter .default .rx .notification(.AVPlayerItemFailedToPlayToEndTime, object: base) .filter { notification in if let obj = notification.object as? Base, obj == self.base { return true } else { return false } } } public var playbackStalled: Observable<Notification> { return NotificationCenter .default .rx .notification(.AVPlayerItemPlaybackStalled, object: base) .filter { notification in if let obj = notification.object as? Base, obj == self.base { return true } else { return false } } } public var newAccessLogEntry: Observable<Notification> { return NotificationCenter .default .rx .notification(.AVPlayerItemNewAccessLogEntry, object: base) .filter { notification in if let obj = notification.object as? Base, obj == self.base { return true } else { return false } } } public var newErrorLogEntry: Observable<Notification> { return NotificationCenter .default .rx .notification(.AVPlayerItemNewErrorLogEntry, object: base) .filter { notification in if let obj = notification.object as? Base, obj == self.base { return true } else { return false } } } }
25.201149
69
0.634436
fbbb1318337f2fbbf2e84d85ec8d20c41d63b736
26,593
// // RNTrackPlayer.swift // RNTrackPlayer // // Created by David Chavez on 13.08.17. // Copyright © 2017 David Chavez. All rights reserved. // import Foundation import MediaPlayer import SwiftAudioEx @objc(RNTrackPlayer) public class RNTrackPlayer: RCTEventEmitter { // MARK: - Attributes private var hasInitialized = false private let player = QueuedAudioPlayer() // MARK: - Lifecycle Methods public override init() { super.init() player.event.playbackEnd.addListener(self, handleAudioPlayerPlaybackEnded) player.event.receiveMetadata.addListener(self, handleAudioPlayerMetadataReceived) player.event.stateChange.addListener(self, handleAudioPlayerStateChange) player.event.fail.addListener(self, handleAudioPlayerFailed) player.event.queueIndex.addListener(self, handleAudioPlayerQueueIndexChange) } deinit { reset(resolve: { _ in }, reject: { _, _, _ in }) } // MARK: - RCTEventEmitter override public static func requiresMainQueueSetup() -> Bool { return true; } @objc(constantsToExport) override public func constantsToExport() -> [AnyHashable: Any] { return [ "STATE_NONE": AVPlayerWrapperState.idle.rawValue, "STATE_READY": AVPlayerWrapperState.ready.rawValue, "STATE_PLAYING": AVPlayerWrapperState.playing.rawValue, "STATE_PAUSED": AVPlayerWrapperState.paused.rawValue, "STATE_STOPPED": AVPlayerWrapperState.idle.rawValue, "STATE_BUFFERING": AVPlayerWrapperState.loading.rawValue, "TRACK_PLAYBACK_ENDED_REASON_END": PlaybackEndedReason.playedUntilEnd.rawValue, "TRACK_PLAYBACK_ENDED_REASON_JUMPED": PlaybackEndedReason.jumpedToIndex.rawValue, "TRACK_PLAYBACK_ENDED_REASON_NEXT": PlaybackEndedReason.skippedToNext.rawValue, "TRACK_PLAYBACK_ENDED_REASON_PREVIOUS": PlaybackEndedReason.skippedToPrevious.rawValue, "TRACK_PLAYBACK_ENDED_REASON_STOPPED": PlaybackEndedReason.playerStopped.rawValue, "PITCH_ALGORITHM_LINEAR": PitchAlgorithm.linear.rawValue, "PITCH_ALGORITHM_MUSIC": PitchAlgorithm.music.rawValue, "PITCH_ALGORITHM_VOICE": PitchAlgorithm.voice.rawValue, "CAPABILITY_PLAY": Capability.play.rawValue, "CAPABILITY_PLAY_FROM_ID": "NOOP", "CAPABILITY_PLAY_FROM_SEARCH": "NOOP", "CAPABILITY_PAUSE": Capability.pause.rawValue, "CAPABILITY_STOP": Capability.stop.rawValue, "CAPABILITY_SEEK_TO": Capability.seek.rawValue, "CAPABILITY_SKIP": "NOOP", "CAPABILITY_SKIP_TO_NEXT": Capability.next.rawValue, "CAPABILITY_SKIP_TO_PREVIOUS": Capability.previous.rawValue, "CAPABILITY_SET_RATING": "NOOP", "CAPABILITY_JUMP_FORWARD": Capability.jumpForward.rawValue, "CAPABILITY_JUMP_BACKWARD": Capability.jumpBackward.rawValue, "CAPABILITY_LIKE": Capability.like.rawValue, "CAPABILITY_DISLIKE": Capability.dislike.rawValue, "CAPABILITY_BOOKMARK": Capability.bookmark.rawValue, "REPEAT_OFF": RepeatMode.off.rawValue, "REPEAT_TRACK": RepeatMode.track.rawValue, "REPEAT_QUEUE": RepeatMode.queue.rawValue, ] } @objc(supportedEvents) override public func supportedEvents() -> [String] { return [ "playback-queue-ended", "playback-state", "playback-error", "playback-track-changed", "playback-metadata-received", "remote-stop", "remote-pause", "remote-play", "remote-duck", "remote-next", "remote-seek", "remote-previous", "remote-jump-forward", "remote-jump-backward", "remote-like", "remote-dislike", "remote-bookmark", ] } func setupInterruptionHandling() { let notificationCenter = NotificationCenter.default notificationCenter.removeObserver(self) notificationCenter.addObserver(self, selector: #selector(handleInterruption), name: AVAudioSession.interruptionNotification, object: nil) } @objc func handleInterruption(notification: Notification) { guard let userInfo = notification.userInfo, let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt, let type = AVAudioSession.InterruptionType(rawValue: typeValue) else { return } if type == .began { // Interruption began, take appropriate actions (save state, update user interface) self.sendEvent(withName: "remote-duck", body: [ "paused": true ]) } else if type == .ended { guard let optionsValue = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt else { return } let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue) if options.contains(.shouldResume) { // Interruption Ended - playback should resume self.sendEvent(withName: "remote-duck", body: [ "paused": false ]) } else { // Interruption Ended - playback should NOT resume self.sendEvent(withName: "remote-duck", body: [ "paused": true, "permanent": true ]) } } } private func setupSessionCategory(_ configs: [String: Any]) { // configure audio session - category, options & mode var sessionCategory: AVAudioSession.Category = .playback var sessionCategoryOptions: AVAudioSession.CategoryOptions = [] var sessionCategoryMode: AVAudioSession.Mode = .default if let sessionCategoryStr = configs["iosCategory"] as? String, let mappedCategory = SessionCategory(rawValue: sessionCategoryStr) { sessionCategory = mappedCategory.mapConfigToAVAudioSessionCategory() } let sessionCategoryOptsStr = config["iosCategoryOptions"] as? [String] let mappedCategoryOpts = sessionCategoryOptsStr?.compactMap { SessionCategoryOptions(rawValue: $0)?.mapConfigToAVAudioSessionCategoryOptions() } ?? [] sessionCategoryOptions = AVAudioSession.CategoryOptions(mappedCategoryOpts) if let sessionCategoryModeStr = configs["iosCategoryMode"] as? String, let mappedCategoryMode = SessionCategoryMode(rawValue: sessionCategoryModeStr) { sessionCategoryMode = mappedCategoryMode.mapConfigToAVAudioSessionCategoryMode() } try? AVAudioSession.sharedInstance().setActive(false) // Progressively opt into AVAudioSession policies for background audio // and AirPlay 2. if #available(iOS 13.0, *) { try? AVAudioSession.sharedInstance().setCategory(sessionCategory, mode: sessionCategoryMode, policy: .longFormAudio, options: sessionCategoryOptions) } else if #available(iOS 11.0, *) { try? AVAudioSession.sharedInstance().setCategory(sessionCategory, mode: sessionCategoryMode, policy: .longForm, options: sessionCategoryOptions) } else { try? AVAudioSession.sharedInstance().setCategory(sessionCategory, mode: sessionCategoryMode, options: sessionCategoryOptions) } } // MARK: - Bridged Methods @objc(setupPlayer:resolver:rejecter:) public func setupPlayer(config: [String: Any], resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { setupSessionCategory(config); if hasInitialized { resolve(NSNull()) return } setupInterruptionHandling(); // configure if player waits to play let autoWait: Bool = config["waitForBuffer"] as? Bool ?? false player.automaticallyWaitsToMinimizeStalling = autoWait // configure buffer size let minBuffer: TimeInterval = config["minBuffer"] as? TimeInterval ?? 0 player.bufferDuration = minBuffer // configure if control center metdata should auto update let autoUpdateMetadata: Bool = config["autoUpdateMetadata"] as? Bool ?? true player.automaticallyUpdateNowPlayingInfo = autoUpdateMetadata // setup event listeners player.remoteCommandController.handleChangePlaybackPositionCommand = { [weak self] event in if let event = event as? MPChangePlaybackPositionCommandEvent { self?.sendEvent(withName: "remote-seek", body: ["position": event.positionTime]) return MPRemoteCommandHandlerStatus.success } return MPRemoteCommandHandlerStatus.commandFailed } player.remoteCommandController.handleNextTrackCommand = { [weak self] _ in self?.sendEvent(withName: "remote-next", body: nil) return MPRemoteCommandHandlerStatus.success } player.remoteCommandController.handlePauseCommand = { [weak self] _ in self?.sendEvent(withName: "remote-pause", body: nil) return MPRemoteCommandHandlerStatus.success } player.remoteCommandController.handlePlayCommand = { [weak self] _ in self?.sendEvent(withName: "remote-play", body: nil) return MPRemoteCommandHandlerStatus.success } player.remoteCommandController.handlePreviousTrackCommand = { [weak self] _ in self?.sendEvent(withName: "remote-previous", body: nil) return MPRemoteCommandHandlerStatus.success } player.remoteCommandController.handleSkipBackwardCommand = { [weak self] event in if let command = event.command as? MPSkipIntervalCommand, let interval = command.preferredIntervals.first { self?.sendEvent(withName: "remote-jump-backward", body: ["interval": interval]) return MPRemoteCommandHandlerStatus.success } return MPRemoteCommandHandlerStatus.commandFailed } player.remoteCommandController.handleSkipForwardCommand = { [weak self] event in if let command = event.command as? MPSkipIntervalCommand, let interval = command.preferredIntervals.first { self?.sendEvent(withName: "remote-jump-forward", body: ["interval": interval]) return MPRemoteCommandHandlerStatus.success } return MPRemoteCommandHandlerStatus.commandFailed } player.remoteCommandController.handleStopCommand = { [weak self] _ in self?.sendEvent(withName: "remote-stop", body: nil) return MPRemoteCommandHandlerStatus.success } player.remoteCommandController.handleTogglePlayPauseCommand = { [weak self] _ in if self?.player.playerState == .paused { self?.sendEvent(withName: "remote-play", body: nil) return MPRemoteCommandHandlerStatus.success } self?.sendEvent(withName: "remote-pause", body: nil) return MPRemoteCommandHandlerStatus.success } player.remoteCommandController.handleLikeCommand = { [weak self] _ in self?.sendEvent(withName: "remote-like", body: nil) return MPRemoteCommandHandlerStatus.success } player.remoteCommandController.handleDislikeCommand = { [weak self] _ in self?.sendEvent(withName: "remote-dislike", body: nil) return MPRemoteCommandHandlerStatus.success } player.remoteCommandController.handleBookmarkCommand = { [weak self] _ in self?.sendEvent(withName: "remote-bookmark", body: nil) return MPRemoteCommandHandlerStatus.success } hasInitialized = true resolve(NSNull()) } @objc(destroy) public func destroy() { print("Destroying player") self.player.stop() self.player.nowPlayingInfoController.clear() try? AVAudioSession.sharedInstance().setActive(false) hasInitialized = false } @objc(updateOptions:resolver:rejecter:) public func update(options: [String: Any], resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { var capabilitiesStr = options["capabilities"] as? [String] ?? [] if (capabilitiesStr.contains("play") && capabilitiesStr.contains("pause")) { capabilitiesStr.append("togglePlayPause"); } let capabilities = capabilitiesStr.compactMap { Capability(rawValue: $0) } player.remoteCommands = capabilities.map { capability in capability.mapToPlayerCommand(forwardJumpInterval: options["forwardJumpInterval"] as? NSNumber, backwardJumpInterval: options["backwardJumpInterval"] as? NSNumber, likeOptions: options["likeOptions"] as? [String: Any], dislikeOptions: options["dislikeOptions"] as? [String: Any], bookmarkOptions: options["bookmarkOptions"] as? [String: Any]) } resolve(NSNull()) } @objc(add:before:resolver:rejecter:) public func add(trackDicts: [[String: Any]], before trackIndex: NSNumber, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { UIApplication.shared.beginReceivingRemoteControlEvents(); } var tracks = [Track]() for trackDict in trackDicts { guard let track = Track(dictionary: trackDict) else { reject("invalid_track_object", "Track is missing a required key", nil) return } tracks.append(track) } if (trackIndex.intValue > player.items.count) { reject("index_out_of_bounds", "The track index is out of bounds", nil) } else if trackIndex.intValue == -1 { // -1 means no index was passed and therefore should be inserted at the end. try? player.add(items: tracks, playWhenReady: false) } else { try? player.add(items: tracks, at: trackIndex.intValue) } resolve(NSNull()) } @objc(remove:resolver:rejecter:) public func remove(tracks indexes: [Int], resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Removing tracks:", indexes) for index in indexes { // we do not allow removal of the current item if index == player.currentIndex { continue } try? player.removeItem(at: index) } resolve(NSNull()) } @objc(removeUpcomingTracks:rejecter:) public func removeUpcomingTracks(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Removing upcoming tracks") player.removeUpcomingItems() resolve(NSNull()) } @objc(skip:resolver:rejecter:) public func skip(to trackIndex: NSNumber, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { if (trackIndex.intValue < 0 || trackIndex.intValue >= player.items.count) { reject("index_out_of_bounds", "The track index is out of bounds", nil) return } print("Skipping to track:", trackIndex) try? player.jumpToItem(atIndex: trackIndex.intValue, playWhenReady: player.playerState == .playing) resolve(NSNull()) } @objc(skipToNext:rejecter:) public func skipToNext(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Skipping to next track") do { try player.next() resolve(NSNull()) } catch (_) { reject("queue_exhausted", "There is no tracks left to play", nil) } } @objc(skipToPrevious:rejecter:) public func skipToPrevious(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Skipping to next track") do { try player.previous() resolve(NSNull()) } catch (_) { reject("no_previous_track", "There is no previous track", nil) } } @objc(reset:rejecter:) public func reset(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Resetting player.") player.stop() resolve(NSNull()) DispatchQueue.main.async { UIApplication.shared.endReceivingRemoteControlEvents(); } } @objc(play:rejecter:) public func play(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Starting/Resuming playback") DispatchQueue.main.async { try? AVAudioSession.sharedInstance().setActive(true) } player.play() resolve(NSNull()) } @objc(pause:rejecter:) public func pause(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Pausing playback") DispatchQueue.main.async { try? AVAudioSession.sharedInstance().setActive(false) } player.pause() resolve(NSNull()) } @objc(stop:rejecter:) public func stop(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Stopping playback") DispatchQueue.main.async { try? AVAudioSession.sharedInstance().setActive(false) } player.stop() resolve(NSNull()) } @objc(seekTo:resolver:rejecter:) public func seek(to time: Double, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Seeking to \(time) seconds") player.seek(to: time) resolve(NSNull()) } @objc(setRepeatMode:resolver:rejecter:) public func setRepeatMode(repeatMode: NSNumber, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { player.repeatMode = SwiftAudioEx.RepeatMode(rawValue: repeatMode.intValue) ?? .off resolve(NSNull()) } @objc(getRepeatMode:rejecter:) public func getRepeatMode(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Getting current repeatMode") resolve(player.repeatMode.rawValue) } @objc(setVolume:resolver:rejecter:) public func setVolume(level: Float, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Setting volume to \(level)") player.volume = level resolve(NSNull()) } @objc(getVolume:rejecter:) public func getVolume(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Getting current volume") resolve(player.volume) } @objc(setRate:resolver:rejecter:) public func setRate(rate: Float, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Setting rate to \(rate)") player.rate = rate resolve(NSNull()) } @objc(getRate:rejecter:) public func getRate(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Getting current rate") resolve(player.rate) } @objc(getTrack:resolver:rejecter:) public func getTrack(index: NSNumber, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { if (index.intValue >= 0 && index.intValue < player.items.count) { let track = player.items[index.intValue] resolve((track as? Track)?.toObject()) } else { resolve(NSNull()) } } @objc(getQueue:rejecter:) public func getQueue(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { let serializedQueue = player.items.map { ($0 as! Track).toObject() } resolve(serializedQueue) } @objc(getCurrentTrack:rejecter:) public func getCurrentTrack(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { let index = player.currentIndex if index < 0 || index >= player.items.count { resolve(NSNull()) } else { resolve(index) } } @objc(getDuration:rejecter:) public func getDuration(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { resolve(player.duration) } @objc(getBufferedPosition:rejecter:) public func getBufferedPosition(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { resolve(player.bufferedPosition) } @objc(getPosition:rejecter:) public func getPosition(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { resolve(player.currentTime) } @objc(getState:rejecter:) public func getState(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { resolve(player.playerState.rawValue) } @objc(updateMetadataForTrack:metadata:resolver:rejecter:) public func updateMetadata(for trackIndex: NSNumber, metadata: [String: Any], resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { if (trackIndex.intValue < 0 || trackIndex.intValue >= player.items.count) { reject("index_out_of_bounds", "The track index is out of bounds", nil) return } let track = player.items[trackIndex.intValue] as! Track track.updateMetadata(dictionary: metadata) if (player.currentIndex == trackIndex.intValue) { Metadata.update(for: player, with: metadata) } resolve(NSNull()) } @objc(clearNowPlayingMetadata:rejecter:) public func clearNowPlayingMetadata(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { player.nowPlayingInfoController.clear() } @objc(updateNowPlayingMetadata:resolver:rejecter:) public func updateNowPlayingMetadata(metadata: [String: Any], resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { Metadata.update(for: player, with: metadata) } // MARK: - QueuedAudioPlayer Event Handlers func handleAudioPlayerStateChange(state: AVPlayerWrapperState) { sendEvent(withName: "playback-state", body: ["state": state.rawValue]) } func handleAudioPlayerMetadataReceived(metadata: [AVMetadataItem]) { func getMetadataItem(forIdentifier: AVMetadataIdentifier) -> String { return AVMetadataItem.metadataItems(from: metadata, filteredByIdentifier: forIdentifier).first?.stringValue ?? "" } var source: String { switch metadata.first?.keySpace { case AVMetadataKeySpace.id3: return "id3" case AVMetadataKeySpace.icy: return "icy" case AVMetadataKeySpace.quickTimeMetadata: return "quicktime" case AVMetadataKeySpace.common: return "unknown" default: return "unknown" } } let album = getMetadataItem(forIdentifier: .commonIdentifierAlbumName) var artist = getMetadataItem(forIdentifier: .commonIdentifierArtist) var title = getMetadataItem(forIdentifier: .commonIdentifierTitle) var date = getMetadataItem(forIdentifier: .commonIdentifierCreationDate) var url = ""; var genre = ""; if (source == "icy") { url = getMetadataItem(forIdentifier: .icyMetadataStreamURL) } else if (source == "id3") { if (date.isEmpty) { date = getMetadataItem(forIdentifier: .id3MetadataDate) } genre = getMetadataItem(forIdentifier: .id3MetadataContentType) url = getMetadataItem(forIdentifier: .id3MetadataOfficialAudioSourceWebpage) if (url.isEmpty) { url = getMetadataItem(forIdentifier: .id3MetadataOfficialAudioFileWebpage) } if (url.isEmpty) { url = getMetadataItem(forIdentifier: .id3MetadataOfficialArtistWebpage) } } else if (source == "quicktime") { genre = getMetadataItem(forIdentifier: .quickTimeMetadataGenre) } // Detect ICY metadata and split title into artist & title: // - source should be either "unknown" (pre iOS 14) or "icy" (iOS 14 and above) // - we have a title, but no artist if ((source == "unknown" || source == "icy") && !title.isEmpty && artist.isEmpty) { if let index = title.range(of: " - ")?.lowerBound { artist = String(title.prefix(upTo: index)); title = String(title.suffix(from: title.index(index, offsetBy: 3))); } } var data : [String : String?] = [ "title": title.isEmpty ? nil : title, "url": url.isEmpty ? nil : url, "artist": artist.isEmpty ? nil : artist, "album": album.isEmpty ? nil : album, "date": date.isEmpty ? nil : date, "genre": genre.isEmpty ? nil : genre ] if (data.values.contains { $0 != nil }) { data["source"] = source sendEvent(withName: "playback-metadata-received", body: data) } } func handleAudioPlayerFailed(error: Error?) { sendEvent(withName: "playback-error", body: ["error": error?.localizedDescription]) } func handleAudioPlayerPlaybackEnded(reason: PlaybackEndedReason) { // fire an event for the queue ending if player.nextItems.count == 0 { sendEvent(withName: "playback-queue-ended", body: [ "track": player.currentIndex, "position": player.currentTime, ]) } // fire an event for the same track starting again switch player.repeatMode { case .track: handleAudioPlayerQueueIndexChange(previousIndex: player.currentIndex, nextIndex: player.currentIndex) default: break } } func handleAudioPlayerQueueIndexChange(previousIndex: Int?, nextIndex: Int?) { var dictionary: [String: Any] = [ "position": player.currentTime ] if let previousIndex = previousIndex { dictionary["track"] = previousIndex } if let nextIndex = nextIndex { dictionary["nextTrack"] = nextIndex } sendEvent(withName: "playback-track-changed", body: dictionary) } }
39.929429
161
0.639454
912fbe88f53ecf36e4676222211bc1711ff4c73e
1,235
// // planrightproTests.swift // planrightproTests // // Created by Edward Wilson on 2/20/22. // import XCTest @testable import planrightpro class planrightproTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. // Any test you write for XCTest can be annotated as throws and async. // Mark your test throws to produce an unexpected failure when your test encounters an uncaught error. // Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
33.378378
130
0.687449
2344e2b8c7713b4427818eb8628ede5cc345ce3d
2,418
// // DashboardViewController.swift // fujiko // // Created by Charlie Cai on 9/3/20. // Copyright © 2020 tickboxs. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxDataSources class DashboardViewController: ViewController<DashboardViewModel> { @IBOutlet weak var tableView: TableView! override func makeUI() { super.makeUI() title = R.string.i18n.dashboard() // Settings Button let settingsButtonItem: UIBarButtonItem = { let settingsButton = Button(type: .custom) settingsButton.rx.tap .asDriver() .drive(vm.input.settingsTapped) .disposed(by: disposeBag) settingsButton .setImage(R.image.settings()? .byResize(to: CGSize(width: 30, height: 30)), for: .normal) return UIBarButtonItem(customView: settingsButton) }() self.navigationItem.leftBarButtonItem = settingsButtonItem // Notifications Button let notificationsButtonItem: UIBarButtonItem = { let notificationsButton = Button(type: .custom) notificationsButton.rx.tap .asDriver() .drive(vm.input.notificationsTapped) .disposed(by: disposeBag) notificationsButton .setImage(R.image.notifications()? .byResize(to: CGSize(width: 35, height: 35)), for: .normal) return UIBarButtonItem(customView: notificationsButton) }() self.navigationItem.rightBarButtonItem = notificationsButtonItem tableView.register(R.nib.taskCell) } override func bindViewModel() { tableView.rx.itemSelected .asDriver() .drive(vm.input.taskTapped) .disposed(by: disposeBag) vm.output.tasks .asDriver(onErrorJustReturn: []) .drive(tableView.rx.items(cellIdentifier: R.reuseIdentifier.taskCell.identifier, cellType: TaskCell.self)) { (_, taskCellViewModel, taskCell) in taskCell.vm = taskCellViewModel } .disposed(by: disposeBag) vm.output.refreshing .asDriver() .drive(tableView.rx.isRefreshing) .disposed(by: disposeBag) } }
32.24
101
0.582713
08e586b1d90e41e91915a44d3e31942bb907cd18
1,699
// // Statu.swift // Model file Generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport import Foundation class Status : NSObject, NSCoding{ var cause : String! var code : Int! var message : String! override init() { } /** * Instantiate the instance using the passed dictionary values to set the properties values */ init(fromDictionary dictionary: NSDictionary){ cause = dictionary["cause"] as? String code = dictionary["code"] as? Int message = dictionary["message"] as? String } /** * Returns all the available property values in the form of NSDictionary object where the key is the approperiate json key and the value is the value of the corresponding property */ func toDictionary() -> NSDictionary { let dictionary = NSMutableDictionary() if cause != nil{ dictionary["cause"] = cause } if code != nil{ dictionary["code"] = code } if message != nil{ dictionary["message"] = message } return dictionary } /** * NSCoding required initializer. * Fills the data from the passed decoder */ @objc required init(coder aDecoder: NSCoder) { cause = aDecoder.decodeObjectForKey("cause") as? String code = aDecoder.decodeObjectForKey("code") as? Int message = aDecoder.decodeObjectForKey("message") as? String } /** * NSCoding required method. * Encodes mode properties into the decoder */ @objc func encodeWithCoder(aCoder: NSCoder) { if cause != nil{ aCoder.encodeObject(cause, forKey: "cause") } if code != nil{ aCoder.encodeObject(code, forKey: "code") } if message != nil{ aCoder.encodeObject(message, forKey: "message") } } }
22.653333
180
0.670394
e8160adc712fb19fbccef8421e36ac839059df32
13,427
/* FileManager.swift This source file is part of the SDGCornerstone open source project. https://sdggiesbrecht.github.io/SDGCornerstone Copyright ©2017–2021 Jeremy David Giesbrecht and the SDGCornerstone project contributors. Soli Deo gloria. Licensed under the Apache Licence, Version 2.0. See http://www.apache.org/licenses/LICENSE-2.0 for licence information. */ import Foundation import SDGControlFlow import SDGLogic #if !PLATFORM_LACKS_FOUNDATION_FILE_MANAGER extension FileManager { // MARK: - Domains internal static func possibleDebugDomain(_ domain: String) -> String { #if DEBUG return domain + ".debug" #else return domain #endif } // MARK: - Recommended File Locations /// A recommended location for file operations. /// /// For the temporary files used only transiently, use `FileManager.withTemporaryDirectory(appropriateFor:_:)` instead. public enum RecommendedLocation { /// Permanent, backed‐up storage for application‐related, internal‐use files that are hidden from the user. case applicationSupport /// For caches that are saved to improve performance. The operating system may empty this if it needs to create space. Do not save anything here that cannot be regenerated if necessary. case cache } private static var locations: [FileManager: [RecommendedLocation: URL]] = [:] private var locations: [RecommendedLocation: URL] { get { return FileManager.locations[self] ?? [:] } set { FileManager.locations[self] = newValue } } private func url(in location: RecommendedLocation, for domain: String) -> URL { let zoneURL = cached(in: &locations[location]) { let searchPath: FileManager.SearchPathDirectory switch location { case .applicationSupport: searchPath = .applicationSupportDirectory case .cache: searchPath = .cachesDirectory } do { return try url( for: searchPath, in: .userDomainMask, appropriateFor: nil, create: true ) } catch { do { // @exempt(from: tests) // Enable read queries even if directories could not be created, such as on a read‐only file system. return try url( for: searchPath, in: .userDomainMask, appropriateFor: nil, create: false ) } catch { preconditionFailure("\(error.localizedDescription)") } } } return zoneURL.appendingPathComponent(FileManager.possibleDebugDomain(domain)) } /// Returns a URL for the specified location and relative path in the application’s domain. /// /// - Parameters: /// - location: The location. /// - relativePath: The path. public func url(in location: RecommendedLocation, at relativePath: String) -> URL { return url(in: location, for: ProcessInfo.applicationDomain, at: relativePath) } /// Returns a URL for the specified location, domain and relative path. /// /// - Parameters: /// - location: The location. /// - domain: The domain. /// - relativePath: The path. public func url(in location: RecommendedLocation, for domain: String, at relativePath: String) -> URL { return url(in: location, for: domain).appendingPathComponent(relativePath) } /// Deletes everything in the specified location for the application domain. /// /// - Parameters: /// - location: The location. public func delete(_ location: RecommendedLocation) { delete(location, for: ProcessInfo.applicationDomain) } /// Deletes everything in the specified location and domain. /// /// - Parameters: /// - location: The location. /// - domain: The domain. public func delete(_ location: RecommendedLocation, for domain: String) { let folder = url(in: location, for: domain) try? removeItem(at: folder) } /// Performs an operation with a temporary directory. /// /// This method cleans up the directory its provides immediately after the operation completes. /// /// The directory will be in a location where the operating system will clean it up eventually in the event of a crash preventing the method from performing clean‐up itself. /// /// - Parameters: /// - destination: The approximate destination of any files that will be moved out of the temporary directory. The method will attempt to use a temporary directory on the same volume so the move can be made faster. Pass `nil` if it does not matter. /// - body: The body of the operation. /// - directory: The provided temporary directory. public func withTemporaryDirectory<Result>( appropriateFor destination: URL?, _ body: (_ directory: URL) throws -> Result ) rethrows -> Result { var directory: URL #if os(Android) // #workaround(Swift 5.3.2, .itemReplacementDirectory leads to illegal instruction.) directory = temporaryDirectory #else let volume = try? url( for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true ) if let itemReplacement = try? url( for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: volume, create: true ) { directory = itemReplacement } else { // @exempt(from: tests) macOS fails to find the preferred item replacement directory from time to time. if let anyVolume = try? url( for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: nil, create: true ) { directory = anyVolume } else { // @exempt(from: tests) if #available(macOS 10.12, iOS 10, watchOS 3, tvOS 10, *) { // @exempt(from: tests) directory = temporaryDirectory } else { // @exempt(from: tests) directory = URL(fileURLWithPath: NSTemporaryDirectory()) } } } #endif directory.appendPathComponent(UUID().uuidString) defer { try? removeItem(at: directory) } return try body(directory) } // MARK: - Unicode Path Representations /// Returns the URL with any path components adjusted to match their on‐disk Unicode representations. /// /// - Parameters: /// - url: The URL to adjust. public func existingRepresentation(of url: URL) -> URL { // Prevent checking outside the root. if url.path == "/" { return url } if (try? url.checkResourceIsReachable()) == true ∨ url.pathComponents.isEmpty { return url } else { let component = url.lastPathComponent let parent = existingRepresentation(of: url.deletingLastPathComponent()) for existing in (try? FileManager.default.contentsOfDirectory( at: parent, includingPropertiesForKeys: nil )) ?? [] { let onDisk = existing.lastPathComponent if onDisk == component { // @exempt(from: tests) Not reachable from some file systems. return parent.appendingPathComponent(onDisk) } } return parent.appendingPathComponent(component) } } // MARK: - Making Changes to the File System /// Creates a directory at the specified location. /// /// This method creates any missing intermediate directories. All directories are created with the default attributes. /// /// This method will automatically use the on disk Unicode representation of any existing path components. /// /// - Parameters: /// - location: The location where the directory should be created. public func createDirectory(at location: URL) throws { return try createDirectory( at: existingRepresentation(of: location), withIntermediateDirectories: true, attributes: nil ) } /// Moves the item at the specified source to the specified destination, creating intermediate directories if necessary. /// /// This method will automatically use the on disk Unicode representation of any existing path components. /// /// - Parameters: /// - source: The URL of the source item. /// - destination: The destination URL. public func move(_ source: URL, to destination: URL) throws { try createDirectory(at: destination.deletingLastPathComponent()) try moveItem( at: existingRepresentation(of: source), to: existingRepresentation(of: destination) ) } /// Copies the item at the specified source URL to the specified destination URL, creating intermediate directories if necessary. /// /// This method will automatically use the on disk Unicode representation of any existing path components. /// /// - Parameters: /// - source: The URL of the source item. /// - destination: The destination URL. public func copy(_ source: URL, to destination: URL) throws { try createDirectory(at: destination.deletingLastPathComponent()) try copyItem( at: existingRepresentation(of: source), to: existingRepresentation(of: destination) ) } // MARK: - Enumerating Files /// Returns a list files and directories located immediately inside in the specified directory. /// /// This method will automatically use the on disk Unicode representation of any existing path components. /// /// - Parameters: /// - directory: The root directory for the search. public func contents(ofDirectory directory: URL) throws -> [URL] { return try contentsOfDirectory( at: existingRepresentation(of: directory), includingPropertiesForKeys: nil, options: [] ) } private static let unknownFileReadingError = NSError( domain: NSCocoaErrorDomain, code: NSFileReadUnknownError, userInfo: nil ) /// Returns a list of all files in the specified directory, including those nested within subdirectories. /// /// Directories themselves are not returned—only the files they contain. /// /// - Parameters: /// - directory: The root directory for the search. public func deepFileEnumeration(in directory: URL) throws -> [URL] { do { return try _deepFileEnumeration(in: directory) } catch { // @exempt(from: tests) // Fallback for Windows, which errors if the URL wasn’t marked as a directory. let originalError = error let asDirectory = directory.deletingLastPathComponent().appendingPathComponent( directory.lastPathComponent, isDirectory: true ) do { return try _deepFileEnumeration(in: asDirectory) } catch { throw originalError } } } private func _deepFileEnumeration(in directory: URL) throws -> [URL] { var failureReason: Error? // Thrown after enumeration stops. (See below.) guard let enumerator = FileManager.default.enumerator( at: existingRepresentation(of: directory), includingPropertiesForKeys: [.isDirectoryKey], options: [], errorHandler: { (_, error: Error) -> Bool in // @exempt(from: tests) // @exempt(from: tests) It is unknown what circumstances would actually cause an error. failureReason = error return false // Stop. } ) else { // @exempt(from: tests) // @exempt(from: tests) It is unknown what circumstances would actually result in a `nil` enumerator being returned. throw FileManager.unknownFileReadingError } var result: [URL] = [] for object in enumerator { guard let url = object as? URL else { throw FileManager.unknownFileReadingError // @exempt(from: tests) //It is unknown why something other than a URL would be returned. } var objCBool: ObjCBool = false let isDirectory = FileManager.default.fileExists(atPath: url.path, isDirectory: &objCBool) ∧ objCBool.boolValue if ¬isDirectory { // Skip directories. result.append(url) } } if let error = failureReason { throw error // @exempt(from: tests) // It is unknown what circumstances would actually cause an error. } return result } // MARK: - Working Directory /// Executes the closure in the specified directory. /// /// The directory will be automatically created if necessary. /// /// - Parameters: /// - directory: The directory in which to execute the closure. /// - closure: The closure. public func `do`(in directory: URL, closure: () throws -> Void) throws { try createDirectory(at: directory) let previous = currentDirectoryPath _ = changeCurrentDirectoryPath(directory.path) defer { _ = changeCurrentDirectoryPath(previous) } try closure() } } #endif
34.875325
256
0.630297
01453166fcc3607b75f3a67cb6d54ac9e8216792
4,534
// // ViewController.swift // Mwap // // Created by Justin Loew on 1/16/17. // Copyright © 2017 Justin Loew. All rights reserved. // import UIKit import MapKit class ViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var locationLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Disable scrolling and zooming the map, since we don't have a button // to re-center the map on the user's current location. mapView.isZoomEnabled = false mapView.isScrollEnabled = false mapView.isRotateEnabled = false mapView.isPitchEnabled = false // Set up the map view to show the user's location. mapView.showsUserLocation = true mapView.userTrackingMode = .followWithHeading // Set the map view's delegate. mapView.delegate = self } private let locationManager = CLLocationManager() override func viewDidAppear(_ animated: Bool) { // Request permission to use the user's location. locationManager.requestWhenInUseAuthorization() } // Update the printed location on screen based on a user's location. func updateLocationLabel(for userLocation: MKUserLocation) { // Make sure we have a valid location. guard let location = userLocation.location else { locationLabel.text = "Unable to determine location." return } // For these descriptions, type `±' with option-shift-+ and type `˚' (degree symbol) with option-k // Get GPS coordinates, altitude, speed, and heading. let gpsDescription: String let altitudeDescription: String let speedDescription: String let headingDescription: String let orientationDescription: String let lastUpdatedDescription: String /// Pretty print a number by trimming off excess decimal points. func pretty(_ n: Double, numDigits: Int = 2) -> String { // Set up a number formatter to pretty print these numbers. let fmt = NumberFormatter() fmt.maximumFractionDigits = numDigits // Apply the number formatter to the number. return fmt.string(from: NSNumber(value: n))! } /// Pretty print a date. func pretty(_ date: Date) -> String { // Set up a date formatter to pretty print the date. let fmt = DateFormatter() fmt.dateStyle = .short fmt.timeStyle = .medium // Apply the date formatter to the date. return fmt.string(from: date) } let coords = location.coordinate gpsDescription = "<\(pretty(coords.latitude, numDigits: 5)), \(pretty(coords.longitude, numDigits: 5))> ± \(Int(location.horizontalAccuracy)) m" altitudeDescription = "\(pretty(location.altitude)) m ± \(Int(location.verticalAccuracy)) m" // Handle the speed. if location.speed >= 0 { // Convert m/s to mph to figure out the speed. let MPH_PER_MS = 2.23694 let speed_mph = location.speed * MPH_PER_MS speedDescription = "\(pretty(location.speed)) m/s (\(pretty(speed_mph)) mph)" } else { // Invalid speed. speedDescription = "Unknown" } // Heading is the direction in which the device is traveling. if location.course >= 0 { headingDescription = "\(pretty(location.course, numDigits: 1))˚" } else { // Invalid heading. headingDescription = "Unknown" } // Get the device orientation (which way the device is pointing). if let deviceHeading = userLocation.heading, deviceHeading.headingAccuracy >= 0 { orientationDescription = "\(pretty(deviceHeading.trueHeading, numDigits: 1))˚ ± \(pretty(deviceHeading.headingAccuracy, numDigits: 1))˚" } else { orientationDescription = "Unknown" } lastUpdatedDescription = "\(pretty(location.timestamp))" // Combine the various descriptions and make them look nice. let descriptions = [ "Location: \(gpsDescription)", "Altitude: \(altitudeDescription)", "Speed: \(speedDescription)", "Heading: \(headingDescription)", "Orientation: \(orientationDescription)", "Last Updated: \(lastUpdatedDescription)", ] let completeDescription = descriptions.joined(separator: "\n") // Finally, put the new description on screen. locationLabel.text = completeDescription } } extension ViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { // This function gets called every time the user's location changes. updateLocationLabel(for: userLocation) } func mapView(_ mapView: MKMapView, didFailToLocateUserWithError error: Error) { print(error) } }
31.929577
146
0.713057
642e499a642aa13b3800162ba2564e0feb10d868
2,034
// // HasStateTitle.swift // EasyRefresher // // Created by Pircate([email protected]) on 2019/5/8 // Copyright © 2019 Pircate. All rights reserved. // import Foundation public protocol HasStateTitle: class { var stateTitles: [RefreshState: String] { get set } var stateAttributedTitles: [RefreshState: NSAttributedString] { get set } /// Sets the title to use for the specified state. /// - Parameters: /// - title: The title to use for the specified state. /// - state: The state that uses the specified title. The possible values are described in RefreshState. func setTitle(_ title: String?, for state: RefreshState) /// Sets the styled title to use for the specified state. /// - Parameters: /// - title: The styled text string to use for the title. /// - state: The state that uses the specified title. The possible values are described in RefreshState. func setAttributedTitle(_ title: NSAttributedString?, for state: RefreshState) /// Returns the title associated with the specified state. /// - Parameter state: The state that uses the title. The possible values are described in RefreshState. func title(for state: RefreshState) -> String? /// Returns the styled title associated with the specified state. /// - Parameter state: The state that uses the styled title. The possible values are described in RefreshState. func attributedTitle(for state: RefreshState) -> NSAttributedString? } public extension HasStateTitle { func setTitle(_ title: String?, for state: RefreshState) { stateTitles[state] = title } func setAttributedTitle(_ title: NSAttributedString?, for state: RefreshState) { stateAttributedTitles[state] = title } func title(for state: RefreshState) -> String? { return stateTitles[state] } func attributedTitle(for state: RefreshState) -> NSAttributedString? { return stateAttributedTitles[state] } }
36.321429
115
0.688299
67c52db95e8ea1860f5fbdacecb1661be44a2ada
27,322
// // ItemBaseController.swift // ImageViewer // // Created by Kristian Angyal on 01/08/2016. // Copyright © 2016 MailOnline. All rights reserved. // import UIKit public protocol ItemView { var image: UIImage? { get set } } open class ItemBaseController<T: UIView>: UIViewController, ItemController, UIGestureRecognizerDelegate, UIScrollViewDelegate where T: ItemView { //UI public var itemView = T() let scrollView = UIScrollView() let activityIndicatorView = UIActivityIndicatorView(style: .white) //DELEGATE / DATASOURCE weak public var delegate: ItemControllerDelegate? weak public var displacedViewsDataSource: GalleryDisplacedViewsDataSource? //STATE public let index: Int public var isInitialController = false let itemCount: Int var swipingToDismiss: SwipeToDismiss? fileprivate var isAnimating = false fileprivate var fetchImageBlock: FetchImageBlock //CONFIGURATION fileprivate var presentationStyle = GalleryPresentationStyle.displacement fileprivate var doubleTapToZoomDuration = 0.15 fileprivate var displacementDuration: TimeInterval = 0.55 fileprivate var reverseDisplacementDuration: TimeInterval = 0.25 fileprivate var itemFadeDuration: TimeInterval = 0.3 fileprivate var displacementTimingCurve: UIView.AnimationCurve = .linear fileprivate var displacementSpringBounce: CGFloat = 0.7 fileprivate let minimumZoomScale: CGFloat = 1 fileprivate var maximumZoomScale: CGFloat = 8 fileprivate var pagingMode: GalleryPagingMode = .standard fileprivate var thresholdVelocity: CGFloat = 500 // The speed of swipe needs to be at least this amount of pixels per second for the swipe to finish dismissal. fileprivate var displacementKeepOriginalInPlace = false fileprivate var displacementInsetMargin: CGFloat = 50 fileprivate var swipeToDismissMode = GallerySwipeToDismissMode.always fileprivate var activityViewByLongPress = true /// INTERACTIONS fileprivate var singleTapRecognizer: UITapGestureRecognizer? fileprivate var longPressRecognizer: UILongPressGestureRecognizer? fileprivate let doubleTapRecognizer = UITapGestureRecognizer() fileprivate let swipeToDismissRecognizer = UIPanGestureRecognizer() // TRANSITIONS fileprivate var swipeToDismissTransition: GallerySwipeToDismissTransition? // MARK: - Initializers public init(index: Int, itemCount: Int, fetchImageBlock: @escaping FetchImageBlock, configuration: GalleryConfiguration, isInitialController: Bool = false) { self.index = index self.itemCount = itemCount self.isInitialController = isInitialController self.fetchImageBlock = fetchImageBlock for item in configuration { switch item { case .swipeToDismissThresholdVelocity(let velocity): thresholdVelocity = velocity case .doubleTapToZoomDuration(let duration): doubleTapToZoomDuration = duration case .presentationStyle(let style): presentationStyle = style case .pagingMode(let mode): pagingMode = mode case .displacementDuration(let duration): displacementDuration = duration case .reverseDisplacementDuration(let duration): reverseDisplacementDuration = duration case .displacementTimingCurve(let curve): displacementTimingCurve = curve case .maximumZoomScale(let scale): maximumZoomScale = scale case .itemFadeDuration(let duration): itemFadeDuration = duration case .displacementKeepOriginalInPlace(let keep): displacementKeepOriginalInPlace = keep case .displacementInsetMargin(let margin): displacementInsetMargin = margin case .swipeToDismissMode(let mode): swipeToDismissMode = mode case .activityViewByLongPress(let enabled): activityViewByLongPress = enabled case .spinnerColor(let color): activityIndicatorView.color = color case .spinnerStyle(let style): activityIndicatorView.style = style case .displacementTransitionStyle(let style): switch style { case .springBounce(let bounce): displacementSpringBounce = bounce case .normal: displacementSpringBounce = 1 } default: break } } super.init(nibName: nil, bundle: nil) self.modalPresentationStyle = .custom self.itemView.isHidden = isInitialController configureScrollView() configureGestureRecognizers() activityIndicatorView.hidesWhenStopped = true } @available (*, unavailable) required public init?(coder aDecoder: NSCoder) { fatalError() } deinit { self.scrollView.removeObserver(self, forKeyPath: "contentOffset") } // MARK: - Configuration fileprivate func configureScrollView() { scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.decelerationRate = .fast scrollView.contentInset = UIEdgeInsets.zero scrollView.contentOffset = CGPoint.zero scrollView.minimumZoomScale = minimumZoomScale scrollView.maximumZoomScale = max(maximumZoomScale, aspectFillZoomScale(forBoundingSize: self.view.bounds.size, contentSize: itemView.bounds.size)) scrollView.delegate = self scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil) } func configureGestureRecognizers() { doubleTapRecognizer.addTarget(self, action: #selector(scrollViewDidDoubleTap(_:))) doubleTapRecognizer.numberOfTapsRequired = 2 scrollView.addGestureRecognizer(doubleTapRecognizer) let singleTapRecognizer = UITapGestureRecognizer() singleTapRecognizer.addTarget(self, action: #selector(scrollViewDidSingleTap)) singleTapRecognizer.numberOfTapsRequired = 1 scrollView.addGestureRecognizer(singleTapRecognizer) singleTapRecognizer.require(toFail: doubleTapRecognizer) self.singleTapRecognizer = singleTapRecognizer if activityViewByLongPress == true { let longPressRecognizer = UILongPressGestureRecognizer() longPressRecognizer.addTarget(self, action: #selector(scrollViewDidLongPress)) scrollView.addGestureRecognizer(longPressRecognizer) self.longPressRecognizer = longPressRecognizer } if swipeToDismissMode != .never { swipeToDismissRecognizer.addTarget(self, action: #selector(scrollViewDidSwipeToDismiss)) swipeToDismissRecognizer.delegate = self view.addGestureRecognizer(swipeToDismissRecognizer) swipeToDismissRecognizer.require(toFail: doubleTapRecognizer) } } fileprivate func createViewHierarchy() { self.view.addSubview(scrollView) scrollView.addSubview(itemView) activityIndicatorView.startAnimating() view.addSubview(activityIndicatorView) } // MARK: - View Controller Lifecycle override open func viewDidLoad() { super.viewDidLoad() createViewHierarchy() fetchImage() } public func fetchImage() { fetchImageBlock { [weak self] image in if let image = image { DispatchQueue.main.async { self?.activityIndicatorView.stopAnimating() var itemView = self?.itemView itemView?.image = image itemView?.isAccessibilityElement = image.isAccessibilityElement itemView?.accessibilityLabel = image.accessibilityLabel itemView?.accessibilityTraits = image.accessibilityTraits self?.view.setNeedsLayout() self?.view.layoutIfNeeded() } } } } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.delegate?.itemControllerWillAppear(self) } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.delegate?.itemControllerDidAppear(self) } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.delegate?.itemControllerWillDisappear(self) } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() scrollView.frame = self.view.bounds activityIndicatorView.center = view.boundsCenter if let size = itemView.image?.size , size != CGSize.zero { let aspectFitItemSize = aspectFitSize(forContentOfSize: size, inBounds: self.scrollView.bounds.size) itemView.bounds.size = aspectFitItemSize scrollView.contentSize = itemView.bounds.size itemView.center = scrollView.boundsCenter } } public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return itemView } // MARK: - Scroll View delegate methods public func scrollViewDidZoom(_ scrollView: UIScrollView) { itemView.center = contentCenter(forBoundingSize: scrollView.bounds.size, contentSize: scrollView.contentSize) } @objc func scrollViewDidSingleTap() { self.delegate?.itemControllerDidSingleTap(self) } @objc func scrollViewDidLongPress() { self.delegate?.itemControllerDidLongPress(self, in: itemView) } @objc func scrollViewDidDoubleTap(_ recognizer: UITapGestureRecognizer) { let touchPoint = recognizer.location(ofTouch: 0, in: itemView) let aspectFillScale = aspectFillZoomScale(forBoundingSize: scrollView.bounds.size, contentSize: itemView.bounds.size) if (scrollView.zoomScale == 1.0 || scrollView.zoomScale > aspectFillScale) { let zoomRectangle = zoomRect(ForScrollView: scrollView, scale: aspectFillScale, center: touchPoint) UIView.animate(withDuration: doubleTapToZoomDuration, animations: { [weak self] in self?.scrollView.zoom(to: zoomRectangle, animated: false) }) } else { UIView.animate(withDuration: doubleTapToZoomDuration, animations: { [weak self] in self?.scrollView.setZoomScale(1.0, animated: false) }) } } @objc func scrollViewDidSwipeToDismiss(_ recognizer: UIPanGestureRecognizer) { /// A deliberate UX decision...you have to zoom back in to scale 1 to be able to swipe to dismiss. It is difficult for the user to swipe to dismiss from images larger then screen bounds because almost all the time it's not swiping to dismiss but instead panning a zoomed in picture on the canvas. guard scrollView.zoomScale == scrollView.minimumZoomScale else { return } let currentVelocity = recognizer.velocity(in: self.view) let currentTouchPoint = recognizer.translation(in: view) if swipingToDismiss == nil { swipingToDismiss = (abs(currentVelocity.x) > abs(currentVelocity.y)) ? .horizontal : .vertical } guard let swipingToDismissInProgress = swipingToDismiss else { return } switch recognizer.state { case .began: swipeToDismissTransition = GallerySwipeToDismissTransition(scrollView: self.scrollView) case .changed: self.handleSwipeToDismissInProgress(swipingToDismissInProgress, forTouchPoint: currentTouchPoint) case .ended: self.handleSwipeToDismissEnded(swipingToDismissInProgress, finalVelocity: currentVelocity, finalTouchPoint: currentTouchPoint) default: break } } // MARK: - Swipe To Dismiss func handleSwipeToDismissInProgress(_ swipeOrientation: SwipeToDismiss, forTouchPoint touchPoint: CGPoint) { switch (swipeOrientation, index) { case (.horizontal, 0) where self.itemCount != 1: /// edge case horizontal first index - limits the swipe to dismiss to HORIZONTAL RIGHT direction. swipeToDismissTransition?.updateInteractiveTransition(horizontalOffset: min(0, -touchPoint.x)) case (.horizontal, self.itemCount - 1) where self.itemCount != 1: /// edge case horizontal last index - limits the swipe to dismiss to HORIZONTAL LEFT direction. swipeToDismissTransition?.updateInteractiveTransition(horizontalOffset: max(0, -touchPoint.x)) case (.horizontal, _): swipeToDismissTransition?.updateInteractiveTransition(horizontalOffset: -touchPoint.x) // all the rest case (.vertical, _): swipeToDismissTransition?.updateInteractiveTransition(verticalOffset: -touchPoint.y) // all the rest } } func handleSwipeToDismissEnded(_ swipeOrientation: SwipeToDismiss, finalVelocity velocity: CGPoint, finalTouchPoint touchPoint: CGPoint) { let maxIndex = self.itemCount - 1 let swipeToDismissCompletionBlock = { [weak self] in UIApplication.applicationWindow.windowLevel = .normal self?.swipingToDismiss = nil self?.delegate?.itemControllerDidFinishSwipeToDismissSuccessfully() } switch (swipeOrientation, index) { /// Any item VERTICAL UP direction case (.vertical, _) where velocity.y < -thresholdVelocity: swipeToDismissTransition?.finishInteractiveTransition(swipeOrientation, touchPoint: touchPoint.y, targetOffset: (view.bounds.height / 2) + (itemView.bounds.height / 2), escapeVelocity: velocity.y, completion: swipeToDismissCompletionBlock) /// Any item VERTICAL DOWN direction case (.vertical, _) where thresholdVelocity < velocity.y: swipeToDismissTransition?.finishInteractiveTransition(swipeOrientation, touchPoint: touchPoint.y, targetOffset: -(view.bounds.height / 2) - (itemView.bounds.height / 2), escapeVelocity: velocity.y, completion: swipeToDismissCompletionBlock) /// First item HORIZONTAL RIGHT direction case (.horizontal, 0) where thresholdVelocity < velocity.x: swipeToDismissTransition?.finishInteractiveTransition(swipeOrientation, touchPoint: touchPoint.x, targetOffset: -(view.bounds.width / 2) - (itemView.bounds.width / 2), escapeVelocity: velocity.x, completion: swipeToDismissCompletionBlock) /// Last item HORIZONTAL LEFT direction case (.horizontal, maxIndex) where velocity.x < -thresholdVelocity: swipeToDismissTransition?.finishInteractiveTransition(swipeOrientation, touchPoint: touchPoint.x, targetOffset: (view.bounds.width / 2) + (itemView.bounds.width / 2), escapeVelocity: velocity.x, completion: swipeToDismissCompletionBlock) ///If none of the above select cases, we cancel. default: swipeToDismissTransition?.cancelTransition() { [weak self] in self?.swipingToDismiss = nil } } } func animateDisplacedImageToOriginalPosition(_ duration: TimeInterval, completion: ((Bool) -> Void)?) { guard (self.isAnimating == false) else { return } isAnimating = true UIView.animate(withDuration: duration, animations: { [weak self] in self?.scrollView.zoomScale = self!.scrollView.minimumZoomScale if UIApplication.isPortraitOnly { self?.itemView.transform = windowRotationTransform().inverted() } }, completion: { [weak self] finished in completion?(finished) if finished { UIApplication.applicationWindow.windowLevel = UIWindow.Level.normal self?.isAnimating = false } }) } // MARK: - Present/Dismiss transitions public func presentItem(alongsideAnimation: () -> Void, completion: @escaping () -> Void) { guard isAnimating == false else { return } isAnimating = true alongsideAnimation() if var displacedView = displacedViewsDataSource?.provideDisplacementItem(atIndex: index), let image = displacedView.image { if presentationStyle == .displacement { //Prepare the animated imageView let animatedImageView = displacedView.imageView() //rotate the imageView to starting angle if UIApplication.isPortraitOnly == true { animatedImageView.transform = deviceRotationTransform() } //position the image view to starting center animatedImageView.center = displacedView.convert(displacedView.boundsCenter, to: self.view) animatedImageView.clipsToBounds = true self.view.addSubview(animatedImageView) if displacementKeepOriginalInPlace == false { displacedView.isHidden = true } UIView.animate(withDuration: displacementDuration, delay: 0, usingSpringWithDamping: displacementSpringBounce, initialSpringVelocity: 1, options: .curveEaseIn, animations: { [weak self] in if UIApplication.isPortraitOnly == true { animatedImageView.transform = CGAffineTransform.identity } /// Animate it into the center (with optionally rotating) - that basically includes changing the size and position animatedImageView.bounds.size = self?.displacementTargetSize(forSize: image.size) ?? image.size animatedImageView.center = self?.view.boundsCenter ?? CGPoint.zero }, completion: { [weak self] _ in self?.itemView.isHidden = false displacedView.isHidden = false animatedImageView.removeFromSuperview() self?.isAnimating = false completion() }) } } else { itemView.alpha = 0 itemView.isHidden = false UIView.animate(withDuration: itemFadeDuration, animations: { [weak self] in self?.itemView.alpha = 1 }, completion: { [weak self] _ in completion() self?.isAnimating = false }) } } func displacementTargetSize(forSize size: CGSize) -> CGSize { let boundingSize = rotationAdjustedBounds().size return aspectFitSize(forContentOfSize: size, inBounds: boundingSize) } func findVisibleDisplacedView() -> DisplaceableView? { guard let displacedView = displacedViewsDataSource?.provideDisplacementItem(atIndex: index) else { return nil } let displacedViewFrame = displacedView.frameInCoordinatesOfScreen() let validAreaFrame = self.view.frame.insetBy(dx: displacementInsetMargin, dy: displacementInsetMargin) let isVisibleEnough = displacedViewFrame.intersects(validAreaFrame) return isVisibleEnough ? displacedView : nil } public func dismissItem(alongsideAnimation: () -> Void, completion: @escaping () -> Void) { guard isAnimating == false else { return } isAnimating = true alongsideAnimation() switch presentationStyle { case .displacement: if var displacedView = self.findVisibleDisplacedView() { if displacementKeepOriginalInPlace == false { displacedView.isHidden = true } UIView.animate(withDuration: reverseDisplacementDuration, animations: { [weak self] in self?.scrollView.zoomScale = 1 //rotate the image view if UIApplication.isPortraitOnly == true { self?.itemView.transform = deviceRotationTransform() } //position the image view to starting center self?.itemView.bounds = displacedView.bounds self?.itemView.center = displacedView.convert(displacedView.boundsCenter, to: self!.view) self?.itemView.clipsToBounds = true self?.itemView.contentMode = displacedView.contentMode }, completion: { [weak self] _ in self?.isAnimating = false displacedView.isHidden = false completion() }) } else { fallthrough } case .fade: UIView.animate(withDuration: itemFadeDuration, animations: { [weak self] in self?.itemView.alpha = 0 }, completion: { [weak self] _ in self?.isAnimating = false completion() }) } } // MARK: - Arcane stuff /// This resolves which of the two pan gesture recognizers should kick in. There is one built in the GalleryViewController (as it is a UIPageViewController subclass), and another one is added as part of item controller. When we pan, we need to decide whether it constitutes a horizontal paging gesture, or a horizontal swipe-to-dismiss gesture. /// All the logic is from the perspective of SwipeToDismissRecognizer - should it kick in (or let the paging recognizer page)? public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { /// We only care about the swipe to dismiss gesture recognizer, not the built-in pan recognizer that handles paging. guard gestureRecognizer == swipeToDismissRecognizer else { return false } /// The velocity vector will help us make the right decision let velocity = swipeToDismissRecognizer.velocity(in: swipeToDismissRecognizer.view) ///A bit of paranoia guard velocity.orientation != .none else { return false } /// We continue if the swipe is horizontal, otherwise it's Vertical and it is swipe to dismiss. guard velocity.orientation == .horizontal else { return swipeToDismissMode.contains(.vertical) } /// A special case for horizontal "swipe to dismiss" is when the gallery has carousel mode OFF, then it is possible to reach the beginning or the end of image set while paging. Paging will stop at index = 0 or at index.max. In this case we allow to jump out from the gallery also via horizontal swipe to dismiss. if (self.index == 0 && velocity.direction == .right) || (self.index == self.itemCount - 1 && velocity.direction == .left) { return (pagingMode == .standard && swipeToDismissMode.contains(.horizontal)) } return false } // Reports the continuous progress of Swipe To Dismiss to the Gallery View Controller override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { guard let swipingToDismissInProgress = swipingToDismiss else { return } guard keyPath == "contentOffset" else { return } let distanceToEdge: CGFloat let percentDistance: CGFloat switch swipingToDismissInProgress { case .horizontal: distanceToEdge = (scrollView.bounds.width / 2) + (itemView.bounds.width / 2) percentDistance = abs(scrollView.contentOffset.x / distanceToEdge) case .vertical: distanceToEdge = (scrollView.bounds.height / 2) + (itemView.bounds.height / 2) percentDistance = abs(scrollView.contentOffset.y / distanceToEdge) } if let delegate = self.delegate { delegate.itemController(self, didSwipeToDismissWithDistanceToEdge: percentDistance) } } public func closeDecorationViews(_ duration: TimeInterval) { // stub } }
43.094637
348
0.588134
912edf110106b5439224b7f27466770a9d9b4b53
451
// // DocumentModel.swift // ChromaProjectApp // // Created by José Servet Font on 28/12/14. // Copyright (c) 2014 ByBDesigns. All rights reserved. // import Foundation struct DocumentModel { var documents = [ChromaDocument]() var count: Int { return self.documents.count } init(saveSettings: SaveSettings) { switch saveSettings { case .SaveLocally: break case .SaveInCloud: break default: break } } }
13.666667
55
0.665188
e5f6113cfe6c9a81e7ee17e8b09c3ea7ba78eec8
858
import Foundation import VoxeetSDK internal extension VTSpatialDirection { /// Creates instance of the class from react model. /// - Parameter dictionary: react model dictionary /// - Returns: VTSpatialDirection static func create(with dictionary: [String: Any]) -> VTSpatialDirection { return VTSpatialDirection(x: dictionary.value(for: Keys.x) ?? 0, y: dictionary.value(for: Keys.y) ?? 0, z: dictionary.value(for: Keys.z) ?? 0) } } // MARK: - ReactModelMappable extension VTSpatialDirection: ReactModelMappable { func toReactModel() -> ReactModelType { return [ Keys.x: x, Keys.y: y, Keys.z: z ].mapKeysToRawValue() } } // MARK: - ReactModel Keys private enum Keys: String { case x, y, z }
26
78
0.59324
2399c0400274948c6e1095f6e3bf4612843ff10b
739
// // ExchangeRates.swift // Baluchon // // Created by fred on 29/12/2021. // import Foundation struct Rate: Decodable { enum MainKeys: String, CodingKey { case timestamp case rates enum RatesKeys: String, CodingKey { case USD } } var timestamp: Int var USD: Double init(from decoder: Decoder) throws { /// main container let container = try decoder.container(keyedBy: MainKeys.self) self.timestamp = try container.decode(Int.self, forKey: .timestamp) let RatesContainer = try container.nestedContainer(keyedBy: MainKeys.RatesKeys.self, forKey: .rates) self.USD = try RatesContainer.decode(Double.self, forKey: .USD) } }
22.393939
108
0.637348
ccac005fbc2651c1640e23a27fdbe22cbb2a0018
418
// // BluetoothThing+.swift // BluetoothThingTests // // Created by Antonio Yip on 7/03/20. // Copyright © 2020 Antonio Yip. All rights reserved. // import Foundation @testable import BluetoothThing extension BluetoothThing { convenience init(id: UUID, name: String? = nil, serialNumber: Data? = nil) { self.init(id: id, name: name) self.characteristics[.serialNumber] = serialNumber } }
23.222222
80
0.686603
22729aa08ba4aa1a4b8a14865e2efa2c11abb8fa
488
// // TokenProtocol+Map.swift // Ogma // // Created by Mathias Quintero on 4/23/19. // import Foundation extension Hashable { /// Returns a Parser that matches the Token to a Value of T public func map<T>(_ transform: @escaping () throws -> T) -> AnyParser<Self, T> { return parser.map(transform) } /// Returns a Parser that matches the Token to a Value of T public func map<T>(to value: T) -> AnyParser<Self, T> { return map { value } } }
21.217391
85
0.622951
87a05595288f63869e6d7e9248373adf1f3a5665
643
// // UIScrollView-Extension.swift // QiuGuo // // Created by cuirhong on 2017/6/16. // Copyright © 2017年 qiuyoukeji. All rights reserved. // import Foundation import UIKit @objc public extension UIScrollView{ @objc convenience init(frame:CGRect=CGRect.zero,showsVerticalScrollIndicator:Bool=true,showsHorizontalScrollIndicator:Bool=true,isPage:Bool=false){ self.init(frame: frame) isPagingEnabled = isPage self.showsVerticalScrollIndicator = showsVerticalScrollIndicator self.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator } }
20.09375
150
0.698289
619de4da96def0769920b15f53d8568464252db4
2,005
// // ViewController.swift // SMNetworkManager // // Created by [email protected] on 02/10/2020. // Copyright (c) 2020 [email protected]. All rights reserved. // import UIKit import SMNetworkManager class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let button: UIButton = { let button = UIButton(frame: .zero) button.titleLabel?.text = "hey tere" button.translatesAutoresizingMaskIntoConstraints = false return button }() button.addTarget(self, action: #selector(trigger), for: .touchUpInside) self.view.addSubview(button) button.widthAnchor.constraint(equalToConstant: 200).isActive = true button.heightAnchor.constraint(equalToConstant: 200).isActive = true button.backgroundColor = .black } @objc func trigger() { var request = ReqClass() request.category = "Sports" request.country = "IN" request.page = "1" request.pageSize = "10" SMNetworkManager.headers = [:] let API: String = "https://jsonplaceholder.typicode.com/posts" self.errorAlert(title: "Edhi da title", description: "Lets do this", alertType: .promtWithReportToDeveloper(action1TItle: "OK", action2Title: "report", completion: { self.backgroundQueue { self.fetch(url: API, request: request, responseType: [FakeAPIPostsResponse].self) { response in response.forEach { apiResponse in print(apiResponse.title ?? "") } } } })) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } /* [![CI Status](https://img.shields.io/travis/[email protected]/SMNetworkManager.svg?style=flat)](https://travis-ci.org/[email protected]/SMNetworkManager) */
32.868852
180
0.625436
878c2107a8d11cdffcad0f6e701269b5adfdc3c5
4,623
// // The MIT License (MIT) // // Copyright (c) 2017 Snips // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import libetpan enum MessageAttribute { case uid(UInt) case envelope(MessageHeader) case flags(MessageFlag) case bodySection(Message) case bodyStructure(MailPart) case rfc822(Int) case ext(MessageExtension) case internalDate(Date) } extension MessageAttribute: CustomStringConvertible { var description: String { switch self { case .uid(let uid): return "uid(\(uid))" case .envelope(let env): return "envelope(\(env))" case .flags(let flags): return "flags(\(flags))" case .bodySection(let sec): return "bodySection(\(sec))" case .bodyStructure(let structure): return "bodyStructure(\(structure))" case .rfc822(let rfc): return "rfc822(\(rfc))" case .ext(let ext): return "extension(\(ext))" case .internalDate(let date): return "internalDate(\(date))" } } } extension mailimap_msg_att { func parse(_ builder: FetchResultBuilder) -> FetchResult? { sequence(att_list, of: mailimap_msg_att_item.self).forEach { item in guard let parsed = item.parse else { return } builder.addParsedAttribute(parsed) } return builder.result } } extension mailimap_msg_att_item { var parse: MessageAttribute? { switch Int(att_type) { case MAILIMAP_MSG_ATT_ITEM_DYNAMIC: return att_data.att_dyn?.pointee.parse case MAILIMAP_MSG_ATT_ITEM_STATIC: return att_data.att_static?.pointee.parse case MAILIMAP_MSG_ATT_ITEM_EXTENSION: return att_data.att_extension_data?.pointee.parse.map { .ext($0) } default: return nil } } } extension mailimap_msg_att_static { var parse: MessageAttribute? { switch Int(att_type) { case MAILIMAP_MSG_ATT_UID: return .uid(UInt(att_data.att_uid)) case MAILIMAP_MSG_ATT_ENVELOPE: return att_data.att_env?.pointee.parse.map { .envelope($0) } case MAILIMAP_MSG_ATT_BODY_SECTION: let bodySection = att_data.att_body_section?.pointee.parse("") return bodySection.map { .bodySection($0) } case MAILIMAP_MSG_ATT_BODYSTRUCTURE: return att_data.att_body?.pointee.parse("").map { .bodyStructure($0) } case MAILIMAP_MSG_ATT_RFC822_SIZE: return .rfc822(Int(att_data.att_rfc822_size)) case MAILIMAP_MSG_ATT_INTERNALDATE: return att_data.att_internal_date?.pointee.date.flatMap { .internalDate($0) } default: return nil } } } extension mailimap_msg_att_dynamic { var parse: MessageAttribute? { guard att_list?.pointee != nil else { return nil } let flags: MessageFlag = sequence(att_list, of: mailimap_flag_fetch.self).reduce([]) { combined, flagFetch in // Notice: the original code was // // guard flagFetch.fl_type != Int32(MAILIMAP_FLAG_FETCH_OTHER) // // But that seems like a bug to me. I guess we want to get the flag // details if it's "other" guard flagFetch.fl_type == Int32(MAILIMAP_FLAG_FETCH_OTHER) else { return combined } guard let flag = flagFetch.fl_flag?.pointee else { return combined } return [ combined, flag.toMessageFlag ] } guard !flags.isEmpty else { return nil } return .flags(flags) } }
37.893443
117
0.661908
6961b22faf40b985d55ea7e1c69101a66e98122f
230
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let d{}struct Q{ protocol a:d { {}protocol A:A { }}struct da
25.555556
87
0.73913
5d2c214dd8fce43c5008d7b60f28f1ffcde51330
902
// // DXScannerTests.swift // DXScannerTests // // Created by Deepak Singh on 02/10/20. // import XCTest @testable import DXScanner class DXScannerTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.529412
111
0.665188
2186341c674f91e8d44566adb333b5c8c7738d13
2,943
import ReactiveSwift extension Store { /// Calls one of two closures depending on whether a store's optional state is `nil` or not, and /// whenever this condition changes for as long as the cancellable lives. /// /// If the store's state is non-`nil`, it will safely unwrap the value and bundle it into a new /// store of non-optional state that is passed to the first closure. If the store's state is /// `nil`, the second closure is called instead. /// /// This method is useful for handling navigation in UIKit. The state for a screen the user wants /// to navigate to can be held as an optional value in the parent, and when that value goes from /// `nil` to non-`nil`, or non-`nil` to `nil`, you can update the navigation stack accordingly: /// /// class ParentViewController: UIViewController { /// let store: Store<ParentState, ParentAction> /// ... /// func viewDidLoad() { /// ... /// self.store /// .scope(state: \.optionalChild, action: ParentAction.child) /// .ifLet( /// then: { [weak self] childStore in /// self?.navigationController?.pushViewController( /// ChildViewController(store: childStore), /// animated: true /// ) /// }, /// else: { [weak self] in /// guard let self = self else { return } /// self.navigationController?.popToViewController(self, animated: true) /// } /// ) /// } /// } /// /// - Parameters: /// - unwrap: A function that is called with a store of non-optional state when the store's /// state is non-`nil`, or whenever it goes from `nil` to non-`nil`. /// - else: A function that is called when the store's optional state is `nil`, or whenever it /// goes from non-`nil` to `nil`. /// - Returns: A disposable that maintains a subscription to updates whenever the store's state /// goes from `nil` to non-`nil` and vice versa, so that the caller can react to these changes. @discardableResult public func ifLet<Wrapped>( then unwrap: @escaping (Store<Wrapped, Action>) -> Void, else: @escaping () -> Void = {} ) -> Disposable where State == Wrapped? { let elseDisposable = self .producerScope( state: { state -> Effect<Wrapped?, Never> in state .skipRepeats { ($0 != nil) == ($1 != nil) } } ) .startWithValues { store in if store.state == nil { `else`() } } let unwrapDisposable = self .producerScope( state: { state -> Effect<Wrapped, Never> in state .skipRepeats { ($0 != nil) == ($1 != nil) } .compactMap { $0 } } ) .startWithValues(unwrap) return CompositeDisposable([elseDisposable, unwrapDisposable]) } }
39.24
99
0.575263
6469fa216f104d2114e27cdfaa348c6e01e1c548
815
// // CGRect+SwipeAdditions.swift // f-HOOD-z // // Created by Weston Gibler on 1/25/18. // Copyright © 2018 Weston Gibler. All rights reserved. // import CoreGraphics typealias CGLine = (start: CGPoint, end: CGPoint) extension CGRect { var topLine: CGLine { return (SwipeDirection.topLeft.point, SwipeDirection.topRight.point) } var leftLine: CGLine { return (SwipeDirection.topLeft.point, SwipeDirection.bottomLeft.point) } var bottomLine: CGLine { return (SwipeDirection.bottomLeft.point, SwipeDirection.bottomRight.point) } var rightLine: CGLine { return (SwipeDirection.topRight.point, SwipeDirection.bottomRight.point) } var perimeterLines: [CGLine] { return [topLine, leftLine, bottomLine, rightLine] } }
23.970588
82
0.677301
dbbf374bcaef5edc881213176cdbf97fc348ba34
1,194
// // JonesPolynomial.swift // SwiftyKnots // // Created by Taketo Sano on 2018/04/04. // import SwmCore public struct _A: PolynomialIndeterminate { public static let symbol = "A" } public func KauffmanBracket(_ L: Link, normalized: Bool = false) -> LaurentPolynomial<𝐙, _A> { typealias P = LaurentPolynomial<𝐙, _A> let A = P.indeterminate let B = -A.pow(2) - A.pow(-2) let n = L.crossingNumber return Link.State.allSequences(length: n).sum { s -> P in let L1 = L.resolved(by: s) let n = L1.components.count let c1 = s.weight let c0 = s.count - c1 return A.pow(c0 - c1) * B.pow(normalized ? n - 1 : n) } } public struct _q: PolynomialIndeterminate { public static let symbol = "q" } public func JonesPolynomial(_ L: Link, normalized: Bool = true) -> LaurentPolynomial<𝐙, _q> { let A = LaurentPolynomial<𝐙, _A>.indeterminate let f = (-A).pow( -3 * L.writhe ) * KauffmanBracket(L, normalized: normalized) let range = -f.leadExponent / 2 ... -f.tailExponent / 2 let elements = Dictionary(keys: range) { i -> 𝐙 in (-1).pow(i) * f.coeff(-2 * i) } return .init(elements: elements) }
28.428571
94
0.623116
892fe3b8144f992289ac67b34b5d7d1317d94202
7,431
import UIKit import CoreGraphics import ARCollectionViewMasonryLayout import SDWebImage import RxSwift import Artsy_UIColors import SDWebImage // Just a dumb protocol to pass a message back that // something has been tapped on protocol ShowItemTapped { func didTapArtwork(item: Artwork) } // Generic DataSource for dealing with an image based collectionview class CollectionViewDelegate <T>: NSObject, ARCollectionViewMasonryLayoutDelegate { let dimensionLength:CGFloat let itemDataSource: CollectionViewDataSource<T> let delegate: ShowItemTapped? let show: Show // The extra height associated with _none_ image space in the cell, such as artwork metadata var internalPadding:CGFloat = 0 init(datasource: CollectionViewDataSource<T>, collectionView: UICollectionView, show: Show, delegate: ShowItemTapped?) { itemDataSource = datasource dimensionLength = collectionView.bounds.height self.delegate = delegate self.show = show super.init() let layout = ARCollectionViewMasonryLayout(direction: .Horizontal) layout.rank = 1 layout.dimensionLength = dimensionLength layout.itemMargins = CGSize(width: 40, height: 0) layout.contentInset = UIEdgeInsets(top: 0, left: 90, bottom: 0, right: 90) collectionView.delegate = self collectionView.collectionViewLayout = layout collectionView.setNeedsLayout() } func collectionView(collectionView: UICollectionView!, layout collectionViewLayout: ARCollectionViewMasonryLayout!, variableDimensionForItemAtIndexPath indexPath: NSIndexPath!) -> CGFloat { let item = itemDataSource.itemForIndexPath(indexPath) guard let actualItem = item, image: Image = imageForItem(actualItem) else { // otherwise, ship a square return dimensionLength } return widthForImage(image, capped: collectionView.bounds.width) } func widthForImage(image: Image, capped: CGFloat) -> CGFloat { let width: CGFloat let ratio = image.aspectRatio ?? image.imageSize.width / image.imageSize.height width = (dimensionLength - internalPadding) * ratio return min(width, capped) } func imageForItem(item:T) -> Image? { // If it's an artwork grab the default image if var artwork = item as? Artwork, let defaultImage = artwork.defaultImage, let actualImage = defaultImage as? Image { return actualImage } else if let actualImage = item as? Image { // otherwise it is an image return actualImage } return nil } func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { guard let item = itemDataSource.itemForIndexPath(indexPath) else { return } guard let image = imageForItem(item) else { return } if let cell = cell as? ImageCollectionViewCell { if image.imageFormatString == show.imageFormatString { // We can use the install shot from the ShowsOverview cache! let oldThumbnail = image.bestAvailableThumbnailURL() guard let newThumbnail = image.geminiThumbnailURLWithHeight(Int(dimensionLength)) else { return print("Could not generate a thumbnail for image") } cell.image.ar_setImageURL(newThumbnail, takeThisURLFromCacheFirst: oldThumbnail, size:image.imageSize) } else { cell.image.ar_setImage(image, height: dimensionLength) } } if let cell = cell as? ArtworkCollectionViewCell, let artwork = item as? Artwork { cell.artistNameLabel.text = artwork.oneLinerArtist() cell.titleLabel.attributedText = artwork.titleWithDate() cell.image.ar_setImage(image, height: dimensionLength) } } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { guard let item = itemDataSource.itemForIndexPath(indexPath) else { return } if let artwork = item as? Artwork { delegate?.didTapArtwork(artwork) } } } class CollectionViewDataSource <T>: NSObject, UICollectionViewDataSource { let collectionView: UICollectionView let cellIdentifier: String let cache: SDWebImagePrefetcher let show: Show var items: [T]? init(_ collectionView: UICollectionView, cellIdentifier: String, show: Show, cache: SDWebImagePrefetcher) { self.collectionView = collectionView self.cellIdentifier = cellIdentifier self.cache = cache self.show = show super.init() collectionView.dataSource = self } func subscribeToRequest(request: Observable<[(T)]>?) { guard let request = request else { return } request.subscribe() { networkItems in guard let elements = networkItems.element else { return } let newItems = elements.sort(self.moveCachableImageToTop) if let items = self.items { self.items = items + newItems } else { self.items = newItems } self.collectionView.batch() { let previousItemsCount = self.collectionView.numberOfItemsInSection(0) let paths = (previousItemsCount ..< self.items!.count).map({ NSIndexPath(forRow: $0, inSection: 0) }) self.collectionView.insertItemsAtIndexPaths(paths) } self.precache(self.items) } } func itemForIndexPath(path: NSIndexPath) -> T? { return items?[path.row] } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items?.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) } // Sort func moveCachableImageToTop(lhs:T, rhs:T) -> Bool { if imageForItem(lhs)?.imageFormatString == show.imageFormatString { return true } return false } // Low priority image caching func precache(items:[T]?) { guard let items = items else { return } let images = items.map(imageForItem).flatMap { $0 } var urls = images.map { $0.bestThumbnailWithHeight(collectionView.bounds.height) }.flatMap { $0 } // I _feel_ like the precaching is getting in the way of showing the first install shot if let _ = items.first as? Image { urls.removeAtIndex(0) } cache.prefetchURLs(urls) } // As these two are separate generic classes, they can't really share this function, thus: duped. func imageForItem(item:T) -> Image? { // If it's an artwork grab the default image if var artwork = item as? Artwork, let defaultImage = artwork.defaultImage, let actualImage = defaultImage as? Image { return actualImage } else if let actualImage = item as? Image { // otherwise it is an image return actualImage } return nil } }
35.385714
193
0.669762
e2b0f955f3aed72ba21fb1699c55fd29094d1ba7
12,442
// // BRAPIClient+Bundles.swift // breadwallet // // Created by Samuel Sutch on 3/31/17. // Copyright © 2017 breadwallet LLC. All rights reserved. // import Foundation open class AssetArchive { let name: String private let fileManager: FileManager private let archiveUrl: URL private let archivePath: String private let extractedPath: String let extractedUrl: URL private let apiClient: BRAPIClient private var archiveExists: Bool { return fileManager.fileExists(atPath: archivePath) } private var extractedDirExists: Bool { return fileManager.fileExists(atPath: extractedPath) } private var version: String? { guard let archiveContents = try? Data(contentsOf: archiveUrl) else { return nil } return archiveContents.sha256.hexString } init?(name: String, apiClient: BRAPIClient) { self.name = name self.apiClient = apiClient self.fileManager = FileManager.default let bundleDirUrl = apiClient.bundleDirUrl archiveUrl = bundleDirUrl.appendingPathComponent("\(name).tar") extractedUrl = bundleDirUrl.appendingPathComponent("\(name)-extracted", isDirectory: true) archivePath = archiveUrl.path extractedPath = extractedUrl.path } func update(completionHandler: @escaping (_ error: Error?) -> Void) { do { try ensureExtractedPath() //If directory creation failed due to file existing } catch let error as NSError where error.code == 512 && error.domain == NSCocoaErrorDomain { do { try fileManager.removeItem(at: apiClient.bundleDirUrl) try fileManager.createDirectory(at: extractedUrl, withIntermediateDirectories: true, attributes: nil) } catch let e { return completionHandler(e) } } catch let e { return completionHandler(e) } if !archiveExists { // see if the archive was shipped with the app copyBundledArchive() } if !archiveExists { // we do not have the archive, download a fresh copy return downloadCompleteArchive(completionHandler: completionHandler) } apiClient.getAssetVersions(name) { (versions, err) in DispatchQueue.global(qos: .utility).async { if let err = err { print("[AssetArchive] could not get asset versions. error: \(err)") return completionHandler(err) } guard let versions = versions, let version = self.version else { return completionHandler(BRAPIClientError.unknownError) } if versions.index(of: version) == versions.count - 1 { // have the most recent version print("[AssetArchive] already at most recent version of bundle \(self.name)") do { try self.extractArchive() return completionHandler(nil) } catch let e { print("[AssetArchive] error extracting bundle: \(e)") return completionHandler(BRAPIClientError.unknownError) } } else { // need to update the version self.downloadAndPatchArchive(fromVersion: version, completionHandler: completionHandler) } } } } fileprivate func downloadCompleteArchive(completionHandler: @escaping (_ error: Error?) -> Void) { apiClient.downloadAssetArchive(name) { (data, err) in DispatchQueue.global(qos: .utility).async { if let err = err { print("[AssetArchive] error downloading complete archive \(self.name) error=\(err)") return completionHandler(err) } guard let data = data else { return completionHandler(BRAPIClientError.unknownError) } do { try data.write(to: self.archiveUrl, options: .atomic) try self.extractArchive() return completionHandler(nil) } catch let e { print("[AssetArchive] error extracting complete archive \(self.name) error=\(e)") return completionHandler(e) } } } } fileprivate func downloadAndPatchArchive(fromVersion: String, completionHandler: @escaping (_ error: Error?) -> Void) { apiClient.downloadAssetDiff(name, fromVersion: fromVersion) { (data, err) in DispatchQueue.global(qos: .utility).async { if let err = err { print("[AssetArchive] error downloading asset path \(self.name) \(fromVersion) error=\(err)") return completionHandler(err) } guard let data = data else { return completionHandler(BRAPIClientError.unknownError) } let fm = self.fileManager let diffPath = self.apiClient.bundleDirUrl.appendingPathComponent("\(self.name).diff").path let oldBundlePath = self.apiClient.bundleDirUrl.appendingPathComponent("\(self.name).old").path do { if fm.fileExists(atPath: diffPath) { try fm.removeItem(atPath: diffPath) } if fm.fileExists(atPath: oldBundlePath) { try fm.removeItem(atPath: oldBundlePath) } try data.write(to: URL(fileURLWithPath: diffPath), options: .atomic) try fm.moveItem(atPath: self.archivePath, toPath: oldBundlePath) _ = try BRBSPatch.patch( oldBundlePath, newFilePath: self.archivePath, patchFilePath: diffPath) try fm.removeItem(atPath: diffPath) try fm.removeItem(atPath: oldBundlePath) try self.extractArchive() return completionHandler(nil) } catch let e { // something failed, clean up whatever we can, next attempt // will download fresh _ = try? fm.removeItem(atPath: diffPath) _ = try? fm.removeItem(atPath: oldBundlePath) _ = try? fm.removeItem(atPath: self.archivePath) print("[AssetArchive] error applying diff \(self.name) error=\(e)") } } } } fileprivate func ensureExtractedPath() throws { if !extractedDirExists { try fileManager.createDirectory( atPath: extractedPath, withIntermediateDirectories: true, attributes: nil ) } } fileprivate func extractArchive() throws { try BRTar.createFilesAndDirectoriesAtPath(extractedPath, withTarPath: archivePath) } fileprivate func copyBundledArchive() { if let bundledArchiveUrl = Bundle.main.url(forResource: name, withExtension: "tar") { do { try fileManager.copyItem(at: bundledArchiveUrl, to: archiveUrl) print("[AssetArchive] used bundled archive for \(name)") } catch let e { print("[AssetArchive] unable to copy bundled archive `\(name)` \(bundledArchiveUrl) -> \(archiveUrl): \(e)") } } } } // Platform bundle management extension BRAPIClient { // updates asset bundles with names included in the AssetBundles.plist file // if we are in a staging/debug/test environment the bundle names will have "-staging" appended to them open func updateBundles(completionHandler: @escaping (_ results: [(String, Error?)]) -> Void) { // ensure we can create the bundle directory do { try self.ensureBundlePaths() } catch let e { // if not return the creation error for every bundle name return completionHandler([("INVALID", e)]) } guard let path = Bundle.main.path(forResource: "AssetBundles", ofType: "plist"), var names = NSArray(contentsOfFile: path) as? [String] else { log("updateBundles unable to load bundle names") return completionHandler([("INVALID", BRAPIClientError.unknownError)]) } if E.isDebug || E.isTestFlight { names = names.map { n in return n + "-staging" } } let grp = DispatchGroup() let queue = DispatchQueue.global(qos: .utility) var results: [(String, Error?)] = names.map { v in return (v, nil) } queue.async { var i = 0 for name in names { if let archive = AssetArchive(name: name, apiClient: self) { let resIdx = i grp.enter() archive.update(completionHandler: { (err) in objc_sync_enter(results) results[resIdx] = (name, err) objc_sync_exit(results) grp.leave() }) } i += 1 } grp.wait() completionHandler(results) } } fileprivate var bundleDirUrl: URL { let fm = FileManager.default let docsUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first! let bundleDirUrl = docsUrl.appendingPathComponent("bundles", isDirectory: true) return bundleDirUrl } fileprivate func ensureBundlePaths() throws { let fm = FileManager.default var attrs = try? fm.attributesOfItem(atPath: bundleDirUrl.path) if attrs == nil { try fm.createDirectory(atPath: bundleDirUrl.path, withIntermediateDirectories: true, attributes: nil) attrs = try fm.attributesOfItem(atPath: bundleDirUrl.path) } } open func getAssetVersions(_ name: String, completionHandler: @escaping ([String]?, Error?) -> Void) { let req = URLRequest(url: url("/assets/bundles/\(name)/versions")) dataTaskWithRequest(req) {(data, resp, err) in if let err = err { completionHandler(nil, err) return } if let data = data, let parsed = try? JSONSerialization.jsonObject(with: data, options: []), let top = parsed as? NSDictionary, let versions = top["versions"] as? [String] { completionHandler(versions, nil) } else { completionHandler(nil, BRAPIClientError.malformedDataError) } }.resume() } open func downloadAssetArchive(_ name: String, completionHandler: @escaping (Data?, Error?) -> Void) { let req = URLRequest(url: url("/assets/bundles/\(name)/download")) dataTaskWithRequest(req) { (data, response, err) in if err != nil { return completionHandler(nil, err) } if response?.statusCode != 200 { return completionHandler(nil, BRAPIClientError.unknownError) } if let data = data { return completionHandler(data, nil) } else { return completionHandler(nil, BRAPIClientError.malformedDataError) } }.resume() } open func downloadAssetDiff(_ name: String, fromVersion: String, completionHandler: @escaping (Data?, Error?) -> Void) { let req = URLRequest(url: self.url("/assets/bundles/\(name)/diff/\(fromVersion)")) self.dataTaskWithRequest(req, handler: { (data, resp, err) in if err != nil { return completionHandler(nil, err) } if resp?.statusCode != 200 { return completionHandler(nil, BRAPIClientError.unknownError) } if let data = data { return completionHandler(data, nil) } else { return completionHandler(nil, BRAPIClientError.malformedDataError) } }).resume() } }
42.319728
124
0.562128
f8e93c612b4b548e56f5caaa91b5a30192562496
4,731
// // 🦠 Corona-Warn-App // import XCTest import OpenCombine @testable import ENA class TestResultAvailableViewModelTest: CWATestCase { func testGIVEN_ViewModel_WHEN_PrimaryButtonClosureCalled_THEN_ExpectationFulfill() { // GIVEN let expectationFulFill = expectation(description: "primary button code execute") let expectationNotFulFill = expectation(description: "consent cell code excecute") expectationNotFulFill.isInverted = true let client = ClientMock() let appConfiguration = CachedAppConfigurationMock() let store = MockTestStore() store.pcrTest = PCRTest.mock(testResult: .positive) let viewModel = TestResultAvailableViewModel( coronaTestType: .pcr, coronaTestService: CoronaTestService( client: client, store: store, eventStore: MockEventStore(), diaryStore: MockDiaryStore(), appConfiguration: appConfiguration, healthCertificateService: HealthCertificateService( store: store, client: client, appConfiguration: appConfiguration ) ), onSubmissionConsentCellTap: { _ in expectationNotFulFill.fulfill() }, onPrimaryButtonTap: { _ in expectationFulFill.fulfill() }, onDismiss: {} ) // WHEN viewModel.onPrimaryButtonTap({ _ in }) // THEN waitForExpectations(timeout: .medium) } func testGIVEN_ViewModel_WHEN_getDynamicTableViewModel_THEN_SectionsAndCellMatchExpectation() { // GIVEN let expectationNotFulFill = expectation(description: "consent cell code excecute") expectationNotFulFill.isInverted = true var bindings: Set<AnyCancellable> = [] let client = ClientMock() let appConfiguration = CachedAppConfigurationMock() let store = MockTestStore() store.pcrTest = PCRTest.mock(testResult: .positive) let viewModel = TestResultAvailableViewModel( coronaTestType: .pcr, coronaTestService: CoronaTestService( client: client, store: store, eventStore: MockEventStore(), diaryStore: MockDiaryStore(), appConfiguration: appConfiguration, healthCertificateService: HealthCertificateService( store: store, client: client, appConfiguration: appConfiguration ) ), onSubmissionConsentCellTap: { _ in expectationNotFulFill.fulfill() }, onPrimaryButtonTap: { _ in expectationNotFulFill.fulfill() }, onDismiss: {} ) // WHEN var resultDynamicTableViewModel: DynamicTableViewModel? viewModel.$dynamicTableViewModel.sink { dynamicTableViewModel in resultDynamicTableViewModel = dynamicTableViewModel }.store(in: &bindings) // THEN waitForExpectations(timeout: .short) XCTAssertEqual(3, resultDynamicTableViewModel?.numberOfSection) XCTAssertEqual(0, resultDynamicTableViewModel?.numberOfRows(section: 0)) XCTAssertEqual(1, resultDynamicTableViewModel?.numberOfRows(section: 1)) XCTAssertEqual(2, resultDynamicTableViewModel?.numberOfRows(section: 2)) } func testGIVEN_ViewModel_WHEN_GetIconCellActionTigger_THEN_ExpectationFulfill() { // GIVEN let expectationFulFill = expectation(description: "primary button code execute") let expectationNotFulFill = expectation(description: "consent cell code excecute") expectationNotFulFill.isInverted = true var bindings: Set<AnyCancellable> = [] let client = ClientMock() let appConfiguration = CachedAppConfigurationMock() let store = MockTestStore() store.pcrTest = PCRTest.mock(testResult: .positive) let viewModel = TestResultAvailableViewModel( coronaTestType: .pcr, coronaTestService: CoronaTestService( client: client, store: store, eventStore: MockEventStore(), diaryStore: MockDiaryStore(), appConfiguration: appConfiguration, healthCertificateService: HealthCertificateService( store: store, client: client, appConfiguration: appConfiguration ) ), onSubmissionConsentCellTap: { _ in expectationFulFill.fulfill() }, onPrimaryButtonTap: { _ in expectationNotFulFill.fulfill() }, onDismiss: {} ) var resultDynamicTableViewModel: DynamicTableViewModel? let waitForCombineExpectation = expectation(description: "dynamic tableview mode did load") viewModel.$dynamicTableViewModel.sink { dynamicTableViewModel in resultDynamicTableViewModel = dynamicTableViewModel waitForCombineExpectation.fulfill() }.store(in: &bindings) wait(for: [waitForCombineExpectation], timeout: .medium) let iconCell = resultDynamicTableViewModel?.cell(at: IndexPath(row: 0, section: 1)) // WHEN switch iconCell?.action { case .execute(block: let block): block( UIViewController(), nil ) default: XCTFail("unknown action type") } // THEN wait(for: [expectationFulFill, expectationNotFulFill], timeout: .medium) } }
29.943038
96
0.75037
d92cb23853e65bda52bcc15ed48fab5d2bc846df
5,578
// // ViewController.swift // AudioKitParticles // // Created by Simon Gladman on 28/12/2015. // Copyright © 2015 Simon Gladman. All rights reserved. // import AudioKit import UIKit class ParticleViewController: UIViewController { override var supportedInterfaceOrientations : UIInterfaceOrientationMask { return .landscape } override var shouldAutorotate : Bool { return false } override var prefersStatusBarHidden: Bool { return true } let floatPi = Float.pi var gravityWellAngle: Float = 0 var particleLab: ParticleLab! var amplitude: Float = 0 var lowMaxIndex: Float = 0 var hiMaxIndex: Float = 0 var hiMinIndex: Float = 0 var loopo : Loop? override func viewDidLoad() { super.viewDidLoad() // ---- view.backgroundColor = UIColor.black let numParticles = ParticleCount.cazz if view.frame.height < view.frame.width { particleLab = ParticleLab(width: UInt(view.frame.width), height: UInt(view.frame.height), numParticles: numParticles) particleLab.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height) } else { particleLab = ParticleLab(width: UInt(view.frame.height), height: UInt(view.frame.width), numParticles: numParticles) particleLab.frame = CGRect(x: 0, y: 0, width: view.frame.height, height: view.frame.width) } particleLab.particleLabDelegate = self particleLab.dragFactor = 0.9 particleLab.clearOnStep = false particleLab.respawnOutOfBoundsParticles = true view.addSubview(particleLab) // statusLabel.textColor = UIColor.darkGray // statusLabel.text = "Particles" // view.addSubview(statusLabel) } override func viewWillAppear(_ animated: Bool) { loopo = Loop(every: 1 / 30) { let fftData = MTSignalPlayer.singleton.fft!.fftData let count = 250 let lowMax = fftData[0 ... (count / 2) - 1].max() ?? 0 let hiMax = fftData[count / 2 ... count - 1].max() ?? 0 let hiMin = fftData[count / 2 ... count - 1].min() ?? 0 let lowMaxIndex = fftData.index(of: lowMax) ?? 0 let hiMaxIndex = fftData.index(of: hiMax) ?? 0 let hiMinIndex = fftData.index(of: hiMin) ?? 0 self.amplitude = Float(MTSignalPlayer.singleton.amplitudeTracker.amplitude * 25) self.lowMaxIndex = Float(lowMaxIndex) self.hiMaxIndex = Float(hiMaxIndex - count / 2) self.hiMinIndex = Float(hiMinIndex - count / 2) } } override func viewWillDisappear(_ animated: Bool) { loopo?.stoppa() loopo = nil } func particleLabStep() { gravityWellAngle += 0.01 let radiusLow = 0.1 + (lowMaxIndex / 256) particleLab.setGravityWellProperties( gravityWell: .one, normalisedPositionX: 0.5 + radiusLow * sin(gravityWellAngle), normalisedPositionY: 0.5 + radiusLow * cos(gravityWellAngle), mass: (lowMaxIndex * amplitude), spin: -(lowMaxIndex * amplitude)) particleLab.setGravityWellProperties( gravityWell: .four, normalisedPositionX: 0.5 + radiusLow * sin((gravityWellAngle + floatPi)), normalisedPositionY: 0.5 + radiusLow * cos((gravityWellAngle + floatPi)), mass: (lowMaxIndex * amplitude), spin: -(lowMaxIndex * amplitude)) let radiusHi = 0.1 + (0.25 + (hiMaxIndex / 1_024)) particleLab.setGravityWellProperties( gravityWell: .two, normalisedPositionX: particleLab.getGravityWellNormalisedPosition(gravityWell: .one).x + (radiusHi * sin(gravityWellAngle * 3)), normalisedPositionY: particleLab.getGravityWellNormalisedPosition(gravityWell: .one).y + (radiusHi * cos(gravityWellAngle * 3)), mass: (hiMaxIndex * amplitude), spin: (hiMinIndex * amplitude)) particleLab.setGravityWellProperties( gravityWell: .three, normalisedPositionX: particleLab.getGravityWellNormalisedPosition(gravityWell: .four).x + (radiusHi * sin((gravityWellAngle + floatPi) * 3)), normalisedPositionY: particleLab.getGravityWellNormalisedPosition(gravityWell: .four).y + (radiusHi * cos((gravityWellAngle + floatPi) * 3)), mass: (hiMaxIndex * amplitude), spin: (hiMinIndex * amplitude)) } // MARK: Layout // override func viewDidLayoutSubviews() { // statusLabel.frame = CGRect(x: 5, // y: view.frame.height - statusLabel.intrinsicContentSize.height, // width: view.frame.width, // height: statusLabel.intrinsicContentSize.height) // } // override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { // // } } extension ParticleViewController: ParticleLabDelegate { func particleLabMetalUnavailable() { // handle metal unavailable here } func particleLabDidUpdate(_ status: String) { // statusLabel.text = status particleLab.resetGravityWells() particleLabStep() } }
32.057471
114
0.598781
e87d7b0855ac4562b4aa1500d36190cf266dfca5
1,597
// // ProductListTableViewCell.swift // iProduct // // Created by Shakti Prakash Srichandan on 29/06/21. // import UIKit class ProductListTableViewCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var productImageView: NetworkImageView! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var descLabel: UILabel! @IBOutlet weak var cartButton: UIButton! var data: Displayable? weak var delegate: Tappable? 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 } func setupUIWith(_ data: Displayable, hideCart: Bool = false) { self.data = data self.nameLabel.text = data.name self.priceLabel.text = "Rs:- \(data.price)" self.descLabel.text = data.desc self.productImageView.loadImageWithURL(url: data.image, placeHolderImage: UIImage(systemName: "photo.on.rectangle.angled")) self.cartButton.isSelected = data.incart self.cartButton.isHidden = hideCart } @IBAction func cartButtonTapped(_ sender: UIButton) { guard let currentProduct = data else { return } self.delegate?.performCartinteraction(product: currentProduct, cell: self) } } extension ProductListTableViewCell: CartHandler { func updateCartDetails(status: Bool, atIndex: Int?) { self.cartButton.isSelected = status } }
30.132075
131
0.683782
621a160d526d1385fad333e84b78fea6c3005712
5,717
// // ViewController.swift // AREasyStart // // Created by Manuela Rink on 01.06.18. // Copyright © 2018 Manuela Rink. All rights reserved. // import UIKit import SceneKit import ARKit import GameplayKit class ViewController: UIViewController, ARSCNViewDelegate { @IBOutlet var sceneView: ARSCNView! @IBOutlet weak var saveWorldButton: UIButton! @IBOutlet weak var loadWorldButton: UIButton! var sunshineSystem : SCNParticleSystem? var timer : Timer? var postitIndex = 0 var alert : UIAlertController? var worldFileURL : URL? var screenCenter: CGPoint { let screenSize = view.bounds return CGPoint(x: screenSize.width / 2, y: screenSize.height / 2) } override func viewDidLoad() { super.viewDidLoad() sceneView.delegate = self let scene = SCNScene() sceneView.scene = scene let fileName = "worldmap" let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) worldFileURL = DocumentDirURL.appendingPathComponent(fileName) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func saveWorldMap () { sceneView.session.getCurrentWorldMap { worldMap, error in guard let map = worldMap else { print("Error: \(error!.localizedDescription)"); return } guard let data = try? NSKeyedArchiver.archivedData(withRootObject: map, requiringSecureCoding: true) else { fatalError("can't encode map") } try? data.write(to: self.worldFileURL!) } } func openWorldMap () throws { let mapData = try Data(contentsOf: worldFileURL!) guard let worldMap = try NSKeyedUnarchiver.unarchivedObject(of: ARWorldMap.classForKeyedUnarchiver(), from: mapData) as? ARWorldMap else { throw ARError(.invalidWorldMap) } runSession(worldMap) } @IBAction func runSessionTapped(_ sender: Any) { runSession() } @IBAction func saveWorldTapped(_ sender: Any) { saveWorldMap() alert = UIAlertController(title: "World saved", message: "The ARWorldMap and all elements were sucessfully saved.", preferredStyle: .alert) self.present(alert!, animated: true) timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: false, block: { timer in self.alert?.dismiss(animated: true, completion: nil) }) } @IBAction func openWorldTapped(_ sender: Any) { try? openWorldMap() alert = UIAlertController(title: "World loading...", message: "Loading a map works best when you explore the environment. \nMove your phone around and we'll be up in a second!", preferredStyle: .alert) self.present(alert!, animated: true) timer = Timer.scheduledTimer(withTimeInterval: 10, repeats: false, block: { timer in self.alert?.dismiss(animated: true, completion: nil) }) } @IBAction func sceneTapped(_ sender: UITapGestureRecognizer) { guard let hitTestResult = sceneView .hitTest(sender.location(in: sceneView), types: [.existingPlaneUsingGeometry, .estimatedHorizontalPlane]) .first else { return } // Place an anchor for a virtual character. The model appears in renderer(_:didAdd:for:). let anchor = ARAnchor(name: "postit", transform: hitTestResult.worldTransform) sceneView.session.add(anchor: anchor) } func runSession(_ map: ARWorldMap? = nil) { DispatchQueue.main.async { let configuration = ARWorldTrackingConfiguration() configuration.planeDetection = [.vertical] if let theMap = map { configuration.initialWorldMap = theMap } self.sceneView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors]) } } func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { DispatchQueue.main.async { // if let planeAnchor = anchor as? ARPlaneAnchor { // let planeNode = createPlaneNode(center: planeAnchor.center, extent: planeAnchor.extent) // planeNode.geometry?.firstMaterial?.diffuse.contents = UIColor(white: 1, alpha: 0.1).cgColor // planeNode.geometry?.firstMaterial?.colorBufferWriteMask = [] // planeNode.geometry?.firstMaterial?.isDoubleSided = true // planeNode.castsShadow = false // planeNode.renderingOrder = -1 // node.addChildNode(planeNode) // } if let name = anchor.name, name.hasPrefix("postit") { let sceneURL = Bundle.main.url(forResource: "postit", withExtension: "scn", subdirectory: "art.scnassets") let refNode = SCNReferenceNode(url: sceneURL!)! refNode.load() let postit = refNode.childNode(withName: "postit", recursively: true)?.childNodes[self.postitIndex] node.addChildNode(postit!) self.postitIndex = self.postitIndex >= 5 ? 0 : self.postitIndex + 1 } } } func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) { // DispatchQueue.main.async { // if let planeAnchor = anchor as? ARPlaneAnchor { // updatePlaneNode(node.childNodes[0], center: planeAnchor.center, extent: planeAnchor.extent) // } // } } }
39.427586
209
0.627777
4b29e64394d148a54d33a04e57f2875292187978
262
import Foundation public struct IntegEnvironment { static let networkUrl: String = "INTEG_TESTS_NETWORK_URL" static let networkPassphrase: String = "INTEG_TESTS_NETWORK_PASSPHRASE" static let friendbotUrl: String = "INTEG_TESTS_NETWORK_FRIENDBOT" }
32.75
75
0.801527
9b962f643a8f24372a6a23e9521305d7ee7d243e
224
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A{var b=a class a func i(){class B<T where T:T>:B
32
87
0.75
560fb9e1dc736e1ca4d78c3c667bd0e1f3bde35f
191
// // AnyResponse.swift // Cavy // // Created by Avery Pierce on 2/20/21. // import Foundation struct AnyResponse: Codable { // Placeholder type that does not decode into anything }
14.692308
58
0.685864
72b47c29851c964a611b627d46c503fa491ddd2f
999
import UIKit import Flutter import GoogleCast @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { let kReceiverAppID = kGCKDefaultMediaReceiverApplicationID let kDebugLoggingEnabled = true override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? ) -> Bool { let criteria = GCKDiscoveryCriteria(applicationID: kReceiverAppID) let options = GCKCastOptions(discoveryCriteria: criteria) GCKCastContext.setSharedInstanceWith(options) // Enable logger. GCKLogger.sharedInstance().delegate = self GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } } extension AppDelegate: GCKLoggerDelegate { func logMessage(_ message: String, at level: GCKLoggerLevel, fromFunction function: String, location: String) { if(kDebugLoggingEnabled) { print(function + " - " + message) } } }
29.382353
112
0.782783
50064e63428cd1046a83abf1e9820a0c57d9bf20
979
// // memuDemoTests.swift // memuDemoTests // // Created by Mohammed Gamal on 09/10/16. // Copyright © 2016 Parth Changela. All rights reserved. // import XCTest @testable import memuDemo class memuDemoTests: 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. } } }
26.459459
111
0.635342
79e3dceb3effcb70031b0fba30baae12638e160b
1,486
// // MT_UIResponderUITests.swift // MT-UIResponderUITests // // Created by yunxi on 2020/7/17. // Copyright © 2020 matias. All rights reserved. // import XCTest class MT_UIResponderUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) { XCUIApplication().launch() } } } }
33.772727
182
0.663526
6101512132bc06150acacea845c6fcf1ddaa5795
2,976
// /**************************************************************************** * Copyright 2019, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * ***************************************************************************/ import XCTest class EventForDispatchTests: XCTestCase { func testEqualOperator() { var urlStr = "https://optimizely.com" var message = "One body" let event1 = EventForDispatch(url: URL(string: urlStr), body: message.data(using: .utf8)!) var event2 = EventForDispatch(url: URL(string: urlStr), body: message.data(using: .utf8)!) XCTAssert(event1 == event2) message = "Other body" event2 = EventForDispatch(url: URL(string: urlStr), body: message.data(using: .utf8)!) XCTAssert(event1 != event2) urlStr = "Other url" message = "One body" event2 = EventForDispatch(url: URL(string: urlStr), body: message.data(using: .utf8)!) XCTAssert(event1 != event2) urlStr = "https://optimizely.com" message = "One body" event2 = EventForDispatch(url: URL(string: urlStr), body: message.data(using: .utf8)!) XCTAssert(event1 == event2) } func testDescriptionWithGoodString() { let urlStr = "https://optimizely.com" let message = "This is event body" let event = EventForDispatch(url: URL(string: urlStr), body: message.data(using: .utf8)!) let desc = event.description XCTAssert(desc.contains(urlStr)) XCTAssert(desc.contains(message)) } func testDescriptionWithBadString() { let urlStr = "https://optimizely.com" let message = "This is event body" // use a wrong encoding (UTF16), which will cause invalid string let event = EventForDispatch(url: URL(string: urlStr), body: message.data(using: .utf16)!) let desc = event.description XCTAssert(desc.contains(urlStr)) XCTAssert(desc.contains("UNKNOWN")) } }
43.764706
98
0.527218