repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
ohde-sg/SQLiteSwift
SQLiteSwift/SQLite.swift
1
4254
// // SQLiteConnection.swift // SQLiteSwift // // Created by 大出喜之 on 2016/02/15. // Copyright © 2016年 yoshiyuki ohde. All rights reserved. // import Foundation import FMDB class SQLite { static private var conn: SQLite? private let dbFilePath: String private var _db:FMDatabase? private var db: FMDatabase { get { if let tmpDb = _db { return tmpDb }else{ _db = FMDatabase(path: dbFilePath) return _db! } } } var isOutput:Bool = false init(_ filePath:String){ self.dbFilePath = filePath } /// Create Table according to sql parameter /// - parameter sql: sql statement /// - returns: true on Success, false on Failure func createTable(sql:String) -> Bool { return executeUpdate(sql,nil) } func deleteTable(tables:[String]) -> Bool { let sql = "DROP TABLE IF EXISTS" var result:Bool = true tables.forEach{ if !executeUpdate(sql + " \($0);", nil) { result = false } } return result } func insert(sql:String,values:[AnyObject]!) -> Bool { return executeUpdate(sql,values) } func update(sql:String,values:[AnyObject]!) -> Bool { return executeUpdate(sql,values) } func delete(sql:String,values:[AnyObject]!) -> Bool { return executeUpdate(sql, values) } private func executeUpdate(sql:String, _ values: [AnyObject]!) -> Bool{ do { try db.executeUpdate(sql, values: values) if isOutput { print("Query: \(sql)") } return true } catch { db.rollback() return false; } } private func executeQuery(sql:String, values:[AnyObject]!) -> FMResultSet? { if isOutput { print("Query: \(sql)") } return try? db.executeQuery(sql, values: values) } func beginTransaction(){ if !db.inTransaction() { db.open() db.beginTransaction() } } var inTransaction:Bool { return db.inTransaction() } func commit() { if db.inTransaction() { db.commit() db.close() } } func rollback(){ if db.inTransaction() { db.rollback() } } /// Return whether DBFile is exist /// - returns: true on exist, false on not exist func isExistDBFile() -> Bool { let fileManager: NSFileManager = NSFileManager.defaultManager() return fileManager.fileExistsAtPath(self.dbFilePath) } /// Return whether Tables are exist /// - parameter table names string array /// - returns: false & table array on not exist , true & blank array on all tables exist func isExistTable(tables:[String]) -> (result:Bool,tables:[String]?) { let sql = "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?;" var rtnBl:Bool = true var noExistTables:[String] = [] for table in tables { let result = executeQuery(sql, values: [table]) defer { result?.close() } guard let theResult = result else { return (false,nil) } theResult.next() if theResult.intForColumnIndex(0) == 0 { rtnBl = false noExistTables.append(table) } } return (!rtnBl && noExistTables.count>0) ? (false,noExistTables) : (rtnBl,nil) } func select(sql:String,values:[AnyObject]!) -> [[String:AnyObject]] { let result = executeQuery(sql, values: values) defer { result?.close() } var rtn:[[String:AnyObject]] = [] guard let theResult = result else{ return rtn } while theResult.next() { var dict:[String:AnyObject] = [:] for(key,value) in theResult.resultDictionary() { let theKey = key as! String dict[theKey] = value } rtn.append(dict) } return rtn } }
mit
b49b1652aa1a33527fb14e214f2ffb02
26.551948
92
0.530757
4.523454
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/powerful-integers.swift
2
604
/** * https://leetcode.com/problems/powerful-integers/ * * */ // Date: Fri Apr 30 11:44:05 PDT 2021 class Solution { func powerfulIntegers(_ x: Int, _ y: Int, _ bound: Int) -> [Int] { var result: Set<Int> = [] var a = 1 while a <= bound { var b = 1 while b <= bound { if a + b <= bound { result.insert(a + b) } b *= y if y == 1 { break } } a *= x if x == 1 { break } } return Array(result) } }
mit
de41adc58b4ec578a6b79ac29a7dced9
20.571429
70
0.374172
3.871795
false
false
false
false
zyhndesign/SDX_DG
sdxdg/sdxdg/PersonalInfoViewController.swift
1
6975
// // PersonalInfoViewController.swift // sdxdg // // Created by lotusprize on 16/12/24. // Copyright © 2016年 geekTeam. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class PersonalInfoViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate { @IBOutlet var usernameTextField: UITextField! @IBOutlet var userIconImageView: UIImageView! @IBOutlet var postBtn: UIButton! var newIcon:Bool = false let userId = LocalDataStorageUtil.getUserIdFromUserDefaults() override func viewDidLoad() { super.viewDidLoad() postBtn.layer.cornerRadius = 6 let tapImage:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(fromAlbum(sender:))) userIconImageView.isUserInteractionEnabled = true userIconImageView.addGestureRecognizer(tapImage) } func fromAlbum(sender:Any){ if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){ let picker = UIImagePickerController() picker.delegate = self picker.sourceType = UIImagePickerControllerSourceType.photoLibrary self.present(picker, animated: true, completion: { }) } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let image = info[UIImagePickerControllerOriginalImage] as! UIImage let size:CGSize = CGSize.init(width: 200, height: 200) var newImage:UIImage? UIGraphicsBeginImageContext(size) image.draw(in: CGRect.init(x: 0, y: 0, width: size.width, height: size.height)) newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() userIconImageView.image = newImage newIcon = true picker.dismiss(animated: true) { } } @IBAction func postDataBtnClick(_ sender: Any) { if !newIcon && (usernameTextField.text?.isEmpty)!{ MessageUtil.showMessage(view: self.view, message: "无任何修改") return } var phone:String = "" if !(usernameTextField.text?.isEmpty)!{ phone = usernameTextField.text! } print(phone) if newIcon{ let hud = MBProgressHUD.showAdded(to: self.view, animated: true) hud.label.text = "提交中..." let headers = ["content-type":"multipart/form-data"] Alamofire.request(ConstantsUtil.APP_QINIU_TOKEN).responseJSON { (response) in if let data = response.result.value { let responseResult = JSON(data) let resultCode = responseResult["resultCode"].intValue if resultCode == 200{ let token = responseResult["uptoken"].string! Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append((token.data(using: String.Encoding.utf8)!), withName: "token") let filename = (UIDevice.current.identifierForVendor?.uuidString)! multipartFormData.append(UIImagePNGRepresentation(self.userIconImageView.image!)!, withName: "file", fileName: filename, mimeType: "image/png") }, to: ConstantsUtil.APP_QINIU_UPLOAD_URL, headers: headers, encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in if let value = response.result.value as? [String: AnyObject]{ let json = JSON(value) let headicon = ConstantsUtil.APP_QINIU_IMAGE_URL_PREFIX + json["key"].string! hud.hide(animated: true) self.postUpdateData(phone: phone, headicon: headicon) } } case .failure(let encodingError): hud.label.text = "操作失败" hud.hide(animated: true, afterDelay: 1.0) } } ) } } } } else if (!phone.isEmpty){ self.postUpdateData(phone: phone, headicon: "") } } func postUpdateData(phone:String, headicon:String){ let parameters:Parameters = ["phone":phone,"headicon":headicon,"userId":userId] let hud = MBProgressHUD.showAdded(to: self.view, animated: true) hud.label.text = "提交中..." Alamofire.request(ConstantsUtil.APP_USER_UPDATE_DATA_URL,method:.post,parameters:parameters).responseJSON { (response) in if let data = response.result.value { let responseResult = JSON(data) let resultCode = responseResult["resultCode"].intValue if resultCode == 200{ hud.label.text = "操作成功" hud.hide(animated: true, afterDelay: 1.0) if (!phone.isEmpty){ LocalDataStorageUtil.saveUserInfoToUserDefault(suiteName: "currentUser", key: "phone", value: phone) } if (!headicon.isEmpty){ LocalDataStorageUtil.saveUserInfoToUserDefault(suiteName: "currentUser", key: "headicon", value: headicon) NotificationCenter.default.post(name: NSNotification.Name(rawValue: "HeadIcon"), object: self.userIconImageView.image!) } self.navigationController?.popViewController(animated: true) } else{ hud.label.text = "操作失败" hud.hide(animated: true, afterDelay: 1.0) } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
8cd3b0fb6be69de62fc10c9bd2a8cb0b
40.722892
175
0.515016
6.038361
false
false
false
false
mathewsanders/Tally-Walker
Tally/Tally/Walker.swift
1
9108
// Walker.swift // // Copyright (c) 2016 Mathew Sanders // // 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 /// Options that describe the number of steps to look at when considering the next step in a random walk. public enum WalkType<Item: Hashable> { /// Use a 1-st order markov chain, which only looks at the last step taken. case markovChain /// Look at the longest number of steps possible for an associated frequency model. case matchModel /// Attempt to look at a specific number of steps. This should be used to look at a shorter number of steps than allowed in the frequency model. case steps(Int) /// The number of steps to look at when considering the next step in a random walk. func numberOfSteps(for model: Tally<Item>) -> Int { switch self { case .markovChain: return 1 case .matchModel: return model.ngram.size - 1 case .steps(let steps): return steps } } } /// A Walker object generates sequences of items based of n-grams of items from a Tally object. public struct Walker<Item: Hashable> : Sequence, IteratorProtocol { private let model: Tally<Item> private let walk: WalkType<Item> typealias ElementProbability = (probability: Double, element: NgramElement<Item>) private var newSequence = true private var lastSteps: [Item] = [] /// Initializes and returns a new walker object. /// /// - parameter model: The frequency model to use for random walks. /// - parameter walk: Option for the number of steps to look at when making the next step in a random walk (default value is `WalkType.matchModel`). /// /// - returns: An initialized walker object ready to start generating new sequences. public init(model: Tally<Item>, walkOptions walk: WalkType<Item> = .matchModel) { self.model = model self.walk = walk // seed random number generator let time = Int(NSDate.timeIntervalSinceReferenceDate) srand48(time) } /// Fills a array with sequence of items. /// /// - parameter request: The number of items make the sequence. /// For models of discrete sequences the actual number of items may be less than requested. /// For models of continuous sequences the number of items should always match the requested number. /// /// - returns: An array of items generated from a random walk on the `Tally` frequency model. public mutating func fill(request: Int) -> [Item] { if model.sequence.isDiscrete { endWalk() } return Array(self.prefix(request)) } /// End the current walk so that the next call to `next()` starts a new random walk. public mutating func endWalk() { newSequence = true lastSteps.removeAll() } mutating public func next() -> Item? { return nextStep() } /// Returns the next item in a random walk of the model. /// /// How the next item to return is chosen depends on changes depending on the underlying model. /// /// If the model is empty, nil will always be returned /// /// For models representing continuous sequences: /// - the first item returned will be picked based on the distribution of all items /// - subsequent items will be based on a random walk considering the last n items picked /// - nil will never be returned, unless the model is empty /// /// For models representing discrete sequences: /// - the first item returned will be picked based on the distribution of all starting items /// - subsequent items will be based on a random walk considering the last n items picked /// - nil will be returned to represent the end of the sequence /// /// - returns: the next item, if it exists, or nil if the end of the sequence has been reached mutating public func nextStep() -> Item? { // empty model if model.startingElements().isEmpty { print("Walker.next() Warning: attempting to generate an item from empty model") return nil } // starting a new sequence if newSequence { newSequence = false lastSteps.removeAll() let step = randomWalk(from: model.startingElements()) if let item = step.item { lastSteps = [item] } return step.item } // continuing an existing sequence else { lastSteps.clamp(to: walk.numberOfSteps(for: model)) // continuing a discrete sequence (okay to return nil) if model.sequence.isDiscrete { let nextSteps = model.elementProbabilities(following: lastSteps) let step = randomWalk(from: nextSteps) if let item = step.item { lastSteps.append(item) } return step.item } // continuing a continuous sequence (always want to return next item) else if model.sequence.isContinuous { var foundStep = false var item: Item? = nil while !foundStep { if lastSteps.isEmpty { let step = randomWalk(from: model.startingElements()) item = step.item foundStep = true } else { let nextSteps = model.elementProbabilities(following: lastSteps) let step = randomWalk(from: nextSteps) if let _ = step.item { item = step.item foundStep = true } else if step.isObservableBoundary { var nextSteps = model.distributions(excluding: nextSteps.map({ $0.element })) if nextSteps.isEmpty { nextSteps = model.distributions() } let step = randomWalk(from: nextSteps) if let _ = step.item { item = step.item foundStep = true } } if !foundStep { lastSteps.remove(at: 0) } } } if let item = item { lastSteps.append(item) } return item } } return nil } private mutating func randomWalk(from possibleSteps: [ElementProbability]) -> NgramElement<Item> { if possibleSteps.isEmpty { NSException(name: NSExceptionName.invalidArgumentException, reason: "Walker.randomWalk can not choose from zero possibilities", userInfo: nil).raise() } if possibleSteps.count == 1 { return possibleSteps[0].element } var base = 1.0 typealias StepLimit = (element: NgramElement<Item>, limit: Double) // translate probabilities into lower limits // e.g. (0.25, 0.5, 0.25) -> (0.75, 0.25, 0.0) let lowerLimits: [StepLimit] = possibleSteps.map { possibleStep in let limit = base - possibleStep.probability base = limit return (element: possibleStep.element, limit: limit) } // returns a double 0.0..<1.0 let randomLimit = drand48() // choose the step based on a randomly chosen limit let step = lowerLimits.first { _, lowerLimit in return lowerLimit < randomLimit } return step!.element } }
mit
ace8ff2705702e5a4bd6814be63e1253
39.843049
162
0.580698
5.219484
false
false
false
false
ywwill/ywhades
Sources/App/Extensions/StringParsedDateComponents.swift
1
3198
// // StringParsedDateComponents.swift // ywHades // // Created by YangWei on 2017/7/27. // // import Foundation enum StringParsedDateComponents { static let monthPattern = "Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?" static let dayPattern = "\\d{2}|\\d{1}" static let yearPattern = "\\d{4}" case Month(Int) case Day(Int) case Year(Int) case None static func month(from: String) -> StringParsedDateComponents { let matched = from.match(pattern: self.monthPattern) if matched != "" { switch matched { case "Jan", "January": return .Month(1) case "Feb", "February": return .Month(2) case "Mar", "March": return .Month(3) case "Apr", "April": return .Month(4) case "May": return .Month(5) case "Jun", "June": return .Month(6) case "Jul", "July": return .Month(7) case "Aug", "August": return .Month(8) case "Sep", "September": return .Month(9) case "Oct", "October": return .Month(10) case "Nov", "November": return .Month(11) case "Dec", "December": return .Month(12) default: return .None } } return .None } static func day(from: String) -> StringParsedDateComponents { let matched = from.match(pattern: self.dayPattern) if matched != "", let matchedInt = Int(matched) { return .Day(matchedInt) } return .None } static func year(from: String) -> StringParsedDateComponents { let matched = from.match(pattern: self.yearPattern) if matched != "", let matchedInt = Int(matched) { return .Year(matchedInt) } return .None } } extension StringParsedDateComponents: CustomDebugStringConvertible { var debugDescription: String { switch self { case let .Month(month): return "Month \(month)" case let .Day(day): return "Day \(day)" case let .Year(year): return "Year \(year)" case .None: return "None" } } } extension StringParsedDateComponents { // Generate a date from enumeration. static func dateFrom(year: StringParsedDateComponents, month: StringParsedDateComponents, day: StringParsedDateComponents) -> Date? { guard case let .Year(yearInt) = year, case let .Month(monthInt) = month, case let .Day(dayInt) = day else { return nil } let calendar = NSCalendar(identifier: .gregorian) var components = DateComponents() components.year = yearInt components.month = monthInt components.day = dayInt return calendar?.date(from: components) } }
mit
110d0cf9fba3b55043409d7cd1e16c9a
27.810811
150
0.519387
4.575107
false
false
false
false
phimage/ApplicationGroupKit
Sources/FileMessenger.swift
1
4978
// // FileMessenger.swift // ApplicationGroupKit /* The MIT License (MIT) Copyright (c) 2015 Eric Marchand (phimage) 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 open class FileMessenger: Messenger { open var fileManager = FileManager.default open var directory: String? public init(directory: String?) { super.init() self.directory = directory } open override var type: MessengerType { return .file(directory: directory) } override func checkConfig() -> Bool { guard let url = containerURLForSecurity() else { return false } do { try fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) } catch { return false } return true } override func writeMessage(_ message: Message, forIdentifier identifier: MessageIdentifier) -> Bool { guard let path = filePathForIdentifier(identifier) else { return false } return NSKeyedArchiver.archiveRootObject(message, toFile: path) } override func readMessageForIdentifier(_ identifier: MessageIdentifier) -> Message? { guard let path = filePathForIdentifier(identifier) else { return nil } return messageFromFile(path) } override func deleteContentForIdentifier(_ identifier: MessageIdentifier) throws { guard let path = filePathForIdentifier(identifier) else { return } var isDirectory: ObjCBool = false if self.fileManager.fileExists(atPath: path, isDirectory: &isDirectory) { if !isDirectory.boolValue { try self.fileManager.removeItem(atPath: path) } } } override func deleteContentForAllMessageIdentifiers() throws { guard let url = containerURLForSecurity() else { return } let contents = try fileManager.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: []) for content in contents { var isDirectory: ObjCBool = false if self.fileManager.fileExists(atPath: content.absoluteString, isDirectory: &isDirectory) { if !isDirectory.boolValue { try self.fileManager.removeItem(at: content) } } } } override func readMessages() -> [MessageIdentifier: Message]? { guard let url = applicationGroup?.containerURLForSecurity(fileManager) else { return nil } guard let contents = try? fileManager.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: []) else { return nil } var messages = [MessageIdentifier: Message]() for content in contents { let path = content.absoluteString // XXX use absoluteString or path? if let messageIdenfier = content.pathComponents.last, let message = messageFromFile(path) { messages[messageIdenfier] = message } } return messages } // MARK: privates internal func containerURLForSecurity() -> URL? { let container = applicationGroup?.containerURLForSecurity(fileManager) guard let directory = self.directory else { return container } return container?.appendingPathComponent(directory) } internal func fileURLForIdentifier(_ identifier: MessageIdentifier) -> URL? { return containerURLForSecurity()?.appendingPathComponent(identifier) } internal func filePathForIdentifier(_ identifier: MessageIdentifier) -> String? { guard let url = fileURLForIdentifier(identifier) else { return nil } return url.absoluteString } internal func messageFromFile(_ path: String) -> Message? { return NSKeyedUnarchiver.unarchiveObject(withFile: path) as? Message } }
mit
803615ba859bc0c4f0536b905195ad52
34.056338
127
0.667939
5.324064
false
false
false
false
jantimar/Weather-forecast
Weather forecast/OpenWeatheAPIManager.swift
1
17044
// // OpenWeatheAPIManager.swift // Weather forecast // // Created by Jan Timar on 6.5.2015. // Copyright (c) 2015 Jan Timar. All rights reserved. // import UIKit import MapKit import Alamofire class OpenWeatheAPIManager: NSObject { class FoundCityAnnotaion: NSObject,MKAnnotation { let title: String let coordinate: CLLocationCoordinate2D let subtitle: String let country: String init(title: String, subtitle: String,country: String, longitude: Double, latitude: Double) { self.title = title self.subtitle = subtitle self.coordinate = CLLocationCoordinate2DMake(latitude, longitude) self.country = country super.init() } } struct WeatherAPIEror { var description: String var error: NSError } struct FoundCity { var name: String var counrty: String var latitude: Double var longitude: Double var error: WeatherAPIEror? init(error: WeatherAPIEror) { self.error = error self.longitude = 0.0 self.latitude = 0.0 self.counrty = "" self.name = "" } init(name: String, counrty: String, latitude: Double, longitude: Double) { self.longitude = longitude self.latitude = latitude self.counrty = counrty self.name = name } } struct WeatherState { var city: String var counrty: String var description: String var temprature: Float? var humidity: Float? var pressure: Float? var windSpeed: Float? var windDeggree: Float? var rain: Float? var clouds: Float? var error: WeatherAPIEror? init() { city = "" counrty = "" description = "" } } struct Forecasts { var city: String var latitude: Double var longitude: Double var forecast: [Forecast]? init() { city = "" latitude = 0.0 longitude = 0.0 forecast = [Forecast]() } } struct Forecast { var tempratue: Float var description: String var error: WeatherAPIEror? init(error: WeatherAPIEror) { self.error = error self.tempratue = 0.0 self.description = "" } init(tempratue: Float, description: String) { self.tempratue = tempratue self.description = description } } func asynchronlySearchCityLike(named name: String, foundCities: (name: String, [FoundCity]) -> ()) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { //api.openweathermap.org/data/2.5/find?q=York&type=like Alamofire.request(.GET, "http://api.openweathermap.org/data/2.5/find", parameters: ["q": name, "type": "like"]) .response { (request, response, data, error) in UIApplication.sharedApplication().networkActivityIndicatorVisible = false if error != nil { foundCities(name: name, [FoundCity(error: WeatherAPIEror(description: "Cannot connect to Internet", error: error!))]) } else { if let responseData = data as? NSData { var parseError: NSError? // check if parsed data is dictionary if let parsedJsonInDictionary = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments, error:&parseError) as? [String: AnyObject] { if let cityList = parsedJsonInDictionary["list"] as? [AnyObject] { var suitableCities = [FoundCity]() for city in cityList as! [[String:AnyObject]] { if let citySys = city["sys"] as? [String:String] { if let cityName = city["name"] as? String { if let country = citySys["country"] { if let coordination = city["coord"] as? [String:Double] { if let latitude = coordination["lat"] { if let longitude = coordination["lon"]{ suitableCities.append(FoundCity(name: cityName, counrty: country, latitude: latitude, longitude: longitude)) } } } } } } } foundCities(name: name, suitableCities) } } } } } } } func asynchronlyGetForecast(forDaysForecast: Int, longitude: Double, latitude: Double, loadedForecasts:(Forecasts) -> ()) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { //api.openweathermap.org/data/2.5/forecast/daily?lat=35&lon=139&cnt=6&mode=json Alamofire.request(.GET, "http://api.openweathermap.org/data/2.5/forecast/daily", parameters: ["lat": latitude, "lon": longitude, "cnt": forDaysForecast, "mode": "json"]) .response { (request, response, data, error) in UIApplication.sharedApplication().networkActivityIndicatorVisible = false var forecasts = Forecasts() forecasts.latitude = latitude forecasts.longitude = longitude if error != nil { // TODO: Load data from database for var day = 0; day < forDaysForecast; day++ { forecasts.forecast?.append(Forecast(error: WeatherAPIEror(description: "Cannot connect to Internet", error: error!))) } loadedForecasts(forecasts) } else { if let responseData = data as? NSData { var parseError: NSError? // check if parsed data is dictionary if let parsedJsonInDictionary = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments, error:&parseError) as? [String: AnyObject] { if let city = parsedJsonInDictionary["city"] as? [String:AnyObject] { if let cityName = city["name"] as? String { forecasts.city = cityName } } if let list = parsedJsonInDictionary["list"] as? [[String:AnyObject]]{ for dayForecast in list { if let temprature = dayForecast["temp"] as? [String:Float] { if let dayTeplature = temprature["day"] { if let weathers = dayForecast["weather"] as? [AnyObject] { if let firstWeather = weathers.first as? [String:AnyObject] { if let description = firstWeather["description"] as? String { forecasts.forecast!.append(Forecast(tempratue: dayTeplature, description: description)) } } } } } } } loadedForecasts(forecasts) } } } } } } func asynchronlyGetWeatherForCoordinate(longitude: Double,latitude: Double,loadedWeather: (WeatherState) -> ()) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { //api.openweathermap.org/data/2.5/weather?lat=35&lon=139 Alamofire.request(.GET, "http://api.openweathermap.org/data/2.5/weather", parameters: ["lat": latitude, "lon": longitude]) .response { (request, response, data, error) in UIApplication.sharedApplication().networkActivityIndicatorVisible = false var weatherState = WeatherState() if error != nil { //TODO: Load data from database weatherState.error = WeatherAPIEror(description: "Cannot connect to Internet", error: error!) loadedWeather(weatherState) } else { if let responseData = data as? NSData { var parseError: NSError? // check if parsed data is dictionary if let parsedJsonInDictionary = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments, error:&parseError) as? [String: AnyObject] { if let cityName = parsedJsonInDictionary["name"] as? String { weatherState.city = cityName } if let countrySys = parsedJsonInDictionary["sys"] as? [String:AnyObject] { if let country = countrySys["country"] as? String { weatherState.counrty = country } } if let wind = parsedJsonInDictionary["wind"] as? [String:Float] { weatherState.windSpeed = wind["speed"] weatherState.windDeggree = wind["deg"] } if let main = parsedJsonInDictionary["main"] as? [String:Float] { weatherState.temprature = main["temp"] weatherState.pressure = main["pressure"] weatherState.humidity = main["humidity"] } if let weather = parsedJsonInDictionary["weather"] as? [AnyObject]{ if let firstWeather = weather.first as? [String:AnyObject] { if let description = firstWeather["description"] as? String { weatherState.description = description } } } if let clouds = parsedJsonInDictionary["clouds"] as? [String:Float] { weatherState.clouds = clouds["all"] } if let rain = parsedJsonInDictionary["rain"] as? [String:Float]{ weatherState.rain = rain["3h"] } loadedWeather(weatherState) } } } } } } func asynchronlyFoundNearstCitiesForCoordinate(longitude: Double,latitude: Double,count: Int,foundCities: (latitude: Double,longitude: Double, [FoundCityAnnotaion]) -> ()) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { //api.openweathermap.org/data/2.5/find?lat=55.5&lon=37.5&cnt=5 Alamofire.request(.GET, "http://api.openweathermap.org/data/2.5/find", parameters: ["lat": latitude, "lon": longitude, "cnt": count]) .response { (request, response, data, error) in UIApplication.sharedApplication().networkActivityIndicatorVisible = false if let responseData = data as? NSData { var parseError: NSError? // check if parsed data is dictionary if let parsedJsonInDictionary = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments, error:&parseError) as? [String: AnyObject] { var foundedCities = [FoundCityAnnotaion]() if let cities = parsedJsonInDictionary["list"] as? [AnyObject] { for city in cities { if let cityName = city["name"] as? String { if let coordination = city["coord"] as? [String:Double] { if let latitude = coordination["lat"] { if let longitude = coordination["lon"] { if let weather = city["weather"] as? [AnyObject]{ if let firstWeather = weather.first as? [String:AnyObject] { if let description = firstWeather["description"] as? String { if let sys = city["sys"] as? [String:String] { if let country = sys["country"] { foundedCities.append(FoundCityAnnotaion(title: cityName,subtitle: description, country: country,longitude: longitude, latitude: latitude)) } } } } } } } } } } } foundCities(latitude: latitude, longitude: longitude, foundedCities) } } } } } }
mit
f634e926f5c055fd9ce33f221f589c59
49.277286
214
0.412051
6.993845
false
false
false
false
izotx/iTenWired-Swift
Conference App/FNBJSocialFeed/FNBJSocialFeedTwiterController.swift
1
9981
//Copyright (c) 2016, Academic Technology Center //All rights reserved. // //Redistribution and use in source and binary forms, with or without //modification, are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, this //list of conditions and the following disclaimer. // //* Redistributions in binary form must reproduce the above copyright notice, //this list of conditions and the following disclaimer in the documentation //and/or other materials provided with the distribution. // //* Neither the name of FNBJSocialFeed nor the names of its //contributors may be used to endorse or promote products derived from //this software without specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE //IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE //DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE //FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL //DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR //SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER //CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE //OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // FNBJSocialFeedTwiterController.swift // FNBJSocialFeed // // Created by Felipe Brito on 5/31/16. // Copyright © 2016 Academic Technology Center. All rights reserved. // import Foundation import TwitterKit class FNBJSocialFeedTwitterController{ let client = TWTRAPIClient() var hashtag = "" init(hashtag: String){ self.hashtag = hashtag } func loginWithReadPermissions(viewController: UIViewController?, completion: () -> Void){ Twitter.sharedInstance().logInWithViewController(viewController) { (session, error) in print("HERE") if (error != nil) { completion() } completion() } } func hasViewPermission() -> Bool { if (Twitter.sharedInstance().sessionStore.session() == nil) { return false } return true } func favorite(tweet: FNBJSocialFeedTwitterTweet, completion: () -> Void){ if let userID = Twitter.sharedInstance().sessionStore.session()?.userID { let client = TWTRAPIClient(userID: userID) let url = "https://api.twitter.com/1.1/favorites/create.json?id=\(tweet.id)" let params = ["id": tweet.id] var clientError: NSError? let request = client.URLRequestWithMethod("POST", URL: url, parameters: params, error: &clientError) client.sendTwitterRequest(request) { (res, data, err) in if let e = err { print(e) }else if let data = data{ } } }else{ print("error") } } func retweet(tweet: FNBJSocialFeedTwitterTweet, completion: (tweet: FNBJSocialFeedTwitterTweet)->Void){ if let userID = Twitter.sharedInstance().sessionStore.session()?.userID { let client = TWTRAPIClient(userID: userID) let url = "https://api.twitter.com/1.1/statuses/retweet/\(tweet.id).json" let params = ["id": tweet.id] var clientError: NSError? let request = client.URLRequestWithMethod("POST", URL: url, parameters: params, error: &clientError) client.sendTwitterRequest(request) { (res, data, err) in if let e = err { print(e) }else if let data = data{ do { let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) let tweet = FNBJSocialFeedTwitterTweet(dictionary: json as! NSDictionary) completion(tweet: tweet) } catch let jsonError as NSError { print("json error: \(jsonError.localizedDescription)") } } } }else{ print("error") } } func reply(tweet: FNBJSocialFeedTwitterTweet, inReplyTo : FNBJSocialFeedTwitterTweet){ if let userID = Twitter.sharedInstance().sessionStore.session()?.userID { let client = TWTRAPIClient(userID: userID) let url = "https://api.twitter.com/1.1/statuses/update.json" let params = ["status": tweet.text, "in_reply_to_status_id": inReplyTo.id] var clientError: NSError? let request = client.URLRequestWithMethod("POST", URL: url, parameters: params, error: &clientError) client.sendTwitterRequest(request) { (res, data, err) in if let e = err { print(e) }else if let data = data{ } } }else{ print("error") } } func getPublicPageSocialFeed(hashTag: String, completion: (tweets: [FNBJSocialFeedTwitterTweet], paging: String) -> Void){ let statusesShowEndpoint = "https://api.twitter.com/1.1/search/tweets.json" let params = ["q": hashTag, "src": "typd"] var clientError : NSError? let request = client.URLRequestWithMethod("GET", URL: statusesShowEndpoint, parameters: params, error: &clientError) client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in if connectionError != nil { print("Error: \(connectionError)") } guard let data = data else{ return } do { let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) let statuses = json.objectForKey("statuses") as? NSArray var tweets:[FNBJSocialFeedTwitterTweet] = [] for status in statuses!{ let tweet = FNBJSocialFeedTwitterTweet(dictionary: (status as? NSDictionary)!) tweets.append(tweet) } let metaData = json.objectForKey("search_metadata") as? NSDictionary var paging = "" if let next = metaData?.objectForKey("next_results") as? String{ paging = next } print("Paging: \(paging)") completion(tweets: tweets,paging: paging) } catch let jsonError as NSError { print("json error: \(jsonError.localizedDescription)") } } } func getPublicPageSocialFeed(withPagin paging: String, completion: (tweets: [FNBJSocialFeedTwitterTweet], paging: String) -> Void){ //TODO: Twitter Paging let client = TWTRAPIClient() let url = NSURL(string: "https://api.twitter.com/1.1/search/tweets.json\(paging)") let a = NSURLRequest(URL: url!) client.sendTwitterRequest(a) { (response, data, connectionError) in if connectionError != nil { print("Error: \(connectionError)") } do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) let statuses = json.objectForKey("statuses") as? NSArray var tweets:[FNBJSocialFeedTwitterTweet] = [] for status in statuses!{ let tweet = FNBJSocialFeedTwitterTweet(dictionary: (status as? NSDictionary)!) tweets.append(tweet) } let metaData = json.objectForKey("search_metadata") as? NSDictionary var paging = "" if let next = metaData?.objectForKey("next_results") as? String{ paging = next } print("Paging: \(paging)") completion(tweets: tweets,paging: paging) } catch let jsonError as NSError { print("json error: \(jsonError.localizedDescription)") } } } func checkForNewTweets(oldTweets: [FNBJSocialFeedTwitterTweet], completion: (hasNewTweets: Bool) -> Void){ self.getPublicPageSocialFeed(self.hashtag) { (tweets, paging) in guard var new = tweets as? [FNBJSocialFeedTwitterTweet], var old = oldTweets as? [FNBJSocialFeedTwitterTweet] else{ completion(hasNewTweets: false) return } new.sortInPlace({$0.date.isGreaterThanDate($1.date)}) old.sortInPlace({$0.date.isGreaterThanDate($1.date)}) if new[0].date.isGreaterThanDate(old[0].date){ completion(hasNewTweets: true) return } } completion(hasNewTweets: false) } }
bsd-2-clause
5cdf1aa9710c3837e67bf6a66b986b2b
35.032491
135
0.542986
5.562988
false
false
false
false
XWJACK/Music
Music/Modules/Player/MusicPlayerViewController.swift
1
22462
// // MusicPlayerViewController.swift // Music // // Created by Jack on 3/16/17. // Copyright © 2017 Jack. All rights reserved. // import UIKit import MediaPlayer import Wave /// Music Player Status enum MusicPlayerStatus { case playing case paused prefix public static func !(a: MusicPlayerStatus) -> MusicPlayerStatus { return a == .playing ? .paused : .playing } } class MusicPlayerViewController: MusicViewController { //MARK: - UI property //MARK: - Base View fileprivate let backgroundImageView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "background_default_dark-ip5")) fileprivate let effectView: UIVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light)) fileprivate let maskBackgroundImageView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "player_background_mask-ip5")) fileprivate let mainView: UIView = UIView() //MARK: - Display View fileprivate let displayView: UIView = UIView() fileprivate let coverView: MusicPlayerCoverView = MusicPlayerCoverView() //MARK: - Action View fileprivate let actionView: UIView = UIView() fileprivate let downloadButton: MusicPlayerDownloadButton = MusicPlayerDownloadButton(type: .custom) fileprivate let loveButton: MusicPlayerLoveButton = MusicPlayerLoveButton(type: .custom) fileprivate let lyricTableView: UITableView = UITableView(frame: .zero, style: .grouped) //MARK: - Progress View fileprivate let progressView: UIView = UIView() fileprivate let currentTimeLabel: UILabel = UILabel() fileprivate let timeSlider: MusicPlayerSlider = MusicPlayerSlider() fileprivate let durationTimeLabel: UILabel = UILabel() //MARK: - Control View fileprivate let controlView: UIView = UIView() fileprivate let playModeButton: MusicPlayerModeButton = MusicPlayerModeButton(type: .custom) fileprivate let lastButton: UIButton = UIButton(type: .custom) fileprivate let controlButton: MusicPlayerControlButton = MusicPlayerControlButton(type: .custom) fileprivate let nextButton: UIButton = UIButton(type: .custom) fileprivate let listButton: UIButton = UIButton(type: .custom) //MARK: - Other property fileprivate var isUserInteraction: Bool = false fileprivate var player: StreamAudioPlayer? = nil fileprivate var timer: Timer? = nil fileprivate var resource: MusicResource? = nil fileprivate var lyricParser: LyricParser? fileprivate var lyricCellHeight: CGFloat = 26 fileprivate var lyricInsert: CGFloat = 12//(actionViewHeight - lyricCellHeight) / 2 var isHiddenInput: Bool { return resource == nil } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) currentTimeLabel.text = "00:00" durationTimeLabel.text = "00:00" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { view.backgroundColor = .clear musicNavigationBar.titleLabel.font = .font18 mainView.backgroundColor = UIColor.black.withAlphaComponent(0.5) displayView.addSubview(coverView) actionView.addSubview(loveButton) actionView.addSubview(downloadButton) actionView.addSubview(lyricTableView) progressView.addSubview(currentTimeLabel) progressView.addSubview(durationTimeLabel) progressView.addSubview(timeSlider) controlView.addSubview(playModeButton) controlView.addSubview(listButton) controlView.addSubview(lastButton) controlView.addSubview(controlButton) controlView.addSubview(nextButton) mainView.addSubview(maskBackgroundImageView) mainView.addSubview(displayView) mainView.addSubview(actionView) mainView.addSubview(progressView) mainView.addSubview(controlView) view.addSubview(backgroundImageView) view.addSubview(effectView) view.addSubview(mainView) super.viewDidLoad() // - Base View backgroundImageView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } effectView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } mainView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } maskBackgroundImageView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } // - Display View displayView.snp.makeConstraints { (make) in make.left.right.equalToSuperview() make.top.equalToSuperview().offset(88) } coverView.snp.makeConstraints { (make) in make.center.equalToSuperview() make.width.height.equalTo(234) } // - Action View loveButton.mode = .disable loveButton.addTarget(self, action: #selector(loveButtonClicked(_:)), for: .touchUpInside) downloadButton.addTarget(self, action: #selector(downloadButtonClicked(_:)), for: .touchUpInside) lyricTableView.backgroundColor = .clear lyricTableView.separatorStyle = .none lyricTableView.contentInset = UIEdgeInsets(top: lyricInsert, left: 0, bottom: lyricInsert, right: 0) lyricTableView.delegate = self lyricTableView.dataSource = self lyricTableView.showsVerticalScrollIndicator = false lyricTableView.showsHorizontalScrollIndicator = false lyricTableView.register(MusicLyricTableViewCell.self, forCellReuseIdentifier: MusicLyricTableViewCell.reuseIdentifier) actionView.snp.makeConstraints { (make) in make.height.equalTo(50) make.left.right.equalToSuperview() make.top.equalTo(displayView.snp.bottom) } loveButton.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(15) make.centerY.equalToSuperview() make.width.height.equalTo(40) } downloadButton.snp.makeConstraints { (make) in make.right.equalToSuperview().offset(-15) make.centerY.equalToSuperview() make.width.height.equalTo(40) } lyricTableView.snp.makeConstraints { (make) in make.left.equalTo(loveButton.snp.right).offset(15) make.right.equalTo(downloadButton.snp.left).offset(-15) make.centerY.equalToSuperview() make.top.bottom.equalToSuperview() } // - Progress View currentTimeLabel.font = .font10 currentTimeLabel.textColor = .white timeSlider.isEnabled = false timeSlider.minimumTrackTintColor = .white timeSlider.maximumTrackTintColor = UIColor.white.withAlphaComponent(0.1) timeSlider.setThumbImage(#imageLiteral(resourceName: "player_slider").scaleToSize(newSize: timeSlider.thumbImageSize), for: .normal) timeSlider.setThumbImage(#imageLiteral(resourceName: "player_slider_prs").scaleToSize(newSize: timeSlider.thumbImageSize), for: .highlighted) timeSlider.addTarget(self, action: #selector(timeSliderSeek(_:)), for: .touchUpInside) timeSlider.addTarget(self, action: #selector(timeSliderSeek(_:)), for: .touchUpOutside) timeSlider.addTarget(self, action: #selector(timeSliderValueChange(_:)), for: .valueChanged) durationTimeLabel.font = .font10 durationTimeLabel.textColor = .white progressView.snp.makeConstraints { (make) in make.height.equalTo(36) make.left.right.equalToSuperview() make.top.equalTo(actionView.snp.bottom) } currentTimeLabel.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(8) make.centerY.equalToSuperview() } durationTimeLabel.snp.makeConstraints { (make) in make.right.equalToSuperview().offset(-8) make.centerY.equalToSuperview() } timeSlider.snp.makeConstraints { (make) in make.left.equalTo(55) make.right.equalTo(-55) make.centerY.equalToSuperview() } // - Control View controlButton.mode = .paused controlButton.addTarget(self, action: #selector(controlButtonClicked(_:)), for: .touchUpInside) playModeButton.setImage(#imageLiteral(resourceName: "player_control_model_order"), for: .normal) playModeButton.setImage(#imageLiteral(resourceName: "player_control_model_order_highlighted"), for: .highlighted) playModeButton.addTarget(self, action: #selector(playModeButtonClicked(_:)), for: .touchUpInside) lastButton.setImage(#imageLiteral(resourceName: "player_control_last"), for: .normal) lastButton.setImage(#imageLiteral(resourceName: "player_control_last_press"), for: .highlighted) lastButton.addTarget(self, action: #selector(lastButtonClicked(_:)), for: .touchUpInside) nextButton.setImage(#imageLiteral(resourceName: "player_control_next"), for: .normal) nextButton.setImage(#imageLiteral(resourceName: "player_control_next_press"), for: .highlighted) nextButton.addTarget(self, action: #selector(nextButtonClicked(_:)), for: .touchUpInside) listButton.setImage(#imageLiteral(resourceName: "player_control_list"), for: .normal) listButton.setImage(#imageLiteral(resourceName: "player_control_list_press"), for: .highlighted) listButton.addTarget(self, action: #selector(listButtonClicked(_:)), for: .touchUpInside) controlView.snp.makeConstraints { (make) in make.height.equalTo(54) make.left.right.equalToSuperview() make.top.equalTo(progressView.snp.bottom) make.bottom.equalToSuperview().offset(-20) } controlButton.snp.makeConstraints { (make) in make.width.height.equalTo(54) make.center.equalToSuperview() } lastButton.snp.makeConstraints { (make) in make.right.equalTo(controlButton.snp.left).offset(-15) make.width.height.equalTo(40) make.centerY.equalToSuperview() } nextButton.snp.makeConstraints { (make) in make.left.equalTo(controlButton.snp.right).offset(15) make.width.height.equalTo(40) make.centerY.equalToSuperview() } playModeButton.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(10) make.width.height.equalTo(50) make.centerY.equalToSuperview() } listButton.snp.makeConstraints { (make) in make.right.equalToSuperview().offset(-10) make.width.height.equalTo(50) make.centerY.equalToSuperview() } } func playResource(_ resource: MusicResource = MusicResourceManager.default.current()) { reset() self.resource = resource title = resource.name backgroundImageView.kf.setImage(with: resource.album?.picUrl, placeholder: backgroundImageView.image ?? #imageLiteral(resourceName: "background_default_dark-ip5"), options: [.forceTransition, .transition(.fade(1))]) let rawDuration = resource.duration / 1000 durationTimeLabel.text = rawDuration.musicTime timeSlider.maximumValue = rawDuration.float coverView.setImage(url: resource.album?.picUrl) downloadButton.mode = resource.resourceSource == .download ? .downloaded : .download controlButton.mode = .paused MusicResourceManager.default.register(resource.id, responseBlock: { self.player?.respond(with: $0) }, lyricBlock: { (model) in if let lyric = model?.lyric { DispatchManager.default.playerQueue.async { self.lyricParser = LyricParser(lyric) DispatchManager.default.main.async { self.lyricTableView.reloadData() } } } else { DispatchManager.default.main.async { self.lyricParser = nil self.lyricTableView.reloadData() } } }, failedBlock: networkBusy) } //MARK: - Control func playCommand() { player?.play() controlButton.mode = .paused } func pauseCommand() { player?.pause() controlButton.mode = .playing } func lastTrack() { playResource(MusicResourceManager.default.last()) } func nextTrack() { playResource(MusicResourceManager.default.next()) } //MARK: - Reset fileprivate func reset() { player?.stop() player = nil destoryTimer() player = StreamAudioPlayer() player?.delegate = self timeSlider.isEnabled = false timeSlider.resetProgress() dismissBuffingStatus() MusicResourceManager.default.unRegister(resource?.id ?? "No Resource") createTimer() } //MARK: - Timer fileprivate func createTimer() { timer = Timer(timeInterval: 0.5, target: self, selector: #selector(refresh), userInfo: nil, repeats: true) RunLoop.main.add(timer!, forMode: .commonModes) } fileprivate func destoryTimer() { timer?.invalidate() timer = nil } //MARK: - Refresh @objc fileprivate func refresh() { guard !isUserInteraction, let currentTime = player?.currentTime else { return } currentTimeLabel.text = currentTime.musicTime timeSlider.value = currentTime.float updateRemoteControl(currentTime) updateLyric(currentTime) } fileprivate func updateLyric(_ time: TimeInterval) { guard let lyricParser = lyricParser else { return } /// 0..<lyricParser.timeLyric.count let index: Int = (lyricParser.timeLyric.index(where: { $0.time > time }) ?? lyricParser.timeLyric.count) - 1 let offSet: CGFloat = CGFloat(index) * lyricCellHeight - lyricInsert for i in 0..<lyricParser.timeLyric.count { guard let cell = lyricTableView.cellForRow(at: IndexPath(row: i, section: 0)) as? MusicLyricTableViewCell else { continue } i != index ? cell.normal() : cell.heightLight() } guard !lyricTableView.isDragging else { return } lyricTableView.setContentOffset(CGPoint(x: 0, y: offSet), animated: true) } fileprivate func updateRemoteControl(_ time: TimeInterval) { var info: [String: Any] = [:] info[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(image: backgroundImageView.image ?? #imageLiteral(resourceName: "background_default_dark")) info[MPMediaItemPropertyTitle] = resource?.name ?? "" info[MPNowPlayingInfoPropertyElapsedPlaybackTime] = time info[MPMediaItemPropertyPlaybackDuration] = (resource?.duration ?? 0) / 1000 MPNowPlayingInfoCenter.default().nowPlayingInfo = info } fileprivate func post(status: MusicPlayerStatus) { NotificationCenter.default.post(name: .playStatusChange, object: nil, userInfo: ["Status": status]) } //MARK: - Buffing Status fileprivate func showBuffingStatus() { player?.pause() timeSlider.loading(true) } fileprivate func dismissBuffingStatus() { timeSlider.loading(false) } } //MARK: - Progress Target extension MusicPlayerViewController { @objc fileprivate func timeSliderValueChange(_ sender: MusicPlayerSlider) { isUserInteraction = true currentTimeLabel.text = TimeInterval(sender.value).musicTime } @objc fileprivate func timeSliderSeek(_ sender: MusicPlayerSlider) { isUserInteraction = false if player?.seek(toTime: TimeInterval(sender.value)) == true { player?.play() controlButton.mode = .paused } else { showBuffingStatus() ConsoleLog.verbose("timeSliderSeek to time: " + "\(sender.value)" + " but need to watting") } } } //MARK: - Action Target extension MusicPlayerViewController { @objc fileprivate func loveButtonClicked(_ sender: MusicPlayerLoveButton) { // guard let id = resourceId else { return } // MusicNetwork.default.request(API.default.like(musicID: id, isLike: sender.mode == .love), success: { // if $0.isSuccess { sender.mode = !sender.mode } // }) } @objc fileprivate func downloadButtonClicked(_ sender: MusicPlayerDownloadButton) { switch sender.mode { case .download: guard let resource = resource else { return } MusicResourceManager.default.download(resource, successBlock: { DispatchManager.default.main.async { self.downloadButton.mode = .downloaded } }) case .downloaded: let controller = UIAlertController(title: "Delete this Music?", message: nil, preferredStyle: .alert) controller.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action) in guard let resource = self.resource else { return } DispatchManager.default.resourceQueue.async { MusicResourceManager.default.delete(resource) DispatchManager.default.main.async { sender.mode = .download self.view.makeToast("Delete Music Successful") } } })) controller.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(controller, animated: true, completion: nil) default: break } } } //MARK: - Control Target extension MusicPlayerViewController { @objc fileprivate func playModeButtonClicked(_ sender: MusicPlayerModeButton) { sender.changePlayMode() MusicResourceManager.default.resourceLoadMode = sender.mode } @objc fileprivate func controlButtonClicked(_ sender: MusicPlayerControlButton) { if sender.mode == .playing { playCommand() } else { pauseCommand() } } @objc fileprivate func lastButtonClicked(_ sender: UIButton) { lastTrack() } @objc fileprivate func nextButtonClicked(_ sender: UIButton) { nextTrack() } @objc fileprivate func listButtonClicked(_ sender: UIButton) { } } //MARK: - StreamAudioPlayerDelegate extension MusicPlayerViewController: StreamAudioPlayerDelegate { func streamAudioPlayerCompletedParsedAudioInfo(_ player: StreamAudioPlayer) { ConsoleLog.verbose("streamAudioPlayerCompletedParsedAudioInfo") DispatchManager.default.main.async { self.timeSlider.isEnabled = true } } func streamAudioPlayer(_ player: StreamAudioPlayer, didCompletedPlayFromTime time: TimeInterval) { ConsoleLog.verbose("didCompletedSeekToTime: " + "\(time)") DispatchManager.default.main.async { self.dismissBuffingStatus() guard self.controlButton.mode == .paused else { return } self.player?.play() } } func streamAudioPlayer(_ player: StreamAudioPlayer, didCompletedPlayAudio isEnd: Bool) { DispatchManager.default.main.async { if isEnd { self.nextTrack() } else { self.showBuffingStatus() } } } // func streamAudioPlayer(_ player: StreamAudioPlayer, queueStatusChange status: AudioQueueStatus) { // DispatchQueue.main.async { // switch status { // case .playing: self.controlButton.mode = .paused // case .paused: self.controlButton.mode = .playing // case .stop: self.controlButton.mode = .playing // } // } // } func streamAudioPlayer(_ player: StreamAudioPlayer, parsedProgress progress: Progress) { DispatchManager.default.main.async { self.timeSlider.buffProgress(progress) if progress.fractionCompleted > 0.01 && self.controlButton.mode == .paused { self.player?.play() } } } // func streamAudioPlayer(_ player: StreamAudioPlayer, anErrorOccur error: WaveError) { // ConsoleLog.error(error) // } } // MARK: - UITableViewDelegate extension MusicPlayerViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return lyricCellHeight } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return .leastNonzeroMagnitude } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return .leastNonzeroMagnitude } } // MARK: - UITableViewDataSource extension MusicPlayerViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return lyricParser?.timeLyric.count ?? 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: MusicLyricTableViewCell.reuseIdentifier, for: indexPath) as? MusicLyricTableViewCell else { return MusicLyricTableViewCell() } cell.indexPath = indexPath cell.normal(lyric: lyricParser?.timeLyric[indexPath.row].lyric ?? "No Lyric") return cell } }
mit
714216fc9318e5ac56fe07fe89da2c5c
37.725862
197
0.635858
5.262652
false
false
false
false
banxi1988/BXSlider
Example/BXSlider/ViewController.swift
1
1294
// // ViewController.swift // BXSlider // // Created by banxi1988 on 11/12/2015. // Copyright (c) 2015 banxi1988. All rights reserved. // import UIKit import BXSlider class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let urls = [ "http://ww2.sinaimg.cn/large/72973f93gw1exwtjow3juj216n16n151.jpg", "http://ww4.sinaimg.cn/large/72973f93gw1exmgz9wywcj216o1kwnfs.jpg", "http://ww1.sinaimg.cn/large/72973f93gw1extl2fs0zjj22ak1pxqv6.jpg", "http://ww2.sinaimg.cn/large/72973f93gw1ex8qcz2m6zj20dc0hsgnh.jpg", "http://ww3.sinaimg.cn/large/72973f93gw1ex461bmtocj20dc0hsq57.jpg", "http://ww2.sinaimg.cn/large/72973f93gw1ewqbfxchf6j218g0xc4es.jpg", ] let slides = urls.flatMap{ NSURL(string: $0)}.map{ BXSimpleSlide(imageURL: $0) } let slider = BXSlider<BXSimpleSlide>() slider.onTapBXSlideHandler = { slide in NSLog("onTapSlide \(slide.imageURL)") } slider.autoSlide = false self.view.addSubview(slider) slider.updateSlides(slides) let width = view.frame.width let height = width * 0.618 slider.frame = CGRect(x: 0, y: 0, width: width, height: height) } }
mit
d4c398585a638192b408c57b68d5f950
31.35
88
0.645286
3.133172
false
false
false
false
teambition/RefreshView
RefreshDemo/SecondViewController.swift
1
3719
// // SecondViewController.swift // RefreshDemo // // Created by ZouLiangming on 16/1/25. // Copyright © 2016年 ZouLiangming. All rights reserved. // import UIKit import RefreshView class SecondViewController: UITableViewController { var content = [String]() @objc func beginRefresh() { self.tableView.refreshHeader?.autoBeginRefreshing() } override func viewDidLoad() { super.viewDidLoad() // RefreshView.changeTarget(type: .people) self.tableView.tableFooterView = UIView() self.tableView.isShowLoadingView = true self.tableView.loadingView?.offsetY = 30 self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Refresh", style: .done, target: self, action: #selector(beginRefresh)) let minseconds = 2 * Double(NSEC_PER_SEC) let dtime = DispatchTime.now() + Double(Int64(minseconds)) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: dtime, execute: { for index in 1...10 { self.content.append(String(index)) self.tableView.reloadData() self.tableView.isShowLoadingView = false self.tableView.refreshFooter?.isShowLoadingView = true } }) self.tableView.refreshHeader = CustomRefreshHeaderView.headerWithRefreshingBlock(.white, startLoading: { let minseconds = 3 * Double(NSEC_PER_SEC) let dtime = DispatchTime.now() + Double(Int64(minseconds)) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: dtime, execute: { let count = self.content.count for index in count+1...count+5 { self.content.append(String(index)) self.tableView.reloadData() } self.tableView.refreshHeader?.endRefreshing() self.tableView.refreshFooter?.isShowLoadingView = false self.tableView.refreshHeader = nil }) }) self.tableView.refreshFooter = CustomRefreshFooterView.footerWithLoadingText("Loading More Data", startLoading: { let minseconds = 1 * Double(NSEC_PER_SEC) let dtime = DispatchTime.now() + Double(Int64(minseconds)) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: dtime, execute: { let count = self.content.count for index in count+1...count+5 { self.content.append(String(index)) self.tableView.reloadData() } self.tableView.refreshFooter?.endRefreshing() self.tableView.refreshFooter?.isShowLoadingView = count < 20 }) }) } func dismiss() { self.tableView.refreshHeader?.endRefreshing() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return self.content.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BASIC", for: indexPath) cell.textLabel?.text = self.content[(indexPath as NSIndexPath).row] return cell } }
mit
8c3630367226c90aac1e626b38626ee2
36.918367
143
0.630248
4.974565
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/Services/Interest/CustodialAccountBalanceStates.swift
1
1978
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import MoneyKit public typealias CustodialAccountBalanceState = AccountBalanceState<CustodialAccountBalance> public struct CustodialAccountBalanceStates: Equatable { // MARK: - Properties static var absent: CustodialAccountBalanceStates { CustodialAccountBalanceStates() } private var balances: [CurrencyType: CustodialAccountBalanceState] = [:] // MARK: - Subscript public subscript(currency: CurrencyType) -> CustodialAccountBalanceState { get { balances[currency] ?? .absent } set { balances[currency] = newValue } } // MARK: - Init public init(balances: [CurrencyType: CustodialAccountBalanceState] = [:]) { self.balances = balances } } extension CustodialAccountBalanceStates { // MARK: - Init init( response: CustodialBalanceResponse, enabledCurrenciesService: EnabledCurrenciesServiceAPI = resolve() ) { balances = response.balances .compactMap { item in CustodialAccountBalance( currencyCode: item.key, balance: item.value, enabledCurrenciesService: enabledCurrenciesService ) } .reduce(into: [CurrencyType: CustodialAccountBalanceState]()) { result, balance in result[balance.currency] = .present(balance) } } } extension CustodialAccountBalance { // MARK: - Init fileprivate init?( currencyCode: String, balance: CustodialBalanceResponse.Balance, enabledCurrenciesService: EnabledCurrenciesServiceAPI ) { guard let currencyType = try? CurrencyType( code: currencyCode, enabledCurrenciesService: enabledCurrenciesService ) else { return nil } self.init(currency: currencyType, response: balance) } }
lgpl-3.0
08f44e8f762a7ae87141c2c4d6d7dc91
26.84507
94
0.642387
5.780702
false
false
false
false
jopamer/swift
test/TBD/function.swift
1
1432
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=all -swift-version 4 %s // RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=all -swift-version 4 %s -enable-testing // RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=all -swift-version 4 %s -O // RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=all -swift-version 4 %s -enable-testing -O public func publicNoArgs() {} public func publicSomeArgs(_: Int, x: Int) {} public func publicWithDefault(_: Int = 0) {} internal func internalNoArgs() {} internal func internalSomeArgs(_: Int, x: Int) {} internal func internalWithDefault(_: Int = 0) {} private func privateNoArgs() {} private func privateSomeArgs(_: Int, x: Int) {} private func privateWithDefault(_: Int = 0) {} @_cdecl("c_publicNoArgs") public func publicNoArgsCDecl() {} @_cdecl("c_publicSomeArgs") public func publicSomeArgsCDecl(_: Int, x: Int) {} @_cdecl("c_publicWithDefault") public func publicWithDefaultCDecl(_: Int = 0) {} @_cdecl("c_internalNoArgs") internal func internalNoArgsCDecl() {} @_cdecl("c_internalSomeArgs") internal func internalSomeArgsCDecl(_: Int, x: Int) {} @_cdecl("c_internalWithDefault") internal func internalWithDefaultCDecl(_: Int = 0) {}
apache-2.0
19dfa1531bf8210ee6f1072a2e51582d
58.666667
155
0.726257
3.492683
false
true
false
false
rc2server/appserver
Sources/servermodel/DynamicJSON.swift
1
6046
// // DynamicJSON.swift // DynamicJSON // // Created by Saoud Rizwan on 1/1/19. // // from [Github](https://github.com/saoudrizwan/DynamicJSON.git) import Foundation @dynamicMemberLookup public enum JSON { // MARK: Cases case dictionary(Dictionary<String, JSON>) case array(Array<JSON>) case string(String) case number(NSNumber) case bool(Bool) case null // MARK: Dynamic Member Lookup public subscript(dynamicMember member: String) -> JSON { if case .dictionary(let dict) = self { return dict[member] ?? .null } return .null } // MARK: Subscript public subscript(index: Int) -> JSON { if case .array(let arr) = self { return index < arr.count ? arr[index] : .null } return .null } public subscript(key: String) -> JSON { if case .dictionary(let dict) = self { return dict[key] ?? .null } return .null } // MARK: Initializers public init(data: Data, options: JSONSerialization.ReadingOptions = .allowFragments) throws { let object = try JSONSerialization.jsonObject(with: data, options: options) self = JSON(object) } public init(_ object: Any) { if let data = object as? Data, let converted = try? JSON(data: data) { self = converted } else if let dictionary = object as? [String: Any] { self = JSON.dictionary(dictionary.mapValues { JSON($0) }) } else if let array = object as? [Any] { self = JSON.array(array.map { JSON($0) }) } else if let string = object as? String { self = JSON.string(string) } else if let bool = object as? Bool { self = JSON.bool(bool) } else if let number = object as? NSNumber { self = JSON.number(number) } else if let json = object as? JSON { self = json } else { self = JSON.null } } // MARK: Accessors public var dictionary: Dictionary<String, JSON>? { if case .dictionary(let value) = self { return value } return nil } public var array: Array<JSON>? { if case .array(let value) = self { return value } return nil } public var string: String? { if case .string(let value) = self { return value } else if case .bool(let value) = self { return value ? "true" : "false" } else if case .number(let value) = self { return value.stringValue } return nil } public var number: NSNumber? { if case .number(let value) = self { return value } else if case .bool(let value) = self { return NSNumber(value: value) } else if case .string(let value) = self, let doubleValue = Double(value) { return NSNumber(value: doubleValue) } return nil } public var double: Double? { return number?.doubleValue } public var int: Int? { return number?.intValue } public var bool: Bool? { if case .bool(let value) = self { return value } else if case .number(let value) = self { return value.boolValue } else if case .string(let value) = self, (["true", "t", "yes", "y", "1"].contains { value.caseInsensitiveCompare($0) == .orderedSame }) { return true } else if case .string(let value) = self, (["false", "f", "no", "n", "0"].contains { value.caseInsensitiveCompare($0) == .orderedSame }) { return false } return nil } // MARK: Helpers public var object: Any { get { switch self { case .dictionary(let value): return value.mapValues { $0.object } case .array(let value): return value.map { $0.object } case .string(let value): return value case .number(let value): return value case .bool(let value): return value case .null: return NSNull() } } } public func data(options: JSONSerialization.WritingOptions = []) -> Data { return (try? JSONSerialization.data(withJSONObject: self.object, options: options)) ?? Data() } } // MARK: - Comparable extension JSON: Comparable { public static func == (lhs: JSON, rhs: JSON) -> Bool { switch (lhs, rhs) { case (.dictionary, .dictionary): return lhs.dictionary == rhs.dictionary case (.array, .array): return lhs.array == rhs.array case (.string, .string): return lhs.string == rhs.string case (.number, .number): return lhs.number == rhs.number case (.bool, .bool): return lhs.bool == rhs.bool case (.null, .null): return true default: return false } } public static func < (lhs: JSON, rhs: JSON) -> Bool { switch (lhs, rhs) { case (.string, .string): if let lhsString = lhs.string, let rhsString = rhs.string { return lhsString < rhsString } return false case (.number, .number): if let lhsNumber = lhs.number, let rhsNumber = rhs.number { return lhsNumber.doubleValue < rhsNumber.doubleValue } return false default: return false } } } // MARK: - ExpressibleByLiteral extension JSON: Swift.ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, Any)...) { let dictionary = elements.reduce(into: [String: Any](), { $0[$1.0] = $1.1}) self.init(dictionary) } } extension JSON: Swift.ExpressibleByArrayLiteral { public init(arrayLiteral elements: Any...) { self.init(elements) } } extension JSON: Swift.ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value) } } extension JSON: Swift.ExpressibleByFloatLiteral { public init(floatLiteral value: FloatLiteralType) { self.init(value) } } extension JSON: Swift.ExpressibleByIntegerLiteral { public init(integerLiteral value: IntegerLiteralType) { self.init(value) } } extension JSON: Swift.ExpressibleByBooleanLiteral { public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } } // MARK: - Pretty Print extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { public var description: String { return String(describing: self.object as AnyObject).replacingOccurrences(of: ";\n", with: "\n") } public var debugDescription: String { return description } }
isc
428fb0bca3d01dc12f6d57d43be77963
22.80315
99
0.672345
3.379542
false
false
false
false
antrix1989/PhotoSlider
Example/PhotoSliderDemo/ViewController.swift
1
5387
// // ViewController.swift // PhotoSliderDemo // // Created by nakajijapan on 4/12/15. // Copyright (c) 2015 net.nakajijapan. All rights reserved. // import UIKit import PhotoSlider class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, PhotoSliderDelegate { @IBOutlet var tableView:UITableView! var collectionView:UICollectionView! var imageURLs = [ NSURL(string:"https://raw.githubusercontent.com/nakajijapan/PhotoSlider/master/Example/Resources/image001.jpg")!, NSURL(string:"https://raw.githubusercontent.com/nakajijapan/PhotoSlider/master/Example/Resources/image002.jpg")!, NSURL(string:"https://raw.githubusercontent.com/nakajijapan/PhotoSlider/master/Example/Resources/image003.jpg")!, NSURL(string:"https://raw.githubusercontent.com/nakajijapan/PhotoSlider/master/Example/Resources/image004.jpg")!, NSURL(string:"https://raw.githubusercontent.com/nakajijapan/PhotoSlider/master/Example/Resources/image005.jpg")!, NSURL(string:"https://raw.githubusercontent.com/nakajijapan/PhotoSlider/master/Example/Resources/image006.jpg")!, NSURL(string:"https://raw.githubusercontent.com/nakajijapan/PhotoSlider/master/Example/Resources/image007.jpg")!, NSURL(string:"https://raw.githubusercontent.com/nakajijapan/PhotoSlider/master/Example/Resources/image008.jpg")!, ] override func prefersStatusBarHidden() -> Bool { return false } override func viewDidLayoutSubviews() { if self.collectionView != nil { self.collectionView.reloadData() } } // MARK: - UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = self.tableView.dequeueReusableCellWithIdentifier("cell01") as! UITableViewCell self.collectionView = cell.viewWithTag(1) as! UICollectionView self.collectionView.delegate = self self.collectionView.dataSource = self return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row == 0 { if UIDevice.currentDevice().orientation == UIDeviceOrientation.Portrait || UIDevice.currentDevice().orientation == UIDeviceOrientation.PortraitUpsideDown { return tableView.bounds.size.width } else { return tableView.bounds.size.height } } return 0.0; } // MARK: - UICollectionViewDataSource func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.imageURLs.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell = collectionView.dequeueReusableCellWithReuseIdentifier("hcell", forIndexPath: indexPath) as! UICollectionViewCell var imageView = cell.viewWithTag(1) as! UIImageView imageView.sd_setImageWithURL(self.imageURLs[indexPath.row]) return cell } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { if UIDevice.currentDevice().orientation == UIDeviceOrientation.Portrait || UIDevice.currentDevice().orientation == UIDeviceOrientation.PortraitUpsideDown { return CGSize(width:collectionView.bounds.size.width, height:collectionView.bounds.size.width) } else { return CGSize(width:self.tableView.bounds.size.width, height:collectionView.bounds.size.height) } } // MARK: - UICollectionViewDelegate func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { var photoSlider = PhotoSlider.ViewController(imageURLs: self.imageURLs) photoSlider.modalPresentationStyle = .OverCurrentContext photoSlider.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve photoSlider.delegate = self photoSlider.index = indexPath.row UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: UIStatusBarAnimation.Fade) self.presentViewController(photoSlider, animated: true, completion: nil) } // MARK: - PhotoSliderDelegate func photoSliderControllerWillDismiss(viewController: PhotoSlider.ViewController) { UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: UIStatusBarAnimation.Fade) } // MARK: - UIContentContainer internal override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { self.tableView.reloadData() } }
mit
7f7675ed40624476308a89b059b083c3
40.122137
195
0.715426
5.804957
false
false
false
false
Scior/Spica
Spica/ExifViewController.swift
1
2444
// // ExifViewController.swift // Spica // // Created by Scior on 2017/06/27. // Copyright © 2017年 Scior All rights reserved. // import UIKit class ExifViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let titles = ["カメラ", "レンズ", "焦点距離", "絞り", "シャッタースピード", "ISO", "露出プログラム", "露出", "撮影日時"] var values = (0...8).map{_ in ""} @IBOutlet weak var exifTableView: UITableView! @IBAction func close(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() guard let photo = (presentingViewController as? ImageViewController)?.photo else { return } Flickr.shared.getExif(photo: photo) { [weak self] exif in guard let weakSelf = self else { return } weakSelf.values[0] = exif.camera weakSelf.values[1] = exif.lensModel weakSelf.values[2] = exif.focalLength weakSelf.values[3] = exif.aperture weakSelf.values[4] = exif.exposureTime weakSelf.values[5] = exif.ISO weakSelf.values[6] = exif.exposureProgram weakSelf.values[7] = exif.exposureCompensation weakSelf.values[8] = exif.dateTime weakSelf.exifTableView.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return titles.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = exifTableView.dequeueReusableCell(withIdentifier: "exifValue", for: indexPath) cell.textLabel?.text = "\(titles[indexPath.row]): \(values[indexPath.row])" return cell } /* // 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. } */ }
mit
97c58f8f2272bda3f018bade11d78cc9
31.506849
106
0.622419
4.537285
false
false
false
false
soyabi/wearableD
WearableD/BLECentral.swift
2
7159
// // BLECentral.swift // WearableD // // Created by Ryan Ford on 1/14/15. // Copyright (c) 2015 Intuit. All rights reserved. // import Foundation import CoreBluetooth protocol BLECentralDelegate { func bleCentralStatusUpdate (update : String) func bleCentralIsReady() func bleCentralCharactoristicValueUpdate (update: String) func bleDidEncouneterError(error : NSError) func bleCentralDidStop() } class BLECentral : NSObject, CBCentralManagerDelegate, CBPeripheralDelegate { var devices: CBPeripheral? = nil var myCentralManager : CBCentralManager? = nil var delegate : BLECentralDelegate? = nil let wctService = BLEIDs.wctService init (delegate : BLECentralDelegate) { self.delegate = delegate super.init() } func openBLECentral() { closeBLECentral() myCentralManager = CBCentralManager(delegate: self, queue : nil) } func closeBLECentral() { if self.myCentralManager != nil { myCentralManager?.stopScan() if self.devices != nil { myCentralManager?.cancelPeripheralConnection(self.devices) } self.delegate?.bleCentralDidStop() } self.devices = nil self.myCentralManager = nil } //delegate method called after CBCentralManager constructor func centralManagerDidUpdateState(central: CBCentralManager!) { var statusMsg = "Bluetooth LE error..." switch central.state { case .Unknown: statusMsg = "Bluetoothe LE state is unknown" case .Unsupported: statusMsg = "Bluetooth LE is not supported on this device" case .Unauthorized: statusMsg = "Needs your approval to use Bluetooth LE on this device" case .Resetting: statusMsg = "Bluetooth LE is resetting, please wait..." case .PoweredOff: statusMsg = "Please turn on Bluetooth from settings and come back" default: statusMsg = "Bluetooth LE is ready..." } //make sure the device has bluetooth turned on if central.state == .PoweredOn { //once it is on scan for peripherals - nil will find everything. typically should pass a UUID as frist arg myCentralManager?.scanForPeripheralsWithServices([wctService], options: nil) //myCentralManager?.scanForPeripheralsWithServices(nil, options: nil) statusMsg = "Searching for device ..." self.delegate?.bleCentralIsReady() } else { println("needs state: CBcentralState.PoweredOn, but got \(central.state.rawValue). quit.") } self.delegate?.bleCentralStatusUpdate(statusMsg) } //delegate called when a peripheral is found func centralManager(central: CBCentralManager!, didDiscoverPeripheral peripheral: CBPeripheral!, advertisementData: [NSObject : AnyObject]!, RSSI: NSNumber!) { var name = peripheral!.name == nil ? "" : peripheral!.name self.delegate?.bleCentralStatusUpdate("Found Peripheral: \(name). Connecting...") devices = peripheral myCentralManager?.connectPeripheral(peripheral, options: nil) } //delegate called when a peripheral connects func centralManager(central: CBCentralManager!, didConnectPeripheral peripheral: CBPeripheral!) { self.delegate?.bleCentralStatusUpdate("Peripheral Connected. Scanning will stop and start to look for services...") //stop scaning after per conection myCentralManager?.stopScan(); peripheral.delegate = self //pass service uuid here //peripheral.discoverServices(nil) peripheral.discoverServices([wctService]) } //delegate called when a service is called func peripheral(peripheral: CBPeripheral!, didDiscoverServices error: NSError!) { if (error != nil) { self.delegate?.bleDidEncouneterError(error) println("there was an error contecting to the service") } else { for service in peripheral.services { self.delegate?.bleCentralStatusUpdate("Service Found: \(service.UUIDString). Start to look for characteristics...") peripheral.discoverCharacteristics(nil, forService : service as! CBService) } } } func peripheral(peripheral: CBPeripheral!, didDiscoverCharacteristicsForService service: CBService!, error: NSError!) { if (error != nil) { self.delegate?.bleDidEncouneterError(error) println("there was an error discovering char") } else { for characteristic in service.characteristics { self.delegate?.bleCentralStatusUpdate("Characteristic Found: \(characteristic.UUIDString). Start to subscribe value updates...") //peripheral.readValueForCharacteristic(characteristic as CBCharacteristic) //subscibe to value updates peripheral.setNotifyValue(true, forCharacteristic : characteristic as! CBCharacteristic) } } } //delgate called when attempting to read a value from a char func peripheral(peripheral: CBPeripheral!, didUpdateValueForCharacteristic characteristic: CBCharacteristic!, error: NSError!) { if error != nil { self.delegate?.bleDidEncouneterError(error) println("there was an error reading char value") } else { self.delegate?.bleCentralStatusUpdate("Read characteristic Value") var rawValue = NSString(data: characteristic.value, encoding: NSUTF8StringEncoding) if let value = rawValue { println("data read from characteristic - \(value)") self.delegate?.bleCentralCharactoristicValueUpdate(value as String) } else { self.delegate?.bleCentralCharactoristicValueUpdate("No Value Found") } } } //delegate called when attempting to subsribe to a char func peripheral(peripheral: CBPeripheral!, didUpdateNotificationStateForCharacteristic characteristic: CBCharacteristic!, error: NSError!) { var rawValue : NSString? if error != nil { self.delegate?.bleDidEncouneterError(error) println("error subscribing to char") } else { self.delegate?.bleCentralStatusUpdate("Subscribing to characteristic Value") if characteristic.value != nil { rawValue = NSString(data: characteristic.value, encoding: NSUTF8StringEncoding) if let value = rawValue { self.delegate?.bleCentralCharactoristicValueUpdate(value as String) println("data updated from characteristic - \(value)") } else { self.delegate?.bleCentralCharactoristicValueUpdate("No Value Found") } } } } }
apache-2.0
573bd841fbada2ea8284a451dbf09da7
38.777778
163
0.63277
5.718051
false
false
false
false
hacsoc/hack_cwru-ios
HackCWRU App/Helpers/HTTPHelper.swift
1
1442
// // HTTPHelper.swift // HackCWRU // // Created by Andrew Mason on 5/24/15. // Copyright (c) 2015 CWRU Hacker Society. All rights reserved. // import Foundation class HTTPHelper { // Exectue a GET request. Returns the data returned from the request as NSData. // Caller is responsible for knowing how the data should be structured and // casting appropratiely. // // :url: - The URL to which to send the request. // :params: (optional) - Any query params to append to the URL. class func get(url: String, params: NSDictionary = NSDictionary()) throws -> NSData { let url = NSURL(string: url + self.queryString(params))! let request = NSURLRequest(URL: url) let response:AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil return try NSURLConnection.sendSynchronousRequest(request, returningResponse: response) } // Return a query string to be appended to a URL. // // Currently does not support nested parameters/dictonaries (i.e. param[sub_param]=blah) // // :params: - dictionary of param names to values to be in the query string private class func queryString(params: NSDictionary) -> String { if params.count == 0 { return "" } var query = [String]() for (k, v) in params { query.append("\(k)=\(v)") } return "?" + query.joinWithSeparator("&") } }
mit
314613977720285e0187a381177ee38e
34.170732
95
0.635922
4.291667
false
false
false
false
gavinbunney/Toucan
Source/Toucan.swift
1
29148
// Toucan.swift // // Copyright (c) 2014-2019 Gavin Bunney // // 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 import CoreGraphics /** Toucan - Fabulous Image Processing in Swift. The Toucan class provides two methods of interaction - either through an instance, wrapping an single image, or through the static functions, providing an image for each invocation. This allows for some flexible usage. Using static methods when you need a single operation: let resizedImage = Toucan.resize(myImage, size: CGSize(width: 100, height: 150)) Or create an instance for easy method chaining: let resizedAndMaskedImage = Toucan(withImage: myImage).resize(CGSize(width: 100, height: 150)).maskWithEllipse().image */ public class Toucan : NSObject { #if swift(>=4.2) internal typealias ImageOrientation = UIImage.Orientation #else internal typealias ImageOrientation = UIImageOrientation #endif public var image : UIImage? public init(image withImage: UIImage) { self.image = withImage } // MARK: - Resize /** Resize the contained image to the specified size. Depending on what fitMode is supplied, the image may be clipped, cropped or scaled. @see documentation on FitMode. The current image on this toucan instance is replaced with the resized image. - parameter size: Size to resize the image to - parameter fitMode: How to handle the image resizing process - returns: Self, allowing method chaining */ public func resize(_ size: CGSize, fitMode: Toucan.Resize.FitMode = .clip) -> Toucan { if let image = self.image { self.image = Toucan.Resize.resizeImage(image, size: size, fitMode: fitMode) } return self } /** Resize the contained image to the specified size by resizing the image to fit within the width and height boundaries without cropping or scaling the image. The current image on this toucan instance is replaced with the resized image. - parameter size: Size to resize the image to - returns: Self, allowing method chaining */ @objc public func resizeByClipping(_ size: CGSize) -> Toucan { if let image = self.image { self.image = Toucan.Resize.resizeImage(image, size: size, fitMode: .clip) } return self } /** Resize the contained image to the specified size by resizing the image to fill the width and height boundaries and crops any excess image data. The resulting image will match the width and height constraints without scaling the image. The current image on this toucan instance is replaced with the resized image. - parameter size: Size to resize the image to - returns: Self, allowing method chaining */ @objc public func resizeByCropping(_ size: CGSize) -> Toucan { if let image = self.image { self.image = Toucan.Resize.resizeImage(image, size: size, fitMode: .crop) } return self } /** Resize the contained image to the specified size by scaling the image to fit the constraining dimensions exactly. The current image on this toucan instance is replaced with the resized image. - parameter size: Size to resize the image to - returns: Self, allowing method chaining */ @objc public func resizeByScaling(_ size: CGSize) -> Toucan { if let image = self.image { self.image = Toucan.Resize.resizeImage(image, size: size, fitMode: .scale) } return self } /** Container struct for all things Resize related */ public struct Resize { /** FitMode drives the resizing process to determine what to do with an image to make it fit the given size bounds. - Clip: Resizes the image to fit within the width and height boundaries without cropping or scaling the image. - Crop: Resizes the image to fill the width and height boundaries and crops any excess image data. - Scale: Scales the image to fit the constraining dimensions exactly. */ public enum FitMode { /** Resizes the image to fit within the width and height boundaries without cropping or scaling the image. The resulting image is assured to match one of the constraining dimensions, while the other dimension is altered to maintain the same aspect ratio of the input image. */ case clip /** Resizes the image to fill the width and height boundaries and crops any excess image data. The resulting image will match the width and height constraints without scaling the image. */ case crop /** Scales the image to fit the constraining dimensions exactly. */ case scale } /** Resize an image to the specified size. Depending on what fitMode is supplied, the image may be clipped, cropped or scaled. @see documentation on FitMode. - parameter image: Image to Resize - parameter size: Size to resize the image to - parameter fitMode: How to handle the image resizing process - returns: Resized image */ public static func resizeImage(_ image: UIImage, size: CGSize, fitMode: FitMode = .clip) -> UIImage? { let imgRef = Util.CGImageWithCorrectOrientation(image) let originalWidth = CGFloat(imgRef.width) let originalHeight = CGFloat(imgRef.height) let widthRatio = size.width / originalWidth let heightRatio = size.height / originalHeight let scaleRatio = fitMode == .clip ? min(heightRatio, widthRatio) : max(heightRatio, widthRatio) let resizedImageBounds = CGRect(x: 0, y: 0, width: round(originalWidth * scaleRatio), height: round(originalHeight * scaleRatio)) let resizedImage = Util.drawImageInBounds(image, bounds: resizedImageBounds) guard resizedImage != nil else { return nil } switch (fitMode) { case .clip: return resizedImage case .crop: let croppedRect = CGRect(x: (resizedImage!.size.width - size.width) / 2, y: (resizedImage!.size.height - size.height) / 2, width: size.width, height: size.height) return Util.croppedImageWithRect(resizedImage!, rect: croppedRect) case .scale: return Util.drawImageInBounds(resizedImage!, bounds: CGRect(x: 0, y: 0, width: size.width, height: size.height)) } } } // MARK: - Mask /** Mask the contained image with another image mask. Note that the areas in the original image that correspond to the black areas of the mask show through in the resulting image. The areas that correspond to the white areas of the mask aren’t painted. The areas that correspond to the gray areas in the mask are painted using an intermediate alpha value that’s equal to 1 minus the image mask sample value. - parameter maskImage: Image Mask to apply to the Image - returns: Self, allowing method chaining */ public func maskWithImage(maskImage : UIImage) -> Toucan { if let image = self.image { self.image = Toucan.Mask.maskImageWithImage(image, maskImage: maskImage) } return self } /** Mask the contained image with an ellipse. Allows specifying an additional border to draw on the clipped image. For a circle, ensure the image width and height are equal! - parameter borderWidth: Optional width of the border to apply - default 0 - parameter borderColor: Optional color of the border - default White - returns: Self, allowing method chaining */ public func maskWithEllipse(borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.white) -> Toucan { if let image = self.image { self.image = Toucan.Mask.maskImageWithEllipse(image, borderWidth: borderWidth, borderColor: borderColor) } return self } /** Mask the contained image with a path (UIBezierPath) that will be scaled to fit the image. - parameter path: UIBezierPath to mask the image - returns: Self, allowing method chaining */ public func maskWithPath(path: UIBezierPath) -> Toucan { if let image = self.image { self.image = Toucan.Mask.maskImageWithPath(image, path: path) } return self } /** Mask the contained image with a path (UIBezierPath) which is provided via a closure. - parameter path: closure that returns a UIBezierPath. Using a closure allows the user to provide the path after knowing the size of the image - returns: Self, allowing method chaining */ public func maskWithPathClosure(path: (_ rect: CGRect) -> (UIBezierPath)) -> Toucan { if let image = self.image { self.image = Toucan.Mask.maskImageWithPathClosure(image, pathInRect: path) } return self } /** Mask the contained image with a rounded rectangle border. Allows specifying an additional border to draw on the clipped image. - parameter cornerRadius: Radius of the rounded rect corners - parameter borderWidth: Optional width of border to apply - default 0 - parameter borderColor: Optional color of the border - default White - returns: Self, allowing method chaining */ public func maskWithRoundedRect(cornerRadius: CGFloat, borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.white) -> Toucan { if let image = self.image { self.image = Toucan.Mask.maskImageWithRoundedRect(image, cornerRadius: cornerRadius, borderWidth: borderWidth, borderColor: borderColor) } return self } /** Container struct for all things Mask related */ public struct Mask { /** Mask the given image with another image mask. Note that the areas in the original image that correspond to the black areas of the mask show through in the resulting image. The areas that correspond to the white areas of the mask aren’t painted. The areas that correspond to the gray areas in the mask are painted using an intermediate alpha value that’s equal to 1 minus the image mask sample value. - parameter image: Image to apply the mask to - parameter maskImage: Image Mask to apply to the Image - returns: Masked image */ public static func maskImageWithImage(_ image: UIImage, maskImage: UIImage) -> UIImage? { let imgRef = Util.CGImageWithCorrectOrientation(image) let maskRef = maskImage.cgImage let mask = CGImage(maskWidth: (maskRef?.width)!, height: (maskRef?.height)!, bitsPerComponent: (maskRef?.bitsPerComponent)!, bitsPerPixel: (maskRef?.bitsPerPixel)!, bytesPerRow: (maskRef?.bytesPerRow)!, provider: (maskRef?.dataProvider!)!, decode: nil, shouldInterpolate: false); let masked = imgRef.masking(mask!); return Util.drawImageWithClosure(size: image.size, scale: image.scale) { (size: CGSize, context: CGContext) -> UIImage? in // need to flip the transform matrix, CoreGraphics has (0,0) in lower left when drawing image context.scaleBy(x: 1, y: -1) context.translateBy(x: 0, y: -size.height) context.draw(masked!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height)); let image : UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } } /** Mask the given image with an ellipse. Allows specifying an additional border to draw on the clipped image. For a circle, ensure the image width and height are equal! - parameter image: Image to apply the mask to - parameter borderWidth: Optional width of the border to apply - default 0 - parameter borderColor: Optional color of the border - default White - returns: Masked image */ public static func maskImageWithEllipse(_ image: UIImage, borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.white) -> UIImage? { let imgRef = Util.CGImageWithCorrectOrientation(image) let size = CGSize(width: CGFloat(imgRef.width) / image.scale, height: CGFloat(imgRef.height) / image.scale) return Util.drawImageWithClosure(size: size, scale: image.scale) { (size: CGSize, context: CGContext) -> UIImage? in let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) context.addEllipse(in: rect) context.clip() image.draw(in: rect) if (borderWidth > 0) { context.setStrokeColor(borderColor.cgColor); context.setLineWidth(borderWidth); context.addEllipse(in: CGRect(x: borderWidth / 2, y: borderWidth / 2, width: size.width - borderWidth, height: size.height - borderWidth)); context.strokePath(); } let image : UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } } /** Mask the given image with a path(UIBezierPath) that will be scaled to fit the image. - parameter image: Image to apply the mask to - parameter path: UIBezierPath to make as the mask - returns: Masked image */ public static func maskImageWithPath(_ image: UIImage, path: UIBezierPath) -> UIImage? { let imgRef = Util.CGImageWithCorrectOrientation(image) let size = CGSize(width: CGFloat(imgRef.width) / image.scale, height: CGFloat(imgRef.height) / image.scale) return Util.drawImageWithClosure(size: size, scale: image.scale) { (size: CGSize, context: CGContext) -> UIImage? in let boundSize = path.bounds.size let pathRatio = boundSize.width / boundSize.height let imageRatio = size.width / size.height if pathRatio > imageRatio { //scale based on width let scale = size.width / boundSize.width path.apply(CGAffineTransform(scaleX: scale, y: scale)) path.apply(CGAffineTransform(translationX: 0, y: (size.height - path.bounds.height) / 2.0)) } else { //scale based on height let scale = size.height / boundSize.height path.apply(CGAffineTransform(scaleX: scale, y: scale)) path.apply(CGAffineTransform(translationX: (size.width - path.bounds.width) / 2.0, y: 0)) } let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) context.addPath(path.cgPath) context.clip() image.draw(in: rect) let image : UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } } /** Mask the given image with a path(UIBezierPath) provided via a closure. This allows the user to get the size of the image before computing their path variable. - parameter image: Image to apply the mask to - parameter path: UIBezierPath to make as the mask - returns: Masked image */ public static func maskImageWithPathClosure(_ image: UIImage, pathInRect:(_ rect: CGRect) -> (UIBezierPath)) -> UIImage? { let imgRef = Util.CGImageWithCorrectOrientation(image) let size = CGSize(width: CGFloat(imgRef.width) / image.scale, height: CGFloat(imgRef.height) / image.scale) return maskImageWithPath(image, path: pathInRect(CGRect(x: 0, y: 0, width: size.width, height: size.height))) } /** Mask the given image with a rounded rectangle border. Allows specifying an additional border to draw on the clipped image. - parameter image: Image to apply the mask to - parameter cornerRadius: Radius of the rounded rect corners - parameter borderWidth: Optional width of border to apply - default 0 - parameter borderColor: Optional color of the border - default White - returns: Masked image */ public static func maskImageWithRoundedRect(_ image: UIImage, cornerRadius: CGFloat, borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.white) -> UIImage? { let imgRef = Util.CGImageWithCorrectOrientation(image) let size = CGSize(width: CGFloat(imgRef.width) / image.scale, height: CGFloat(imgRef.height) / image.scale) return Util.drawImageWithClosure(size: size, scale: image.scale) { (size: CGSize, context: CGContext) -> UIImage? in let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIBezierPath(roundedRect:rect, cornerRadius: cornerRadius).addClip() image.draw(in: rect) if (borderWidth > 0) { context.setStrokeColor(borderColor.cgColor); context.setLineWidth(borderWidth); let borderRect = CGRect(x: 0, y: 0, width: size.width, height: size.height) let borderPath = UIBezierPath(roundedRect: borderRect, cornerRadius: cornerRadius) borderPath.lineWidth = borderWidth * 2 borderPath.stroke() } let image : UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } } } // MARK: - Layer /** Overlay an image ontop of the current image. - parameter image: Image to be on the bottom layer - parameter overlayImage: Image to be on the top layer, i.e. drawn on top of image - parameter overlayFrame: Frame of the overlay image - returns: Self, allowing method chaining */ public func layerWithOverlayImage(_ overlayImage: UIImage, overlayFrame: CGRect) -> Toucan { if let image = self.image { self.image = Toucan.Layer.overlayImage(image, overlayImage:overlayImage, overlayFrame:overlayFrame) } return self } /** Container struct for all things Layer related. */ public struct Layer { /** Overlay the given image into a new layout ontop of the image. - parameter image: Image to be on the bottom layer - parameter overlayImage: Image to be on the top layer, i.e. drawn on top of image - parameter overlayFrame: Frame of the overlay image - returns: Masked image */ public static func overlayImage(_ image: UIImage, overlayImage: UIImage, overlayFrame: CGRect) -> UIImage? { let imgRef = Util.CGImageWithCorrectOrientation(image) let size = CGSize(width: CGFloat(imgRef.width) / image.scale, height: CGFloat(imgRef.height) / image.scale) return Util.drawImageWithClosure(size: size, scale: image.scale) { (size: CGSize, context: CGContext) -> UIImage? in let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) image.draw(in: rect) overlayImage.draw(in: overlayFrame); let image : UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } } } /** Container struct for internally used utility functions. */ internal struct Util { /** Get the CGImage of the image with the orientation fixed up based on EXF data. This helps to normalise input images to always be the correct orientation when performing other core graphics tasks on the image. - parameter image: Image to create CGImageRef for - returns: CGImageRef with rotated/transformed image context */ static func CGImageWithCorrectOrientation(_ image : UIImage) -> CGImage { if (image.imageOrientation == ImageOrientation.up) { return image.cgImage! } var transform : CGAffineTransform = CGAffineTransform.identity; switch (image.imageOrientation) { case ImageOrientation.right, ImageOrientation.rightMirrored: transform = transform.translatedBy(x: 0, y: image.size.height) transform = transform.rotated(by: .pi / -2.0) break case ImageOrientation.left, ImageOrientation.leftMirrored: transform = transform.translatedBy(x: image.size.width, y: 0) transform = transform.rotated(by: .pi / 2.0) break case ImageOrientation.down, ImageOrientation.downMirrored: transform = transform.translatedBy(x: image.size.width, y: image.size.height) transform = transform.rotated(by: .pi) break default: break } switch (image.imageOrientation) { case ImageOrientation.rightMirrored, ImageOrientation.leftMirrored: transform = transform.translatedBy(x: image.size.height, y: 0); transform = transform.scaledBy(x: -1, y: 1); break case ImageOrientation.downMirrored, ImageOrientation.upMirrored: transform = transform.translatedBy(x: image.size.width, y: 0); transform = transform.scaledBy(x: -1, y: 1); break default: break } let contextWidth : Int let contextHeight : Int switch (image.imageOrientation) { case ImageOrientation.left, ImageOrientation.leftMirrored, ImageOrientation.right, ImageOrientation.rightMirrored: contextWidth = (image.cgImage?.height)! contextHeight = (image.cgImage?.width)! break default: contextWidth = (image.cgImage?.width)! contextHeight = (image.cgImage?.height)! break } let context : CGContext = CGContext(data: nil, width: contextWidth, height: contextHeight, bitsPerComponent: image.cgImage!.bitsPerComponent, bytesPerRow: 0, space: image.cgImage!.colorSpace!, bitmapInfo: image.cgImage!.bitmapInfo.rawValue)!; context.concatenate(transform); context.draw(image.cgImage!, in: CGRect(x: 0, y: 0, width: CGFloat(contextWidth), height: CGFloat(contextHeight))); let cgImage = context.makeImage(); return cgImage!; } /** Draw the image within the given bounds (i.e. resizes) - parameter image: Image to draw within the given bounds - parameter bounds: Bounds to draw the image within - returns: Resized image within bounds */ static func drawImageInBounds(_ image: UIImage, bounds : CGRect) -> UIImage? { return drawImageWithClosure(size: bounds.size, scale: image.scale) { (size: CGSize, context: CGContext) -> UIImage? in image.draw(in: bounds) let image : UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image }; } /** Crop the image within the given rect (i.e. resizes and crops) - parameter image: Image to clip within the given rect bounds - parameter rect: Bounds to draw the image within - returns: Resized and cropped image */ static func croppedImageWithRect(_ image: UIImage, rect: CGRect) -> UIImage? { return drawImageWithClosure(size: rect.size, scale: image.scale) { (size: CGSize, context: CGContext) -> UIImage? in let drawRect = CGRect(x: -rect.origin.x, y: -rect.origin.y, width: image.size.width, height: image.size.height) context.clip(to: CGRect(x: 0, y: 0, width: rect.size.width, height: rect.size.height)) image.draw(in: drawRect) let image : UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image }; } /** Closure wrapper around image context - setting up, ending and grabbing the image from the context. - parameter size: Size of the graphics context to create - parameter closure: Closure of magic to run in a new context - returns: Image pulled from the end of the closure */ static func drawImageWithClosure(size: CGSize!, scale: CGFloat, closure: @escaping (_ size: CGSize, _ context: CGContext) -> UIImage?) -> UIImage? { guard size.width > 0.0 && size.height > 0.0 else { print("WARNING: Invalid size requested: \(size.width) x \(size.height) - must not be 0.0 in any dimension") return nil } UIGraphicsBeginImageContextWithOptions(size, false, scale) guard let context = UIGraphicsGetCurrentContext() else { print("WARNING: Graphics context is nil!") return nil } return closure(size, context) } } }
mit
dcbb0001d677ce84e8ff984e5be59afa
42.17037
167
0.583802
5.449785
false
false
false
false
MartinOSix/DemoKit
dSwift/SwiftDemoKit/SwiftDemoKit/CustomeCollectionViewController.swift
1
2779
// // CustomeCollectionViewController.swift // SwiftDemoKit // // Created by runo on 17/5/16. // Copyright © 2017年 com.runo. All rights reserved. // import UIKit class CustomeCollectionViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { let tableView = UITableView(frame: kScreenBounds, style: .plain) let reuseIdentifer = String(describing: UITableViewCell.self) let datas = ["瀑布流","圆形","线性"] override func viewDidLoad() { super.viewDidLoad() title = "选择布局" self.navigationController?.navigationBar.isTranslucent = false self.automaticallyAdjustsScrollViewInsets = true tableView.separatorStyle = .none //tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0) tableView.delegate = self tableView.dataSource = self tableView.tableFooterView = UIView() tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifer) view.addSubview(tableView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return datas.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifer, for: indexPath) cell.textLabel?.text = datas[indexPath.row] cell.textLabel?.font = UIFont.systemFont(ofSize: 20, weight: 5) cell.textLabel?.textColor = .orange cell.textLabel?.textAlignment = .center return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let show = ShowCollectionViewController() show.title = datas[indexPath.row] switch datas[indexPath.row] { case "瀑布流": show.style = "waterfall" case "圆形": show.style = "circle" // if let settingurl = URL.init(string: UIApplicationOpenSettingsURLString) { // //UIApplication.shared.openURL(settingurl) // UIApplication.shared.open(<#T##url: URL##URL#>, options: <#T##[String : Any]#>, completionHandler: <#T##((Bool) -> Void)?##((Bool) -> Void)?##(Bool) -> Void#>) // }else{ // print("null url") // } UIApplication.shared.openURL(URL.init(string: UIApplicationOpenSettingsURLString)!) return default: show.style = "line" } navigationController?.pushViewController(show, animated: true) } }
apache-2.0
a3ec29454ec5e18838a208e2bbab1bb5
35.105263
177
0.641399
4.87389
false
false
false
false
AirHelp/Mimus
Sources/Mimus/Matchers/EqualMatcher.swift
1
481
import Foundation public final class EqualTo<T: Equatable>: Matcher { private let object: T? public init(_ object: T?) { self.object = object } public func matches(argument: Any?) -> Bool { if let otherObject = argument as? T { return object == otherObject } return argument == nil && object == nil } public var description: String { return "\(type(of: self)) - \(object.mimusDescription())" } }
mit
21ea0ddf844c1c52bc658c78435b9647
21.904762
65
0.577963
4.412844
false
false
false
false
MA806P/SwiftDemo
SwiftTestDemo/SwiftTestDemo/Closures.swift
1
4766
// // Closures.swift // SwiftTestDemo // // Created by MA806P on 2018/7/29. // Copyright © 2018年 myz. All rights reserved. // import Foundation //--------------- Closures ----------------- //func backward(_ s1: String, _ s2: String) -> Bool { // return s1 > s2 //} //let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] //var reNames = names.sorted(by: backward) //print(reNames) //// ////reNames = names.sorted(by: { (s1: String, s2: String) -> Bool in return s1 > s2 }) ////reNames = names.sorted(by: { s1, s2 in return s1 > s2 }) ////reNames = names.sorted(by: { s1, s2 in s1 > s2 } ) ////reNames = names.sorted(by: { $0 > $1 } ) ////reNames = names.sorted(by: >) ////******************** ////Trailing Closures //func someFuncThatTakesAClosure(closure: () -> Void) { // //func body goes here // print("func call") //} ////Here's how you call this function without using a trailing closure //someFuncThatTakesAClosure (closure: { // //closure's body goes here // print("closure") //}) ////Here's how you call this function with a trailing closure instead //someFuncThatTakesAClosure() { // //trailing closure's body goes here // print("call func") //} // ////If a closure expression is provided as the function or method’s only argument ////and you provide that expression as a trailing closure, ////you do not need to write a pair of parentheses () ////after the function or method’s name when you call the function //someFuncThatTakesAClosure { // //} //reNames = names.sorted { $0 > $1 } ////******************** ////Capturing Values //func makeIncrementer(forIncrement amount: Int) -> () -> Int { // var runningTotal = 0 // func incrementer() -> Int { // runningTotal += amount // return runningTotal // } // return incrementer //} // //let incrementByTen = makeIncrementer(forIncrement: 10) //print("---\(incrementByTen())") //10 //print("---\(incrementByTen())") //20 // //let alsoIncrementByten = incrementByTen; //print("---\(alsoIncrementByten())") //30 //Closures Are Reference Types //the closures these constants refer to are able to increment the runningTotal variables //that they have captured. This is because functions and closures are reference types. //******************** //Escaping Closures //When you declare a function that takes a closure as one of its parameters, //you can write @escaping before the parameter’s type to indicate that the closure is allowed to escape. ////Marking a closure with @escaping means you have to refer to self explicitly within the closure //var completionHandlers: [() -> Void] = [] //func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) { // completionHandlers.append(completionHandler) //} //func someFunctionWithNonescapingClosure(closure: () -> Void) { // closure() //} //class SomeClass { // var x = 10 // func doSomething() { // someFunctionWithEscapingClosure { self.x = 100 } // someFunctionWithNonescapingClosure { x = 200 } // } //} //let instance = SomeClass() //instance.doSomething() //print(instance.x) //// Prints "200" // //completionHandlers.first?() //print(instance.x) //// Prints "100" //******************** //Autoclosures //An autoclosure is a closure that is automatically created to wrap an expression //that’s being passed as an argument to a function. //var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] //// customersInLine is ["Alex", "Ewa", "Barry", "Daniella"] //func serve(customer customerProvider: () -> String) { // print("Now serving \(customerProvider())!") //} //serve(customer: { customersInLine.remove(at: 0) } ) //// Prints "Now serving Chris!" // // //// customersInLine is ["Ewa", "Barry", "Daniella"] //func serve(customer customerProvider: @autoclosure () -> String) { // print("Now serving \(customerProvider())!") //} //serve(customer: customersInLine.remove(at: 0)) //// Prints "Now serving Alex!" // // //// customersInLine is ["Barry", "Daniella"] //var customerProviders: [() -> String] = [] //func collectCustomerProviders(_ customerProvider: @autoclosure @escaping () -> String) { // customerProviders.append(customerProvider) //} //collectCustomerProviders(customersInLine.remove(at: 0)) //collectCustomerProviders(customersInLine.remove(at: 0)) //print("Collected \(customerProviders.count) closures.") //// Prints "Collected 2 closures." //for customerProvider in customerProviders { // print("Now serving \(customerProvider())!") //} //The array is declared outside the scope of the function, //which means the closures in the array can be executed after the function returns. //As a result, the value of the customerProvider argument must be allowed to escape the function’s scope.
apache-2.0
861fe7b0942c327ceeedbf03f5949255
31.554795
105
0.662319
3.915157
false
false
false
false
krin-san/SwiftHTTP
HTTPSecurity.swift
1
7933
////////////////////////////////////////////////////////////////////////////////////////////////// // // HTTPSecurity.swift // SwiftHTTP // // Created by Dalton Cherry on 5/13/15. // Copyright (c) 2015 Vluxe. All rights reserved. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation import Security public class HTTPSSLCert { var certData: NSData? var key: SecKeyRef? /** Designated init for certificates - parameter data: is the binary data of the certificate - returns: a representation security object to be used with */ public init(data: NSData) { self.certData = data } /** Designated init for public keys - parameter key: is the public key to be used - returns: a representation security object to be used with */ public init(key: SecKeyRef) { self.key = key } } public class HTTPSecurity { public var validatedDN = true //should the domain name be validated? var isReady = false //is the key processing done? var certificates: [NSData]? //the certificates var pubKeys: [SecKeyRef]? //the public keys var usePublicKeys = false //use public keys or certificate validation? /** Use certs from main app bundle - parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation - returns: a representation security object to be used with */ public convenience init(usePublicKeys: Bool = false) { let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".") var collect = Array<HTTPSSLCert>() for path in paths { if let d = NSData(contentsOfFile: path as String) { collect.append(HTTPSSLCert(data: d)) } } self.init(certs:collect, usePublicKeys: usePublicKeys) } /** Designated init - parameter keys: is the certificates or public keys to use - parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation - returns: a representation security object to be used with */ public init(certs: [HTTPSSLCert], usePublicKeys: Bool) { self.usePublicKeys = usePublicKeys if self.usePublicKeys { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), { var collect = Array<SecKeyRef>() for cert in certs { if let data = cert.certData where cert.key == nil { cert.key = self.extractPublicKey(data) } if let k = cert.key { collect.append(k) } } self.pubKeys = collect self.isReady = true }) } else { var collect = Array<NSData>() for cert in certs { if let d = cert.certData { collect.append(d) } } self.certificates = collect self.isReady = true } } /** Valid the trust and domain name. - parameter trust: is the serverTrust to validate - parameter domain: is the CN domain to validate - returns: if the key was successfully validated */ public func isValid(trust: SecTrustRef, domain: String?) -> Bool { var tries = 0 while(!self.isReady) { usleep(1000) tries += 1 if tries > 5 { return false //doesn't appear it is going to ever be ready... } } var policy: SecPolicyRef if self.validatedDN { policy = SecPolicyCreateSSL(true, domain) } else { policy = SecPolicyCreateBasicX509() } SecTrustSetPolicies(trust,policy) if self.usePublicKeys { if let keys = self.pubKeys { var trustedCount = 0 let serverPubKeys = publicKeyChainForTrust(trust) for serverKey in serverPubKeys as [AnyObject] { for key in keys as [AnyObject] { if serverKey.isEqual(key) { trustedCount++ break } } } if trustedCount == serverPubKeys.count { return true } } } else if let certs = self.certificates { let serverCerts = certificateChainForTrust(trust) var collect = Array<SecCertificate>() for data in certs { if let cert = SecCertificateCreateWithData(nil,data) { collect.append(cert) } } SecTrustSetAnchorCertificates(trust,collect) var result: SecTrustResultType = 0 SecTrustEvaluate(trust,&result) let r = Int(result) if r == kSecTrustResultUnspecified || r == kSecTrustResultProceed { var trustedCount = 0 for serverCert in serverCerts { for cert in certs { if cert == serverCert { trustedCount++ break } } } if trustedCount == serverCerts.count { return true } } } return false } /** Get the public key from a certificate data - parameter data: is the certificate to pull the public key from - returns: a public key */ func extractPublicKey(data: NSData) -> SecKeyRef? { let possibleCert = SecCertificateCreateWithData(nil,data) if let cert = possibleCert { return extractPublicKeyFromCert(cert,policy: SecPolicyCreateBasicX509()) } return nil } /** Get the public key from a certificate - parameter data: is the certificate to pull the public key from - returns: a public key */ func extractPublicKeyFromCert(cert: SecCertificate, policy: SecPolicy) -> SecKeyRef? { var possibleTrust: SecTrust? withUnsafeMutablePointer(&possibleTrust) { SecTrustCreateWithCertificates(cert, policy, $0) } if let trust = possibleTrust { var result: SecTrustResultType = 0 SecTrustEvaluate(trust,&result) return SecTrustCopyPublicKey(trust) } return nil } /** Get the certificate chain for the trust - parameter trust: is the trust to lookup the certificate chain for - returns: the certificate chain for the trust */ func certificateChainForTrust(trust: SecTrustRef) -> Array<NSData> { var collect = Array<NSData>() for var i = 0; i < SecTrustGetCertificateCount(trust); i++ { if let cert = SecTrustGetCertificateAtIndex(trust,i) { collect.append(SecCertificateCopyData(cert)) } } return collect } /** Get the public key chain for the trust - parameter trust: is the trust to lookup the certificate chain and extract the public keys - returns: the public keys from the certifcate chain for the trust */ func publicKeyChainForTrust(trust: SecTrustRef) -> Array<SecKeyRef> { var collect = Array<SecKeyRef>() let policy = SecPolicyCreateBasicX509() for var i = 0; i < SecTrustGetCertificateCount(trust); i++ { if let cert = SecTrustGetCertificateAtIndex(trust,i) { if let key = extractPublicKeyFromCert(cert, policy: policy) { collect.append(key) } } } return collect } }
apache-2.0
b0e6b7e42fb8d4ef257c8239da322549
31.252033
121
0.550233
5.444749
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/StudyNote/StudyNote/EventList/SNEventViewController.swift
1
1567
// // SNEventViewController.swift // StudyNote // // Created by wuyp on 2019/5/29. // Copyright © 2019 Raymond. All rights reserved. // import UIKit import Common class SNEventViewController: UIViewController { @objc private dynamic let supView = SNEventSupView(frame: CGRect(x: 50, y: 100, width: 200, height: 200)) @objc private dynamic let subView = SNEventSubView(frame: CGRect(x: 20, y: 20, width: 50, height: 50)) @objc private dynamic let supBtn = UIButton(frame: CGRect(x: 50, y: 100, width: 100, height: 100)) @objc private dynamic let subBtn = UIButton(frame: CGRect(x: 20, y: 20, width: 50, height: 50)) @objc override dynamic func viewDidLoad() { super.viewDidLoad() // self.view.addSubview(supView) // supView.addSubview(subView) supView.backgroundColor = UIColor.purple subView.backgroundColor = UIColor.red self.view.addSubview(supBtn) supBtn.addSubview(subBtn) supBtn.backgroundColor = UIColor.yellow subBtn.backgroundColor = UIColor.green subBtn.isEnabled = false supBtn.addTarget(self, action: #selector(supBtnAction), for: .touchUpInside) subBtn.addTarget(self, action: #selector(subBtnAction), for: .touchUpInside) supBtn.setEnlargeArea(areaFloat: 30) } @objc private dynamic func supBtnAction() { print("-----sup btn click") } @objc private dynamic func subBtnAction() { print("======sub btn click") } }
apache-2.0
6915fb9f532468d30d7017bae0e086d7
29.705882
109
0.637931
4.078125
false
false
false
false
Adorkable/SegueingInfo
Examples/FirstNavContainedViewController.swift
1
3549
// // FirstNavContainedViewController.swift // SegueingInfo // // Created by Ian Grossberg on 12/3/15. // Copyright © 2015 Adorkable. All rights reserved. // import UIKit import SegueingInfo class FirstNavContainedViewController: SegueingInfoViewController { @IBOutlet weak var passField : UITextField? func ensurePassField() -> UITextField { guard let passField = self.passField else { assertionFailure("passField Outlet must be attached") return self.passField! } return passField } func ensurePassFieldText() -> String { let passField = self.ensurePassField() guard let text = passField.text else { assertionFailure("passField.text is nil") return "" } return text } fileprivate var received : SegueingInfoInfoClass? @IBOutlet weak var receivedView : UIView? func ensureReceivedView() -> UIView { guard let receivedView = self.receivedView else { assertionFailure("receivedView Outlet must be attached") return self.receivedView! } return receivedView } @IBOutlet weak var receivedLabel : UILabel? func ensureReceivedLabel() -> UILabel { guard let receivedLabel = self.receivedLabel else { assertionFailure("receivedLabel Outlet must be attached") return self.receivedLabel! } return receivedLabel } func ensureReceivedLabelText() -> String { let receivedLabel = self.ensureReceivedLabel() guard let text = receivedLabel.text else { assertionFailure("receivedLabel.text is nil") return "" } return text } @IBInspectable var add : String? func guaranteeAdd() -> String { guard let add = self.add else { return "😘" } return add } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() let receivedView = self.ensureReceivedView() let passField = self.ensurePassField() if let received = self.received { self.received = nil receivedView.isHidden = false let receivedLabel = self.ensureReceivedLabel() receivedLabel.text = "\(received)" passField.text = "\(received)" } else { receivedView.isHidden = true } } } extension FirstNavContainedViewController { @IBAction func pass(_ sender : AnyObject?) { // TODO: tell user they need to set the value self.performSegue(withIdentifier: "pass", sender: "\(self.ensurePassFieldText()) \(self.guaranteeAdd())") } } extension FirstNavContainedViewController : SegueingInfoDestination { func destinationPrepareForSegue(_ segue: SegueingInfoStoryboardSegueClass?, withInfo info: SegueingInfoInfoClass) { if let receivedView = self.receivedView, let receivedLabel = self.receivedLabel, let passField = self.passField { receivedView.isHidden = false receivedLabel.text = "\(info)" passField.text = "\(info)" } else { self.received = info } } }
mit
ba0d7b9f558a50be02e718f687ebdd24
26.48062
119
0.57969
5.662939
false
false
false
false
iMetalk/TCZDemo
SwiftStudyDemo/SwiftDemo/Array.playground/Contents.swift
1
854
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" let VC = NSClassFromString("UIViewController")?.initialize() var someInts = [Int]() someInts.append(10) someInts = [] var threeDoubles = Array(repeating: 1.0, count: 2) var anotherThreeDoubles = Array(repeating: 2.0, count: 5) var sixDoubles = threeDoubles + anotherThreeDoubles var shopList: [String] = ["edge", "milk"] shopList.count shopList.isEmpty shopList.append("water") shopList += ["dadou", "hulu"] shopList[0] shopList[0] = "123" shopList shopList[0...3] = ["1", "2"] shopList shopList.removeLast() shopList.remove(at: 0) shopList shopList.append("1") for foodName in shopList { print(foodName) } for (index, value) in shopList.enumerated() { print("\(index)" + "\(value)") } var twoArray = [Array<Int>]() twoArray.append([1])
mit
fb2f0396352607b346e16ef02106ddfc
17.977778
60
0.694379
3.297297
false
false
false
false
alvaromb/CS-Trivia
Swift Playground/LongestCommonPrefix.playground/section-1.swift
1
494
/** * Longest common prefix for a given array of words */ import Cocoa let strings = ["abba", "abracadabra", "abort", "abigail"] let numberOfWords = countElements(strings) var lcp = "" var i = 0 for char in strings[0] { var occurrences = 0 for word in strings { if i < countElements(word) && char == Array(word)[i] { occurrences++ } } if occurrences == numberOfWords { lcp += char } i++ } println("Longest common prefix \(lcp)")
gpl-3.0
175ce8c3918d7c22fb02f07ab8fc7273
18.8
62
0.589069
3.770992
false
false
false
false
OskarGroth/ColorPickerPopover
ColorPicker/ColorWell.swift
1
1630
// // OGColorWell.swift // ColorPicker // // Created by Oskar Groth on 2016-08-31. // Copyright © 2016 Cindori. All rights reserved. // import Cocoa @objc public protocol ColorWellDelegate { func colorDidChange(colorWell: ColorWell, color: NSColor) } open class ColorWell: NSColorWell, NSPopoverDelegate { @IBOutlet open var delegate: AnyObject? override open var isEnabled: Bool { didSet { alphaValue = isEnabled ? 1 : 0.5 } } let viewController = ColorPickerViewController() override open func activate(_ exclusive: Bool) { viewController.loadView() viewController.colorPanel?.color = color let popover = NSPopover() popover.delegate = self popover.behavior = .semitransient popover.contentViewController = viewController popover.show(relativeTo: frame, of: self.superview!, preferredEdge: .maxX) viewController.colorPanel!.addObserver(self, forKeyPath: "color", options: .new, context: nil) } open func popoverDidClose(_ notification: Notification) { deactivate() viewController.colorPanel?.removeObserver(self, forKeyPath: "color") } override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let panel = object as? NSColorPanel { if panel == viewController.colorPanel { color = viewController.colorPanel!.color delegate?.colorDidChange(colorWell: self, color: color) } } } }
mit
47e743a340f46eb5d02f8f9dd9634f01
31.58
156
0.656845
4.848214
false
false
false
false
OlegTretiakov/ByzantineClock
ByzantineClock/ClockView.swift
1
1831
// // ClockView.swift // ByzantineClock // // Created by Олег Третьяков on 05.02.16. // Copyright © 2016 Олег Третьяков. All rights reserved. // import UIKit class ClockView: UIView { var timeInMinutes = 0 var noData = true override func drawRect(rect: CGRect) { let clockImage = UIImage(named: "clock737.jpg") let imageRect = self.bounds clockImage?.drawInRect(imageRect) if !noData { var startPoint = CGPoint() startPoint.x = imageRect.origin.x + imageRect.width / 2 startPoint.y = imageRect.origin.y + imageRect.height / 2 + 3 //Погрешность в центровке часов относительно рисунка var context = UIGraphicsGetCurrentContext() CGContextSetLineWidth(context, 3.0) CGContextSetFillColorWithColor(context, UIColor.redColor().CGColor) let rectangle = CGRectMake(startPoint.x - 6, startPoint.y - 6, 12, 12) CGContextAddEllipseInRect(context, rectangle) CGContextFillPath(context) let lineInPixels = (imageRect.height / 2) * 0.7 let angle = (Double(timeInMinutes) / 1440) * M_PI * 2 var endPoint = CGPoint() endPoint.x = startPoint.x + CGFloat(cos(angle)) * lineInPixels endPoint.y = startPoint.y + CGFloat(sin(angle)) * lineInPixels context = UIGraphicsGetCurrentContext() CGContextSetLineWidth(context, 3.0) CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor) CGContextMoveToPoint(context, startPoint.x, startPoint.y) CGContextAddLineToPoint(context, endPoint.x, endPoint.y) CGContextStrokePath(context) } } }
mit
f7d9cc6e577b03d0073c6e5f7ae5c874
37.23913
125
0.629335
4.568831
false
false
false
false
pdil/PDColorPicker
Source/PDRoundedRectButton.swift
1
1650
// // PDRoundedRectButton.swift // PDColorPicker // // Created by Paolo Di Lorenzo on 8/8/17. // Copyright © 2017 Paolo Di Lorenzo. All rights reserved. // import UIKit class PDRoundedRectButton: PDBouncyButton { var title: String { didSet { setTitle(title, for: .normal) titleLabel?.sizeToFit() } } var backColor: UIColor { didSet { backgroundColor = backColor } } var foreColor: UIColor { didSet { setTitleColor(foreColor, for: .normal) } } override var intrinsicContentSize: CGSize { guard let labelSize = titleLabel?.intrinsicContentSize else { return .zero } return CGSize(width: labelSize.width + contentEdgeInsets.left + contentEdgeInsets.right, height: super.intrinsicContentSize.height + contentEdgeInsets.top + contentEdgeInsets.bottom) } // MARK: - Initializer init(title: String, backColor: UIColor, foreColor: UIColor) { self.title = "" self.backColor = .black self.foreColor = .black super.init(frame: .zero) defer { self.title = title self.backColor = backColor self.foreColor = foreColor layer.shadowColor = UIColor.black.cgColor layer.shadowOffset = CGSize(width: 0, height: 0) layer.shadowOpacity = 0.6 layer.shadowRadius = 4 } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Life Cycle override func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = bounds.height / 2 contentEdgeInsets = UIEdgeInsets(top: 2, left: 6, bottom: 2, right: 6) } }
mit
13bae1dd7ed6225237f6f091eda09553
23.25
186
0.657975
4.316754
false
false
false
false
onebytegone/actionable
Actionable/Actionable.swift
1
6353
// // Actionable.swift // Actionable // // Created by Ethan Smith on 5/18/15. // Copyright (c) 2015 Ethan Smith. All rights reserved. // import Foundation public protocol ActionableObject { var events: Actionable {get} } public class Actionable { var eventStore: [String : ActionableEvent] = [:] var timer: ActionableTimer = ActionableTimer() public init() { } // ***** // MARK: Event Registration // ***** /** * Registers a handler without any args for the specified event. * * - parameter event: The key for the event handler * - parameter handler: The closure to run on event trigger */ public func on(event: String, handler: () -> Void) -> ActionableHandler { // Since the handler passed doesn't take any args, // we are going to wrap it with one that does. let wrapper = { ( arg: Any? ) in handler() } return self.on(event, handler: wrapper) } /** * Registers a handler for the specified event * * - parameter event: The key for the event handler * - parameter handler: The closure to run on event trigger */ public func on(event: String, handler closure: (Any?) -> Void) -> ActionableHandler { let handler = ActionableHandler(closure) eventSetForEvent(event).addHandler(handler) return handler } /** * Registers a handler for the specified event * * - parameter event: The key for the event handler * - parameter handler: The closure to run on event trigger */ public func on(event: String, handler closure: (Any?, () -> Void) -> Void) -> ActionableHandler { let handler = ActionableHandler(closure) eventSetForEvent(event).addHandler(handler) return handler } // ***** // MARK: Event Triggering // ***** /** * Fires the given event * * - parameter event: The key for the event handler */ public func trigger(event: String, data: Any? = nil) { eventSetForEvent(event).callAllHandlers(data) } /** * Fires the given event, calling all the handlers * sequentially, waiting for each to finish before * calling the next. This is helpful when the event * handlers may have aync actions that need to be * waited on. * * - parameter event: The key for the event handler * - parameter data: The data to pass * - parameter completed: The completion callback */ public func trigger(event: String, data: Any? = nil, completed: () -> Void) { eventSetForEvent(event).callHandlersSequentially(data, completed: completed) } // ***** // MARK: Trigger Based on Time // ***** /** * Fires the given event after a delay * * - parameter delay: The time, in seconds, to wait before triggering the event * - parameter event: The key for the event handler * - parameter data: Any data to pass to the event */ public func triggerAfterDelay(delay: Double, event: String, data: Any? = nil) { timer.timerWithInterval(delay, repeats: false) { () -> Void in self.trigger(event, data: data) } } /** * Fires the given event after an interval, repeating at that interval. * If this is called twice for the same event, it will be called on the * last interval. e.g. called with 30sec interval, then called with 10sec * interval, the event will be repeated on a 10sec interval. * * - parameter interval: The time period, in seconds, to trigger the event on * - parameter event: The key for the event handler * - parameter data: Any data to pass to the event */ public func triggerOnInterval(interval: Double, event: String, data: Any? = nil) { timer.timerWithInterval(interval, repeats: true, key: event) { () -> Void in self.trigger(event, data: data) } } // ***** // MARK: Remove Temporal Events // ***** /** * Removes the delayed or recurring triggers for the event * * - parameter event: The key for the event handler */ public func cancelTrigger(event: String) { timer.cancelTimer(event) } /** * Removes any delayed or recurring triggers for the event */ public func cancelAllTriggers() { timer.disposeOfStoredTimers() } // ***** // MARK: Remove Event Handlers // ***** /** * Removes a handler for the specified event * * - parameter event: The key for the event handler * - parameter wrapper: The `ActionableEvent` that would run on event trigger */ public func off(event: String, wrapper: ActionableHandler) { eventSetForEvent(event).removeHandler(wrapper) } /** * Removes all handlers for the specified event * * - parameter event: The key for the event handler */ public func allOff(event: String) { // Dispose of the event set eventStore[event] = ActionableEvent() } // ***** // MARK: Additional Actions // ***** /** * Adds the event `finalEvent` so it will be triggered when * the event named `initialEvent` on `target` is triggered. * * :Basic flow on trigger: * 1. `target` has trigger called for `initialEvent` * 2. `target` calls all its handlers * 3. One of the handlers triggers `finalEvent` on this object * * - parameter finalEvent: The name of the event to trigger * - parameter target: Another Actionable object that will triggers the event to act on * - parameter initialEvent: The event on `target` that starts the chain */ public func chain(finalEvent: String, to target: Actionable, forEvent initialEvent: String) { target.on(initialEvent) { (data: Any?) -> Void in self.trigger(finalEvent, data: data) } } // ***** // MARK: Helper Functions // ***** /** * Returns the event set for the event. If the event * set doesn't exist, it will be created. * * - parameter eventName: The key for the event handler * * - returns: The `ActionableEvent` for the event key */ private func eventSetForEvent(eventName: String) -> ActionableEvent { if let event = eventStore[eventName] { return event } // Create new ActionableEvent let eventSet = ActionableEvent() eventStore[eventName] = eventSet return eventSet } }
mit
1c3553d6e5993ea90c0f1640cc5ce2e5
28.548837
100
0.634346
4.339481
false
false
false
false
jessesquires/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0101.xcplaygroundpage/Contents.swift
2
7494
/*: # Reconfiguring `sizeof` and related functions into a unified `MemoryLayout` struct * Proposal: [SE-0101](0101-standardizing-sizeof-naming.md) * Authors: [Erica Sadun](http://github.com/erica), [Dave Abrahams](https://github.com/dabrahams) * Review Manager: [Chris Lattner](http://github.com/lattner) * Status: **Implemented (Swift 3)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-July/000244.html) ## Introduction This proposal addresses `sizeof`, `sizeofValue`, `strideof`, `strideofValue`, `align`, and `alignOf`. It discards the value-style standalone functions and combines the remaining items into a unified structure. Review 1: * [Swift Evolution Review Thread](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160620/021527.html) * [Original Proposal](https://github.com/apple/swift-evolution/blob/26e1e5b546b13fb66ee8877ad7018a7856e467ca/proposals/0101-standardizing-sizeof-naming.md) Prior Discussions: * Swift Evolution Pitch: [\[Pitch\] Renaming sizeof, sizeofValue, strideof, strideofValue](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160530/019884.html) * [Earlier Discussions](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160425/016042.html) * [SE-0101 Review](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160620/021527.html) ## Motivation Although `sizeof()`, etc are treated as terms of art, these names are appropriated from C. The functions do not correspond to anything named `sizeof` in LLVM. Swift's six freestanding memory functions increase the API surface area while providing lightly-used and unsafe functionality. These APIs are not like `map`, `filter`, and `Dictionary`. They're specialty items that you should only reach for when performing unsafe operations, mostly inside the guts of higher-level constructs. Refactoring this proposal to use a single namespace increases discoverability, provides a single entry point for related operations, and enables future expansions without introducing further freestanding functions. ## Detailed Design This proposal introduces a new struct, `MemoryLayout` ```swift /// Accesses the memory layout of `T` through its /// `size`, `stride`, and `alignment` properties public struct MemoryLayout<T> { /// Returns the contiguous memory footprint of `T`. /// /// Does not include any dynamically-allocated or "remote" /// storage. In particular, `MemoryLayout<T>.size`, when /// `T` is a class type, is the same regardless of how many /// stored properties `T` has. public static var size: Int { return _sizeof(T) } /// For instances of `T` in an `Array<T>`, returns the number of /// bytes from the start of one instance to the start of the /// next. This is the same as the number of bytes moved when an /// `UnsafePointer<T>` is incremented. `T` may have a lower minimal /// alignment that trades runtime performance for space /// efficiency. The result is always positive. public static var stride: Int { return _strideof(T) } /// Returns the default memory alignment of `T`. public static var alignment: Int { return _alignof(T) } } ``` With this design, consumers call: ```swift // Types MemoryLayout<Int>.size // 8 MemoryLayout<Int>.stride // 8 MemoryLayout<Int>.alignment // 8 ``` ## Values This proposal removes `sizeofValue()`, `strideofValue()`, and `alignofValue()` from the standard library. This proposal adopts the stance that sizes relate to types, not values. Russ Bishop writes in the initial review thread, "Asking about the size of an instance implies things that aren’t true. Sticking _value_ labels on everything doesn’t change the fact that `sizeOf(swift_array)` is not going to give you the size of the underlying buffer no matter how you slice it." As the following chart shows, type-based calls consistently outnumber instance-based calls in gist, github, and stdlib searches. The Google search for `sizeof` is probably too general based on its use in other languages. <table> <tr width = 800> <th width = 200>Term</td> <th width = 150>stdlib search</td> <th width = 150>gist search</td> <th width = 150>Google site:github.com swift</td> </tr> <tr width = 800> <td width = 200>sizeof</td> <td width = 150>157</td> <td width = 150>169</td> <td width = 150>(18,600, term is probably too general)</td> </tr> <tr width = 800> <td width = 200>sizeofValue</td> <td width = 150>4</td> <td width = 150>34</td> <td width = 150>584</td> </tr> <tr width = 800> <td width = 200>alignof</td> <td width = 150>44</td> <td width = 150>11</td> <td width = 150>334</td> </tr> <tr width = 800> <td width = 200>alignofValue</td> <td width = 150>5</td> <td width = 150>5</td> <td width = 150>154</td> </tr> <tr width = 800> <td width = 200>strideof</td> <td width = 150>24</td> <td width = 150>19</td> <td width = 150>347</td> </tr> <tr width = 800> <td width = 200>strideofValue</td> <td width = 150>1</td> <td width = 150>5</td> <td width = 150>163</td> </tr> </table> If for some reason, the core team decides that there's a compelling reason to include value calls, an implementation might look something like this: ```swift extension MemoryLayout<T> { init(_ : @autoclosure () -> T) {} public static func of(_ candidate : @autoclosure () -> T) -> MemoryLayout<T>.Type { return MemoryLayout.init(candidate).dynamicType } } // Value let x: UInt8 = 5 MemoryLayout.of(x).size // 1 MemoryLayout.of(1).size // 8 MemoryLayout.of("hello").stride // 24 MemoryLayout.of(29.2).alignment // 8 ``` #### Known Limitations and Bugs According to Joe Groff, concerns about existential values (it's illegal to ask for the size of an existential value's dynamic type) could be addressed by > "having `sizeof` and friends formally take an Any.Type instead of <T> T.Type. (This might need some tweaking of the underlying builtins to be able to open existential metatypes, but it seems implementable.)" This proposal uses `<T>` / `T.Type` to reflect Swift's current implementation. **Note:** There is a [known bug](https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20160530/002150.html) (cite D. Gregor) that does not enforce `.self` when used with `sizeof`, allowing `sizeof(UInt)`. This call should be `sizeof(UInt.self)`. This proposal is written as if the bug were resolved without relying on adoption of [SE-0090](0090-remove-dot-self.md). ## Impact on Existing Code This proposal requires migration support to replace function calls with struct-based namespacing. This should be a simple substitution with limited impact on existing code that is easily addressed with a fixit. ## Alternatives Considered The original proposal introduced three renamed standalone functions: ```swift public func memorySize<T>(ofValue _: @autoclosure T -> Void) -> Int public func memoryInterval<T>(ofValue _: @autoclosure T -> Void) -> Int public func memoryAlignment<T>(ofValue _: @autoclosure T -> Void) -> Int ``` These functions offered human factor advantages over the current proposal but didn't address Dave's concerns about namespacing and overall safety. This alternative has been discarded and can be referenced by reading the original proposal. ## Acknowledgements Thank you, Xiaodi Wu, Matthew Johnson, Pyry Jahkola, Tony Allevato, Joe Groff, Russ Bishop, and everyone else who contributed to this proposal ---------- [Previous](@previous) | [Next](@next) */
mit
94499bb53e8896c782c9d4ef6ebe46b6
41.556818
368
0.730708
3.715278
false
false
false
false
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/NCCharacterSheetViewController.swift
2
17473
// // NCCharacterSheetViewController.swift // Neocom // // Created by Artem Shimanski on 14.12.16. // Copyright © 2016 Artem Shimanski. All rights reserved. // import UIKit import EVEAPI import Futures class NCCharacterAttributesSection: DefaultTreeSection { init(attributes: NCCharacterAttributes, nodeIdentifier: String? = nil, title: String? = nil) { var rows = [TreeNode]() rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "Intelligence", image: #imageLiteral(resourceName: "intelligence"), title: NSLocalizedString("Intelligence", comment: "").uppercased(), subtitle: "\(attributes.intelligence) \(NSLocalizedString("points", comment: ""))")) rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "Memory", image: #imageLiteral(resourceName: "memory"), title: NSLocalizedString("Memory", comment: "").uppercased(), subtitle: "\(attributes.memory) \(NSLocalizedString("points", comment: ""))")) rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "Perception", image: #imageLiteral(resourceName: "perception"), title: NSLocalizedString("Perception", comment: "").uppercased(), subtitle: "\(attributes.perception) \(NSLocalizedString("points", comment: ""))")) rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "Willpower", image: #imageLiteral(resourceName: "willpower"), title: NSLocalizedString("Willpower", comment: "").uppercased(), subtitle: "\(attributes.willpower) \(NSLocalizedString("points", comment: ""))")) rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "Charisma", image: #imageLiteral(resourceName: "charisma"), title: NSLocalizedString("Charisma", comment: "").uppercased(), subtitle: "\(attributes.charisma) \(NSLocalizedString("points", comment: ""))")) super.init(nodeIdentifier: nodeIdentifier, title: title, children: rows) } } class NCCharacterSheetViewController: NCTreeViewController { override func viewDidLoad() { super.viewDidLoad() accountChangeAction = .reload tableView.register([Prototype.NCHeaderTableViewCell.default, Prototype.NCDefaultTableViewCell.attribute, Prototype.NCDefaultTableViewCell.attributeNoImage, Prototype.NCDefaultTableViewCell.placeholder]) } //MARK: - NCRefreshable private var character: CachedValue<ESI.Character.Information>? private var corporation: CachedValue<ESI.Corporation.Information>? private var alliance: CachedValue<ESI.Alliance.Information>? private var clones: CachedValue<ESI.Clones.JumpClones>? private var attributes: CachedValue<ESI.Skills.CharacterAttributes>? private var implants: CachedValue<[Int]>? private var skills: CachedValue<ESI.Skills.CharacterSkills>? private var skillQueue: CachedValue<[ESI.Skills.SkillQueueItem]>? private var walletBalance: CachedValue<Double>? private var characterImage: CachedValue<UIImage>? private var corporationImage: CachedValue<UIImage>? private var allianceImage: CachedValue<UIImage>? private var characterShip: CachedValue<ESI.Location.CharacterShip>? private var characterLocation: CachedValue<ESI.Location.CharacterLocation>? private var characterObserver: NCManagedObjectObserver? override func load(cachePolicy: URLRequest.CachePolicy) -> Future<[NCCacheRecord]> { guard let account = NCAccount.current else { return .init([]) } title = account.characterName let progress = Progress(totalUnitCount: 11) let dataManager = self.dataManager let characterID = account.characterID return DispatchQueue.global(qos: .utility).async { () -> [NCCacheRecord] in let character = progress.perform{dataManager.character()} let characterDetails = character.then(on: .main) { result -> Future<[NCCacheRecord]> in self.character = result DispatchQueue.main.async { self.characterObserver = NCManagedObjectObserver(managedObject: result.cacheRecord(in: NCCache.sharedCache!.viewContext)) { [weak self] (_,_) in _ = self?.loadCharacterDetails() } } self.update() return progress.perform{self.loadCharacterDetails()} } let clones = progress.perform{dataManager.clones()}.then(on: .main) { result -> CachedValue<ESI.Clones.JumpClones> in self.clones = result self.update() return result } let attributes = progress.perform{dataManager.attributes()}.then(on: .main) { result -> CachedValue<ESI.Skills.CharacterAttributes> in self.attributes = result self.update() return result } let implants = progress.perform{dataManager.implants()}.then(on: .main) { result -> CachedValue<[Int]> in self.implants = result self.update() return result } let skills = progress.perform{dataManager.skills()}.then(on: .main) { result -> CachedValue<ESI.Skills.CharacterSkills> in self.skills = result self.update() return result } let skillQueue = progress.perform{dataManager.skillQueue()}.then(on: .main) { result -> CachedValue<[ESI.Skills.SkillQueueItem]> in self.skillQueue = result self.update() return result } let walletBalance = progress.perform{dataManager.walletBalance()}.then(on: .main) { result -> CachedValue<Double> in self.walletBalance = result self.update() return result } let characterImage = progress.perform{dataManager.image(characterID: characterID, dimension: 512)}.then(on: .main) { result -> CachedValue<UIImage> in self.characterImage = result self.update() return result } let characterLocation = progress.perform{dataManager.characterLocation()}.then(on: .main) { result -> CachedValue<ESI.Location.CharacterLocation> in self.characterLocation = result self.update() return result } let characterShip = progress.perform{dataManager.characterShip()}.then(on: .main) { result -> CachedValue<ESI.Location.CharacterShip> in self.characterShip = result self.update() return result } var records = [character.then(on: .main) {$0.cacheRecord(in: NCCache.sharedCache!.viewContext)}, clones.then(on: .main) {$0.cacheRecord(in: NCCache.sharedCache!.viewContext)}, attributes.then(on: .main) {$0.cacheRecord(in: NCCache.sharedCache!.viewContext)}, implants.then(on: .main) {$0.cacheRecord(in: NCCache.sharedCache!.viewContext)}, skills.then(on: .main) {$0.cacheRecord(in: NCCache.sharedCache!.viewContext)}, skillQueue.then(on: .main) {$0.cacheRecord(in: NCCache.sharedCache!.viewContext)}, walletBalance.then(on: .main) {$0.cacheRecord(in: NCCache.sharedCache!.viewContext)}, characterImage.then(on: .main) {$0.cacheRecord(in: NCCache.sharedCache!.viewContext)}, characterLocation.then(on: .main) {$0.cacheRecord(in: NCCache.sharedCache!.viewContext)}, characterShip.then(on: .main) {$0.cacheRecord(in: NCCache.sharedCache!.viewContext)}].compactMap { try? $0.get() } do { records.append(contentsOf: try characterDetails.get()) } catch {} return records } } override func content() -> Future<TreeNode?> { var sections = [TreeSection]() var rows = [TreeRow]() if let value = self.characterImage?.value { rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.image, nodeIdentifier: "CharacterImage", image: value)) } if let value = self.corporation?.value { rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "Corporation", image: self.corporationImage?.value, title: NSLocalizedString("Corporation", comment: "").uppercased(), subtitle: value.name)) } if let value = self.alliance?.value { rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "Alliance", image: self.allianceImage?.value, title: NSLocalizedString("Alliance", comment: "").uppercased(), subtitle: value.name)) } if let value = self.character?.value { rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "DoB", title: NSLocalizedString("Date of Birth", comment: "").uppercased(), subtitle: DateFormatter.localizedString(from: value.birthday, dateStyle: .short, timeStyle: .none))) if let race = NCDatabase.sharedDatabase?.chrRaces[value.raceID]?.raceName, let bloodline = NCDatabase.sharedDatabase?.chrBloodlines[value.bloodlineID]?.bloodlineName, let ancestryID = value.ancestryID, let ancestry = NCDatabase.sharedDatabase?.chrAncestries[ancestryID]?.ancestryName { rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "Bloodline", title: NSLocalizedString("Bloodline", comment: "").uppercased(), subtitle: "\(race) / \(bloodline) / \(ancestry)")) } if let ss = value.securityStatus { rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "SS", title: NSLocalizedString("Security Status", comment: "").uppercased(), attributedSubtitle: String(format: "%.1f", ss) * [NSAttributedStringKey.foregroundColor: UIColor(security: ss)])) } } if let ship = self.characterShip?.value, let location = self.characterLocation?.value { if let type = NCDatabase.sharedDatabase?.invTypes[ship.shipTypeID], let solarSystem = NCDatabase.sharedDatabase?.mapSolarSystems[location.solarSystemID] { let location = NCLocation(solarSystem) rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "Ship", image: type.icon?.image?.image, title: type.typeName?.uppercased(), attributedSubtitle: location.displayName, accessoryType: .disclosureIndicator,route: Router.Database.TypeInfo(type))) } } if rows.count > 0 { sections.append(DefaultTreeSection(nodeIdentifier: "Bio", title: NSLocalizedString("Bio", comment: "").uppercased(), children: rows)) } if let value = self.walletBalance?.value { let balance = Double(value) let row = DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "Balance", title: NSLocalizedString("Balance", comment: "").uppercased(), subtitle: NCUnitFormatter.localizedString(from: balance, unit: .isk, style: .full)) sections.append(DefaultTreeSection(nodeIdentifier: "Account", title: NSLocalizedString("Account", comment: "").uppercased(), children: [row])) } rows = [] if let attributes = self.attributes?.value, let implants = self.implants?.value, let skills = self.skills?.value, let skillQueue = self.skillQueue?.value { let character = NCCharacter(attributes: NCCharacterAttributes(attributes: attributes, implants: implants), skills: skills, skillQueue: skillQueue) let sp = character.skills.map{$0.value.skillPoints}.reduce(0, +) rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "SP", title: "\(skills.skills.count) \(NSLocalizedString("skills", comment: ""))".uppercased(), subtitle: "\(NCUnitFormatter.localizedString(from: Double(sp), unit: .skillPoints, style: .full))")) } if let value = self.attributes?.value { rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "Respecs", title: NSLocalizedString("Bonus Remaps Available", comment: "").uppercased(), subtitle: "\(value.bonusRemaps ?? 0)")) if let value = value.lastRemapDate { let calendar = Calendar(identifier: .gregorian) var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second, .timeZone], from: value) components.year? += 1 if let date = calendar.date(from: components) { let t = date.timeIntervalSinceNow let s: String if t <= 0 { s = NSLocalizedString("Now", comment: "") } else if t < 3600 * 24 * 7 { s = NCTimeIntervalFormatter.localizedString(from: t, precision: .minutes) } else { s = DateFormatter.localizedString(from: date, dateStyle: .short, timeStyle: .none) } rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "RespecDate", title: NSLocalizedString("Neural Remap Available", comment: "").uppercased(), subtitle: s)) } } } if rows.count > 0 { sections.append(DefaultTreeSection(nodeIdentifier: "Skills", title: NSLocalizedString("Skills", comment: "").uppercased(), children: rows)) } if let attributes = self.attributes?.value, let implants = self.implants?.value { rows = [] let attributes = NCCharacterAttributes(attributes: attributes, implants: implants) sections.append(NCCharacterAttributesSection(attributes: attributes, nodeIdentifier: "Attributes", title: NSLocalizedString("Attributes", comment: "").uppercased())) if !implants.isEmpty { rows = [] let invTypes = NCDatabase.sharedDatabase?.invTypes let list = [(NCDBAttributeID.intelligenceBonus, NSLocalizedString("Intelligence", comment: "")), (NCDBAttributeID.memoryBonus, NSLocalizedString("Memory", comment: "")), (NCDBAttributeID.perceptionBonus, NSLocalizedString("Perception", comment: "")), (NCDBAttributeID.willpowerBonus, NSLocalizedString("Willpower", comment: "")), (NCDBAttributeID.charismaBonus, NSLocalizedString("Charisma", comment: ""))] let implants = implants.compactMap { implant -> (NCDBInvType, Int)? in guard let type = invTypes?[implant] else {return nil} return (type, Int(type.allAttributes[NCDBAttributeID.implantness.rawValue]?.value ?? 100)) }.sorted {$0.1 < $1.1} rows = implants.map { (type, _) -> TreeRow in if let enhancer = list.first(where: { (type.allAttributes[$0.0.rawValue]?.value ?? 0) > 0 }) { return DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "\(type.typeID)Enhancer", image: type.icon?.image?.image ?? NCDBEveIcon.defaultType.image?.image, title: type.typeName?.uppercased(), subtitle: "\(enhancer.1) +\(Int(type.allAttributes[enhancer.0.rawValue]!.value))", accessoryType: .disclosureIndicator, route: Router.Database.TypeInfo(type)) } else { return DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "\(type.typeID)Enhancer", image: type.icon?.image?.image ?? NCDBEveIcon.defaultType.image?.image, title: type.typeName?.uppercased(), accessoryType: .disclosureIndicator, route: Router.Database.TypeInfo(type)) } } if rows.isEmpty { rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.placeholder, nodeIdentifier: "NoImplants", title: NSLocalizedString("No Implants Installed", comment: "").uppercased())) } sections.append(DefaultTreeSection(nodeIdentifier: "Implants", title: NSLocalizedString("Implants", comment: "").uppercased(), children: rows)) } } guard !sections.isEmpty else { return .init(.failure(NCTreeViewControllerError.noResult)) } return .init(RootNode(sections, collapseIdentifier: "NCCharacterSheetViewController")) } private func loadCharacterDetails() -> Future<[NCCacheRecord]> { guard let character = self.character?.value else { return .init([]) } let progress = Progress(totalUnitCount: 4) let dataManager = self.dataManager return DispatchQueue.global(qos: .utility).async { () -> Future<[NCCacheRecord]> in var futures = [Future<NCCacheRecord>]() let corporation = progress.perform{dataManager.corporation(corporationID: Int64(character.corporationID))} corporation.then(on: .main) { result in self.corporation = result } futures.append(corporation.then(on: .main){$0.cacheRecord(in: NCCache.sharedCache!.viewContext)}) let corporationImage = progress.perform{dataManager.image(corporationID: Int64(character.corporationID), dimension: 32)} corporationImage.then(on: .main) { result in self.corporationImage = result } futures.append(corporationImage.then(on: .main){$0.cacheRecord(in: NCCache.sharedCache!.viewContext)}) if let allianceID = (try? corporation.get())?.value?.allianceID { let alliance = progress.perform{dataManager.alliance(allianceID: Int64(allianceID))} alliance.then(on: .main) { result in self.alliance = result } futures.append(alliance.then(on: .main){$0.cacheRecord(in: NCCache.sharedCache!.viewContext)}) let allianceImage = progress.perform{dataManager.image(allianceID: Int64(allianceID), dimension: 32)} allianceImage.then(on: .main) { result in self.allianceImage = result } futures.append(allianceImage.then(on: .main){$0.cacheRecord(in: NCCache.sharedCache!.viewContext)}) } else { progress.completedUnitCount += 2 } return all(futures).finally(on: .main) { self.update() } } } private func update() { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(internalUpdate), object: nil) perform(#selector(internalUpdate), with: nil, afterDelay: 0) } @objc private func internalUpdate() { updateContent() } }
lgpl-2.1
a6c5f85933d3496b0ca884091d58c1bc
48.777778
320
0.719036
4.319407
false
false
false
false
lieonCX/Live
Live/View/Broadcast/BroadcastViewController.swift
1
35970
// // BroadcastViewController.swift // Live // // Created by lieon on 2017/6/20. // Copyright © 2017年 ChengDuHuanLeHui. All rights reserved. // swiftlint:disable variable_name import UIKit import Device import AVKit import AVFoundation import SnapKit import RxSwift import RxCocoa import PromiseKit import RxDataSources import FXDanmaku import Photos class BroadcastViewController: BaseViewController { lazy var broacastVM: BroacastViewModel = BroacastViewModel() fileprivate var roomVM: RoomViewModel = RoomViewModel() fileprivate lazy var txLivePlayer: TXLivePlayer = TXLivePlayer() fileprivate lazy var avatarImgeView: UIImageView = { let imageView = UIImageView() imageView.image = UIImage(named: "placeholderImage_avatar") return imageView }() fileprivate lazy var scrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.backgroundColor = .clear scrollView.isPagingEnabled = true scrollView.bounces = false scrollView.showsHorizontalScrollIndicator = false return scrollView }() fileprivate lazy var svcontainerView: UIView = { let view = UIView() view.backgroundColor = .clear return view }() fileprivate lazy var containerView: UIView = { let view = UIView() view.backgroundColor = UIColor.clear return view }() fileprivate lazy var timeLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 12) label.text = "00:00:00" label.textAlignment = .left label.textColor = UIColor.white return label }() fileprivate lazy var seecountLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 11) label.text = "10000人" label.textAlignment = .left label.textColor = UIColor(hex: CustomKey.Color.mainColor) return label }() fileprivate lazy var collectionBtn: UIButton = { let btn = UIButton() btn.setImage(UIImage(named: "details_iscollect_btn@3x"), for: .normal) btn.setImage(UIImage(named: "details_iscollect_btn@3x"), for: .highlighted) return btn }() lazy var closeBtn: UIButton = { let btn = UIButton() btn.setImage(UIImage(named: "common_close@3x"), for: .normal) btn.setImage(UIImage(named: "common_close@3x"), for: .highlighted) return btn }() fileprivate lazy var beansCountlabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 11) label.textAlignment = .left label.text = "12" label.textColor = UIColor.white return label }() fileprivate lazy var IDlabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 11) label.textAlignment = .left label.text = "1231231233" label.textColor = UIColor.white return label }() fileprivate var shareBtn: UIButton = { let btn = UIButton() btn.setImage(UIImage(named: "play_share@3x"), for: .normal) btn.contentMode = .scaleAspectFit return btn }() fileprivate var screenShotBtn: UIButton = { let btn = UIButton() btn.setImage(UIImage(named: "screenshot"), for: .normal) btn.contentMode = .scaleAspectFit return btn }() fileprivate var messageBtn: UIButton = { let btn = UIButton() btn.setImage(UIImage(named: "anchor_message3x"), for: .normal) btn.setImage(UIImage(named: "anchor_message_highighlight"), for: .highlighted) btn.contentMode = .scaleAspectFit return btn }() fileprivate var switchCamerabtn: UIButton = { let btn = UIButton() btn.setImage(UIImage(named: "switch_camera"), for: .normal) btn.contentMode = .scaleAspectFit return btn }() fileprivate var beautifyBtn: UIButton = { let btn = UIButton() btn.setImage(UIImage(named: "meifu@3x"), for: .normal) btn.setImage(UIImage(named: "meifu_hightlight@3x"), for: .highlighted) btn.contentMode = .scaleAspectFit return btn }() fileprivate lazy var videoParentView: UIImageView = UIImageView(frame: self.view.bounds) fileprivate lazy var alterView: CloseBroadcastView = CloseBroadcastView() fileprivate lazy var shareView: ShareView = { let share = ShareView() share.backgroundColor = .white share.configApperance(textClor: UIColor.black) return share }() fileprivate var timer: Timer? fileprivate var time: Float = 0 fileprivate var messageHandler: MsgHandler = MsgHandler() fileprivate lazy var messageTableView: UITableView = { let view = UITableView() view.delegate = self view.backgroundColor = .clear view.backgroundView = nil view.isOpaque = true view.separatorStyle = .none view.allowsSelection = false view.register(MessageTableViewCell.self, forCellReuseIdentifier: "MessageTableViewCell") return view }() fileprivate lazy var chatView: ChatInputView = { let view = ChatInputView() return view }() struct CustomSize { static let inputH: CGFloat = 60 static let messageTableH: CGFloat = 150 static let messageTableInset: CGFloat = 60 static let bottomViewH: CGFloat = 50 static let chatViewHeight: CGFloat = 80 static let beautiftyViewH: CGFloat = 80 } fileprivate var danmakuView: FXDanmaku = FXDanmaku() fileprivate let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, NSAttributedString>>() fileprivate lazy var gitftAnimateView: GiftConatainerView = { let view = GiftConatainerView(frame: CGRect(x: 0, y: 120, width: 250, height: 200)) return view }() fileprivate var viewerView: ViewerView = ViewerView() fileprivate var realTimer: Timer? fileprivate var bigGiftView = BigGiftAnimationView() fileprivate lazy var beautifyView: BeautifyView = BeautifyView() override func viewDidLoad() { super.viewDidLoad() setupAllContainerView() setupMessageView() setupDanaku() setupGitAnimateView() setupBigGiftView() setupChatView() setupBeautifyView() addRealTimer() } override func viewWillDisappear(_ animated: Bool) { endBroacast() removeTimer() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setupIM() } } // MARK: BASE UI extension BroadcastViewController { /// 设置所有父视图 fileprivate func setupAllContainerView() { view.addSubview(videoParentView) broacastVM.videoParentView = videoParentView let label = MGCustomCountDown.downView() label?.frame = UIScreen.main.bounds label?.delegate = self label?.backgroundColor = .clear view.addSubview(label ?? MGCustomCountDown()) containerView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height) view.addSubview(containerView) if broacastVM.openCamera() { setupUserTagView() setupViewerView() setupBeansView() setupIDView() setupBottomView() label?.addTimerForAnimationDownView() } setupShareView() } /// 设置用户头像视图 fileprivate func setupUserTagView() { let view = UIView() view.backgroundColor = .clear view.backgroundColor = UIColor(hex: 0x605c56, alpha: 0.5) view.layer.cornerRadius = 20 view.layer.masksToBounds = true containerView.addSubview(view) view.addSubview(avatarImgeView) avatarImgeView.layer.cornerRadius = 17 avatarImgeView.layer.masksToBounds = true view.addSubview(seecountLabel) view.addSubview(timeLabel) view.snp.makeConstraints { (maker) in maker.left.equalTo(12) maker.top.equalTo(35) maker.width.equalTo(150) maker.height.equalTo(40) } avatarImgeView.snp.makeConstraints { (maker) in maker.left.equalTo(2) maker.centerY.equalTo(view.snp.centerY) maker.width.equalTo(34) maker.height.equalTo(34) } timeLabel.snp.makeConstraints { (maker) in maker.left.equalTo(avatarImgeView.snp.right).offset(4) maker.centerY.equalTo(avatarImgeView.snp.centerY).offset(-10) maker.width.equalTo(80) } seecountLabel.snp.makeConstraints { (maker) in maker.left.equalTo(timeLabel.snp.left) maker.top.equalTo(timeLabel.snp.bottom).offset(3) } } /// 设置播放器 fileprivate func setupPlayer() { txLivePlayer.setupVideoWidget(svcontainerView.bounds, contain: svcontainerView, insert: 0) } /// 设置观众列表 fileprivate func setupViewerView() { containerView.addSubview(viewerView) viewerView.snp.makeConstraints { (maker) in maker.right.equalTo(-45) maker.top.equalTo(35) maker.height.equalTo(40) maker.width.equalTo(34 * 4) } containerView.addSubview(closeBtn) closeBtn.snp.makeConstraints { (maker) in maker.right.equalTo(-12) maker.centerY.equalTo(viewerView.snp.centerY) maker.width.equalTo(45) maker.height.equalTo(30) } closeBtn.rx.tap .subscribe(onNext: {[weak self] (value) in self?.showAlertView() }) .disposed(by: self.disposeBag) alterView.closeBtn.rx.tap .subscribe(onNext: { [weak self] (_) in self?.roomVM.messageHandler.quitLiveRoom().catch(execute: {_ in }) self?.broacastVM.endLive() .then(execute: { (endlive) -> Void in self?.broacastVM.stopRtmp() let vcc = FinishBroadcastVC() vcc.live = endlive self?.present(vcc, animated: true, completion: nil) }) .catch(execute: { error in }) }) .disposed(by: disposeBag) alterView.continueBtn.rx.tap .subscribe(onNext: { [weak self] (_) in UIView.animate(withDuration: 0.25, animations: { self?.alterView.removeFromSuperview() }) _ = self?.broacastVM.startRtmp() }) .disposed(by: disposeBag) } /// 设置哆豆 视图 fileprivate func setupBeansView() { let view = UIView() view.backgroundColor = .clear view.layer.cornerRadius = 9 view.layer.masksToBounds = true containerView.addSubview(view) view.snp.makeConstraints { (maker) in maker.left.equalTo(12) maker.top.equalTo(35 + 40 + 5) maker.width.equalTo(115) maker.height.equalTo(18) } let beanLabel = UILabel() beanLabel.text = "哆豆:" beanLabel.textColor = UIColor.white beanLabel.font = UIFont.systemFont(ofSize: 11) view.addSubview(beanLabel) beanLabel.snp.makeConstraints { (maker) in maker.left.equalTo(3) maker.centerY.equalTo(view.snp.centerY) } view.addSubview(beansCountlabel) beansCountlabel.snp.makeConstraints { (maker) in maker.left.equalTo(beanLabel.snp.right).offset(5) maker.centerY.equalTo(beanLabel.snp.centerY) } let cover = UILabel() cover.backgroundColor = UIColor(hex: CustomKey.Color.mainColor) cover.layer.cornerRadius = 9 cover.layer.masksToBounds = true view.insertSubview(cover, at: 0) cover.snp.makeConstraints { (maker) in maker.left.equalTo(view.snp.left) maker.top.equalTo(view.snp.top) maker.bottom.equalTo(view.snp.bottom) maker.right.equalTo(beansCountlabel.snp.right).offset(5) } } /// 设置哆豆ID视图 fileprivate func setupIDView() { let view = UIView() view.backgroundColor = .clear view.layer.cornerRadius = 9 view.layer.masksToBounds = true containerView.addSubview(view) view.snp.makeConstraints { (maker) in maker.right.equalTo(-15) maker.top.equalTo(35 + 40 + 5) maker.width.equalTo(145) maker.height.equalTo(18) } view.addSubview(IDlabel) IDlabel.snp.makeConstraints { (maker) in maker.right.equalTo(view.snp.right).offset(-5) maker.centerY.equalTo(view.snp.centerY) } let beanLabel = UILabel() beanLabel.text = "哆集直播ID: " beanLabel.textColor = UIColor.white beanLabel.font = UIFont.systemFont(ofSize: 11) view.addSubview(beanLabel) beanLabel.snp.makeConstraints { (maker) in maker.right.equalTo(IDlabel.snp.left).offset(5) maker.centerY.equalTo(view.snp.centerY) } let cover = UILabel() cover.backgroundColor = UIColor(hex: 0x605c56, alpha: 0.5) cover.layer.cornerRadius = 9 cover.layer.masksToBounds = true view.insertSubview(cover, at: 0) cover.snp.makeConstraints { (maker) in maker.left.equalTo(beanLabel.snp.left).offset(-5) maker.top.equalTo(view.snp.top) maker.bottom.equalTo(view.snp.bottom) maker.right.equalTo(IDlabel.snp.right).offset(5) } setupUserUIData() } /// 设置用户信息 private func setupUserUIData() { let info = broacastVM.liveInfo if let avatarURL = URL(string: CustomKey.URLKey.baseImageUrl + (info.avastar ?? "")) { avatarImgeView.kf.setImage(with: avatarURL) } IDlabel.text = " " + "\(info.userId)" } /// 设置底部视图 fileprivate func setupBottomView() { let cover = UIButton(frame: self.containerView.bounds) containerView.addSubview(messageBtn) messageBtn.snp.makeConstraints { (maker) in maker.left.equalTo(20) maker.bottom.equalTo(-12) maker.size.equalTo(CGSize(width: 34, height: 34)) } containerView.addSubview(screenShotBtn) screenShotBtn.snp.makeConstraints { (maker) in maker.bottom.equalTo(-12) maker.right.equalTo(-12) maker.size.equalTo(CGSize(width: 30, height: 30)) } containerView.addSubview(shareBtn) shareBtn.snp.makeConstraints { (maker) in maker.bottom.equalTo(-12) maker.right.equalTo(screenShotBtn.snp.left).offset(-30) maker.size.equalTo(CGSize(width: 30, height: 30)) } containerView.addSubview(switchCamerabtn) switchCamerabtn.snp.makeConstraints { (maker) in maker.bottom.equalTo(-12) maker.right.equalTo(shareBtn.snp.left).offset(-30) maker.size.equalTo(CGSize(width: 30, height: 30)) } containerView.addSubview(beautifyBtn) beautifyBtn.snp.makeConstraints { (maker) in maker.bottom.equalTo(-12) maker.right.equalTo(switchCamerabtn.snp.left).offset(-30) maker.size.equalTo(CGSize(width: 30, height: 30)) } beautifyBtn.rx.tap .subscribe(onNext: { [weak self] _ in guard let weakSelf = self else { return } UIView.animate(withDuration: 0.25, animations: { let translate = CGAffineTransform.init(translationX: 0, y: -CustomSize.beautiftyViewH) weakSelf.beautifyView.transform = translate weakSelf.containerView.insertSubview(cover, belowSubview: weakSelf.beautifyView) }) }) .disposed(by: disposeBag) switchCamerabtn.rx.tap .subscribe(onNext: { [weak self] _ in self?.broacastVM.switchCamera() }) .disposed(by: disposeBag) messageBtn.rx.tap .subscribe(onNext: { [weak self] _ in self?.chatView.messageTf.becomeFirstResponder() }) .disposed(by: disposeBag) screenShotBtn.rx.tap .subscribe(onNext: { (value) in let shot = UIScreen.getScreenShot() PHPhotoLibrary.shared().performChanges({ PHAssetChangeRequest.creationRequestForAsset(from: shot) }, completionHandler: { (isSuccess, error) in if isSuccess { HUD.showAlert(from: self, title: "提示", enterTitle: "确定", mesaage: "截图保存成功", success: {_ in }) } else { HUD.showAlert(from: self, title: "提示", enterTitle: "确定", mesaage: "截图保存失败", success: { _ in }) } }) }) .disposed(by: self.disposeBag) shareBtn.rx.tap .subscribe(onNext: { (value) in UIView.animate(withDuration: 0.25, animations: { let translate = CGAffineTransform.init(translationX: 0, y: -CustomKey.CustomSize.shareViewHight) self.shareView.transform = translate }) }) .disposed(by: self.disposeBag) shareBtn.rx.tap .subscribe(onNext: { (value) in self.containerView.insertSubview(cover, belowSubview: self.shareView) }) .disposed(by: self.disposeBag) cover.rx.tap .subscribe(onNext: { (value) in UIView.animate(withDuration: 0.25, animations: { self.shareView.transform = CGAffineTransform.identity self.beautifyView.transform = CGAffineTransform.identity }, completion: { _ in cover.removeFromSuperview() }) }) .disposed(by: self.disposeBag) } /// 设置分享UI fileprivate func setupShareView() { shareView.frame = CGRect(x: 0, y: UIScreen.height, width: UIScreen.width, height: CustomKey.CustomSize.shareViewHight) containerView.addSubview(shareView) weak var weakSelf = self guard let liveId = weakSelf?.broacastVM.liveInfo.liveNo else { return } let shareURL = CustomKey.URLKey.baseURL + "/live" + "/" + "\(liveId)" + "/html" let shareName = "Test" let shareContext = "Test" shareView.weiBtn.rx.tap .subscribe(onNext: { (value) in guard let imaage = UIImage(named: "iPhone 6") else { return } Utils.sharePlateType(SSDKPlatformType.typeSinaWeibo, imageArray: [imaage], contentText: shareContext, shareURL: shareURL, shareTitle: shareName, andViewController: self, success: {_ in }) }) .disposed(by: self.disposeBag) shareView.qqZoneBtn.rx.tap .subscribe(onNext: { (value) in guard let imaage = UIImage(named: "iPhone 6") else { return } Utils.sharePlateType(SSDKPlatformType.subTypeQZone, imageArray: [imaage], contentText: shareContext, shareURL: shareURL, shareTitle: shareName, andViewController: self, success: {_ in }) }) .disposed(by: self.disposeBag) shareView.weiChatBtn.rx.tap .subscribe(onNext: { (value) in guard let imaage = UIImage(named: "iPhone 6") else { return } Utils.sharePlateType(SSDKPlatformType.subTypeWechatSession, imageArray: [imaage], contentText: shareContext, shareURL: shareURL, shareTitle: shareName, andViewController: self, success: {_ in }) }) .disposed(by: self.disposeBag) shareView.qqBtn.rx.tap .subscribe(onNext: { (value) in guard let imaage = UIImage(named: "iPhone 6") else { return } Utils.sharePlateType(SSDKPlatformType.subTypeQQFriend, imageArray: [imaage], contentText: shareContext, shareURL: shareURL, shareTitle: shareName, andViewController: self, success: {_ in }) }) .disposed(by: self.disposeBag) shareView.friendCircleBtn.rx.tap .subscribe(onNext: { (value) in guard let imaage = UIImage(named: "iPhone 6") else { return } Utils.sharePlateType(SSDKPlatformType.subTypeWechatTimeline, imageArray: [imaage], contentText: shareContext, shareURL: shareURL, shareTitle: shareName, andViewController: self, success: {_ in }) }) .disposed(by: self.disposeBag) } /// 关闭直播的弹框 private func showAlertView() { view.endEditing(true) UIView.animate(withDuration: 0.25) { self.alterView.frame = self.view.bounds self.containerView.addSubview(self.alterView) } } /// 设置消息记录View fileprivate func setupMessageView() { let bottomH: CGFloat = CustomSize.bottomViewH let inset: CGFloat = CustomSize.messageTableInset let messageH: CGFloat = CustomSize.messageTableH messageTableView.frame = CGRect(x: 0, y: UIScreen.height - bottomH - inset - messageH, width: UIScreen.width, height: messageH) containerView.insertSubview(messageTableView, at: 0) dataSource.configureCell = { (dataSource, tableView, indexPath, element) in let cell: MessageTableViewCell = tableView.dequeueReusableCell(forIndexPath: indexPath) cell.configAttributeMessage(element) return cell } roomVM.messageHandler.recievedMessageCallback = { message in self.setupRecieveMessage(message) } } /// 收到信息的处理 fileprivate func setupRecieveMessage(_ message: IMMessage) { if message.userAction == .danmaku { setupDanmakuData(message) } if message.userAction == .commonGift { setupGiftAnimation(message: message) return } if message.userAction == .bigGift { setupGiftAnimation(message: message) return } self.roomVM.transFormIIMessgae(message) self.roomVM.caculateTextMessageHeight(message) let items = Observable.just([ SectionModel(model: "First section", items: self.roomVM.attributeMessages) ]) items .bind(to: self.messageTableView.rx.items(dataSource: self.dataSource)) .disposed(by: self.disposeBag) self.messageTableView.scrollToRow(at: IndexPath(row: self.roomVM.attributeMessages.count - 1, section: 0), at: .bottom, animated: true) } /// 结束直播 fileprivate func endBroacast() { broacastVM.stopRtmp() timer?.invalidate() timer = nil roomVM.messageHandler.quitLiveRoom().catch(execute: {_ in }) broacastVM.endLive().catch { (_) in} danmakuView.stop() } /// 聊天输入视图 fileprivate func setupChatView() { weak var weaksSelf = self guard let weakSelf = weaksSelf else { return } let chatViewHeight: CGFloat = CustomSize.chatViewHeight chatView.frame = CGRect(x: 0, y: UIScreen.height + chatViewHeight, width: UIScreen.width, height: chatViewHeight) containerView.addSubview(chatView) chatView.backgroundColor = .white NotificationCenter.default.rx .notification(Notification.Name(rawValue: "UIKeyboardWillShowNotification"), object: nil) .subscribe(onNext: { (note) in if let keyboardF = note.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect, let duration = note.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval { UIView.animate(withDuration: duration, animations: { weakSelf.chatView.frame.origin.y = keyboardF.origin.y - CustomSize.inputH weakSelf.messageTableView.frame.origin.y = weakSelf.chatView.frame.origin.y - weakSelf.messageTableView.frame.height }) } }) .disposed(by: disposeBag) NotificationCenter.default.rx .notification(Notification.Name(rawValue: "UIKeyboardWillHideNotification"), object: nil) .subscribe(onNext: { (note) in if let duration = note.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval { UIView.animate(withDuration: duration, animations: { weakSelf.chatView.frame.origin.y = UIScreen.height + chatViewHeight let bottomH: CGFloat = CustomSize.bottomViewH let inset: CGFloat = CustomSize.messageTableInset let messageH: CGFloat = CustomSize.messageTableH weakSelf.messageTableView.frame.origin.y = UIScreen.height - bottomH - inset - messageH }) } }) .disposed(by: disposeBag) chatView.sendBtn.rx.tap .subscribe(onNext: {(note) in weakSelf.sendTextInputMessage() }) .disposed(by: disposeBag) chatView.returnKeyPressAction = { _ in weakSelf.sendTextInputMessage() } roomVM.messageHandler.recievedMessageCallback = { message in weakSelf.setupRecieveMessage(message) } } //// 设置美颜美白视图 fileprivate func setupBeautifyView() { beautifyView.frame = CGRect(x: 0, y: UIScreen.height, width: UIScreen.width, height: CustomSize.beautiftyViewH) beautifyView.backgroundColor = .white containerView.addSubview(beautifyView) let faceSliderValue = Variable<Float>(0.5) _ = beautifyView.faceSlider.rx.value <-> faceSliderValue faceSliderValue.asObservable() .subscribe(onNext: { [weak self] x in self?.broacastVM.beautify(x) }) .disposed(by: disposeBag) let whiteSliderValue = Variable<Float>(0.5) _ = beautifyView.whiteSlider.rx.value <-> whiteSliderValue whiteSliderValue.asObservable() .subscribe(onNext: { [weak self] x in self?.broacastVM.whitenfy(x) }) .disposed(by: disposeBag) } } // MARK: IM extension BroadcastViewController { /// 登录房间 -> 加入房间 fileprivate func setupIM() { roomVM.loginRoom().then { _ -> Void in weak var weakSelf = self if let weakSelf = weakSelf, let groupId = weakSelf.broacastVM.liveInfo.groupId { weakSelf.roomVM.messageHandler.joinLiveRoom(with: groupId) .then(on: DispatchQueue.main, execute: { (_) -> Void in weakSelf.roomVM.messageHandler.joinGrooup() let myMessage = IMMessage() myMessage.userId = CoreDataManager.sharedInstance.getUserInfo()?.userId ?? 0 myMessage.nickName = CoreDataManager.sharedInstance.getUserInfo()?.nickName ?? "" myMessage.msg = "进入直播间" myMessage.userAction = .enterLive myMessage.level = CoreDataManager.sharedInstance.getUserInfo()?.level ?? 0 weakSelf.setupRecieveMessage(myMessage) if weakSelf.broacastVM.startRtmp() { weakSelf.addTimeLineTimer() } }) .catch(execute: { (error) in HUD.showAlert(from: weakSelf, title: "提示", enterTitle: "重试", cancleTitle: "取消", mesaage: "聊天室创建失败,请重试", success: { weakSelf.setupIM() }, failure: { weakSelf.dismiss(animated: true, completion: nil) }) }) } }.catch { error in if let error = error as? AppError { self.view.makeToast(error.message) } } } /// 发送文字消息 fileprivate func sendTextInputMessage() { weak var weaksSelf = self guard let weakSelf = weaksSelf else { return } if let message = chatView.messageTf.text, !message.isEmpty { let myMessage = IMMessage() myMessage.headPic = CoreDataManager.sharedInstance.getUserInfo()?.avatar ?? "" myMessage.userId = CoreDataManager.sharedInstance.getUserInfo()?.userId ?? 0 myMessage.nickName = CoreDataManager.sharedInstance.getUserInfo()?.nickName ?? "" myMessage.msg = message myMessage.level = CoreDataManager.sharedInstance.getUserInfo()?.level ?? 0 if chatView.isDanakuMessage { let danmakuParam = ChatRequestParam() danmakuParam.liveId = roomVM.room?.liveId ?? 0 roomVM.requestSendDanmaku(with: danmakuParam) .then(on: .main, execute: { (_) -> Void in myMessage.userAction = .danmaku weakSelf.roomVM.messageHandler.sendMessage(with: myMessage) weakSelf.setupRecieveMessage(myMessage) }) .catch(execute: { (error) in if let error = error as? AppError, error.erroCode == .pointUnavailable { weakSelf.toRechargeVC() } }) } else { myMessage.userAction = .text roomVM.messageHandler.sendTextMessage(message) setupRecieveMessage(myMessage) } chatView.messageTf.text = "" } } /// 跳转到充值界面 fileprivate func toRechargeVC() { HUD.showAlert(from: self, title: "提示", mesaage: "余额不足,请充值", doneActionTitle: "去充值", handle: { let vcc = RechargeController() self.present(NavigationController(rootViewController: vcc), animated: true, completion: nil) vcc.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "new_nav_arrow_black"), style: .plain, target: self, action: nil) vcc.navigationItem.leftBarButtonItem?.rx.tap .subscribe(onNext: { (value) in vcc.dismiss(animated: true, completion: nil) }) .disposed(by: self.disposeBag) }) } } /// MARK: COUNTDOWN extension BroadcastViewController: MGCustomCountDownDelagete { /// 倒计时结束 func customCountDown(_ downView: MGCustomCountDown!) { downView.isHidden = true downView.removeFromSuperview() getRealTimerInfo() } /// 添加定时器计算直播时长 fileprivate func addTimeLineTimer() { timer?.invalidate() timer = nil timer = Timer(timeInterval: 1.0, target: self, selector: #selector(self.timerAction), userInfo: nil, repeats: true) RunLoop.main.add(timer ?? Timer(), forMode: RunLoopMode.commonModes) } /// 显示推流的时长 @objc private func timerAction() { time += 1 let timeText = String(format: "%02d:%02d:%02d", Int(time / 3600.0), Int((time / 60.0).truncatingRemainder(dividingBy: 60.0)), Int(time.truncatingRemainder(dividingBy: 60.0))) timeLabel.text = timeText } } /// 设置消息列表cell的高度 extension BroadcastViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row < roomVM.cellHeights.count { return roomVM.cellHeights[indexPath.row] } return 30.0 } } // MARK: DANAKU extension BroadcastViewController: FXDanmakuDelegate { /// 设置弹幕 fileprivate func setupDanaku() { danmakuView.frame = CGRect(x: -UIScreen.width, y: 100, width: UIScreen.width * 2, height: 200) containerView.insertSubview(danmakuView, at: 0) let config = FXDanmakuConfiguration.default() config?.rowHeight = 40 config?.itemInsertOrder = .random danmakuView.configuration = config danmakuView.delegate = self danmakuView.register(DanmakuItem.self, forItemReuseIdentifier: "DanmakuItem") } /// 点击某一条弹幕 func danmaku(_ danmaku: FXDanmaku, didClick item: FXDanmakuItem, with data: FXDanmakuItemData) { } /// 根据消息设置弹幕样式 fileprivate func setupDanmakuData(_ message: IMMessage) { if let data = DanmakuItemData(itemReuseIdentifier: "DanmakuItem") { data.message = message danmakuView.add(data) } if !danmakuView.isRunning { danmakuView.start() } } } /// MARK: GIFT extension BroadcastViewController { /// 礼物列表 fileprivate func setupGitAnimateView() { gitftAnimateView.backgroundColor = UIColor.clear containerView.insertSubview(gitftAnimateView, at: 0) } /// 将礼物消息处理为动画 fileprivate func setupGiftAnimation(message: IMMessage) { switch message.userAction { case .commonGift: gitftAnimateView.addGift(message) case .bigGift: gitftAnimateView.addGift(message) bigGiftView.addGift(message) default: break } } /// 大礼物动画视图 fileprivate func setupBigGiftView() { bigGiftView.frame = containerView.bounds containerView.insertSubview(bigGiftView, at: 0) } } /// MARK:TIMER /// 定时获取用户信息 extension BroadcastViewController { fileprivate func addRealTimer() { realTimer?.invalidate() realTimer = nil realTimer = Timer(timeInterval: 5, target: self, selector: #selector(self.getRealTimerInfo), userInfo: nil, repeats: true) RunLoop.main.add(realTimer ?? Timer(), forMode: RunLoopMode.commonModes) } fileprivate func removeTimer() { realTimer?.invalidate() realTimer = nil timer?.invalidate() timer = nil } @objc fileprivate func getRealTimerInfo() { roomVM.requestRealTime(with: "\(broacastVM.liveInfo.liveId)") .then(execute: { [unowned self] (info) -> Void in self.beansCountlabel.text = "\(info.income)" self.seecountLabel.text = "\(info.seeingCount)" + "人" if let users = info.users { self.viewerView.config(Observable.just(users)) } }) .catch(execute: { _ in }) } }
mit
45decf70b681519cca9c7fc6a6e115e4
37.91438
211
0.589574
4.833788
false
false
false
false
vasarhelyia/SwiftySheetsDemo
SwiftySheetsDemo/Parser/SwiftyParser.swift
1
7029
// // SwiftyParser.swift // SwiftySheetsDemo // // Created by Alföldi Norbert on 16/07/16. // Copyright © 2016 Agnes Vasarhelyi. All rights reserved. // import Foundation private struct State { let row: Int let column: Int } @objc public class SwiftyParser : NSObject { public static let sharedInstance = SwiftyParser() private static var context: ASTContext? private var fileStack = Array<String>() private var stateStack = Array<State>() public func parseFile(path: String) throws -> ASTContext { guard let fileHandle = NSFileHandle(forReadingAtPath: path) else { throw NSError(domain: "ParserErrorDomain", code: -1, userInfo: [NSLocalizedDescriptionKey: "Could not open file at path: \(path)"]) } defer { fileHandle.closeFile() } beginParsing() fileStack.append(path) Parser.startWithFileDescriptor(fileHandle.fileDescriptor) guard yyparse() == 0 else { throw NSError(domain: "ParserErrorDomain", code: -1, userInfo: [NSLocalizedDescriptionKey: "Could not parse file at path: \(path)"]) } return SwiftyParser.context! } public func parseString(string: String) throws -> ASTContext { beginParsing() Parser.scanString(string) guard yyparse() == 0 else { throw NSError(domain: "ParserErrorDomain", code: -1, userInfo: [NSLocalizedDescriptionKey: "Could not parse string"]) } return SwiftyParser.context! } private func beginParsing() { fileStack.removeAll() SwiftyParser.context = ASTContext() } private func popFile() { if fileStack.count > 0 { fileStack.removeLast() } } private func pushState(path: String) { fileStack.append(path) stateStack.append(State(row: Int(row), column: Int(column))) } private func popState() { popFile() if let state = stateStack.last { row = CInt(state.row) column = CInt(state.column) stateStack.removeLast() } } private func resolvePath(path: String) -> String? { guard let lastPath = fileStack.last else { return nil } let lastDirectory = (lastPath as NSString).stringByDeletingLastPathComponent let resolvedPath = (lastDirectory as NSString).stringByAppendingPathComponent(path) return resolvedPath } public static func AST_handle_error(msg: String) { if let path = SwiftyParser.sharedInstance.fileStack.last { print("\(path):\(row):\(column): error: \(msg)") } else { print("Error: \(msg)") } } public static func AST_resolve_path(path: String) -> UnsafePointer<Int8> { guard let resolvedPath = SwiftyParser.sharedInstance.resolvePath(path) else { return nil } return (resolvedPath as NSString).UTF8String } public static func AST_push_state(path: String) { SwiftyParser.sharedInstance.pushState(path) } public static func AST_pop_state() { SwiftyParser.sharedInstance.popState() } public static func AST_styledef_register(styleElement: ASTExpression) { if let styleDefinition = styleElement as? ASTStyleDefinition { SwiftyParser.context?.addStyleDefinition(styleDefinition) } else if let styleVariable = styleElement as? ASTVariable { SwiftyParser.context?.addVariable(styleVariable) } } public static func AST_variable_get(name: String) -> ASTVariable? { return context?.variableWithName(name) } public static func AST_styledef_create(name: String, elements: Array<ASTStyleDefinition>) -> ASTStyleDefinition { return ASTStyleDefinition(name: name, elements: elements) } public static func AST_styleelements_create() -> Array<ASTStyleDefinition> { return Array<ASTStyleDefinition>() } public static func AST_styleelements_append(var elements: Array<ASTStyleDefinition>, element: ASTStyleDefinition) -> Array<ASTStyleDefinition> { elements.append(element) return elements } public static func AST_literal_create_fom_dec(dec: String) -> ASTNumericLiteral { return ASTNumericLiteral(stringLiteral: dec) } public static func AST_literal_create_fom_hex(hex: String) -> ASTNumericLiteral { return ASTNumericLiteral(stringLiteral: hex) } public static func AST_literal_create_fom_str(str: String) -> ASTStringLiteral { return ASTStringLiteral(stringLiteral: str) } public static func AST_exprlist_create(left: ASTExpression, right: ASTExpression) -> Array<ASTExpression> { var list = Array<ASTExpression>() list.append(left) list.append(right) return list } public static func AST_exprlist_append(var list: Array<ASTExpression>, element: ASTExpression) -> Array<ASTExpression> { list.append(element) return list } public static func AST_variable_declare(name: String, value: ASTExpression) -> ASTVariable { return ASTVariable(name: name, value: value) } public static func AST_property_create(name: String, value: ASTExpression) -> ASTPropertyDefinition { return ASTPropertyDefinition(propertyName: name, propertyValue: value) } public static func AST_expr_minus(operand: ASTExpression) -> ASTExpression? { if let numericLiteral = operand as? ASTNumericLiteral { return -numericLiteral } return ASTUnaryOperation(operand: operand) } @objc(AST_expr_add_left:right:) public static func AST_expr_add(left: ASTExpression, right: ASTExpression) -> ASTExpression { if let left = left as? ASTNumericLiteral, let right = right as? ASTNumericLiteral { return left + right } else if let left = left as? ASTStringLiteral, let right = right as? ASTStringLiteral { return left + right } return ASTBinaryOperation(leftOperand: left, rightOperand: right, operation: .Add) } @objc(AST_expr_sub_left:right:) public static func AST_expr_sub(left: ASTExpression, right: ASTExpression) -> ASTExpression { return ASTBinaryOperation(leftOperand: left, rightOperand: right, operation: .Sub) } @objc(AST_expr_mul_left:right:) public static func AST_expr_mul(left: ASTExpression, right: ASTExpression) -> ASTExpression { if let left = left as? ASTNumericLiteral, let right = right as? ASTNumericLiteral { return left * right } return ASTBinaryOperation(leftOperand: left, rightOperand: right, operation: .Mul) } @objc(AST_expr_div_left:right:) public static func AST_expr_div(left: ASTExpression, right: ASTExpression) -> ASTExpression { return ASTBinaryOperation(leftOperand: left, rightOperand: right, operation: .Div) } @objc(AST_color_create_from_r:g:b:) public static func AST_color_create_from_rgb(r: ASTExpression, g: ASTExpression, b: ASTExpression) -> ASTColorExpression { return ASTColorExpression(r: r, g: g, b: b) } public static func AST_color_create_from_packed_rgb(rgb: ASTExpression) -> ASTColorExpression { return ASTColorExpression(rgb: rgb) } @objc(AST_color_create_from_r:g:b:a:) public static func AST_color_create_from_rgba(r: ASTExpression, g: ASTExpression, b: ASTExpression, a: ASTExpression) -> ASTColorExpression { return ASTColorExpression(r: r, g: g, b: b, a: a) } public static func AST_color_create_from_packed_rgba(rgba: ASTExpression) -> ASTColorExpression { return ASTColorExpression(rgba: rgba) } }
mit
45b8770450618c6e06890e0090809f8a
29.955947
145
0.733172
3.721928
false
false
false
false
27629678/web_dev
client/Pods/FileBrowser/FileBrowser/FileListTableView.swift
3
3074
// // FlieListTableView.swift // FileBrowser // // Created by Roy Marmelstein on 14/02/2016. // Copyright © 2016 Roy Marmelstein. All rights reserved. // import Foundation extension FileListViewController: UITableViewDataSource, UITableViewDelegate { //MARK: UITableViewDataSource, UITableViewDelegate func numberOfSections(in tableView: UITableView) -> Int { if searchController.isActive { return 1 } return sections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if searchController.isActive { return filteredFiles.count } return sections[section].count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "FileCell" var cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier) if let reuseCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) { cell = reuseCell } cell.selectionStyle = .blue let selectedFile = fileForIndexPath(indexPath) cell.textLabel?.text = selectedFile.displayName cell.imageView?.image = selectedFile.type.image() return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedFile = fileForIndexPath(indexPath) searchController.isActive = false if selectedFile.isDirectory { let fileListViewController = FileListViewController(initialPath: selectedFile.filePath) fileListViewController.didSelectFile = didSelectFile self.navigationController?.pushViewController(fileListViewController, animated: true) } else { if let didSelectFile = didSelectFile { self.dismiss() didSelectFile(selectedFile) } else { let filePreview = previewManager.previewViewControllerForFile(selectedFile, fromNavigation: true) self.navigationController?.pushViewController(filePreview, animated: true) } } tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if searchController.isActive { return nil } if sections[section].count > 0 { return collation.sectionTitles[section] } else { return nil } } func sectionIndexTitles(for tableView: UITableView) -> [String]? { if searchController.isActive { return nil } return collation.sectionIndexTitles } func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { if searchController.isActive { return 0 } return collation.section(forSectionIndexTitle: index) } }
mit
eb273539a300a8be4874efe19f567162
33.144444
113
0.642044
5.776316
false
false
false
false
pardel/Reachability.swift
ReachabilityTests/ReachabilityTests.swift
3
3089
// // ReachabilityTests.swift // ReachabilityTests // // Created by Ashley Mills on 23/11/2015. // Copyright © 2015 Ashley Mills. All rights reserved. // import XCTest import Reachability class ReachabilityTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testValidHost() { // Testing with an invalid host will initially show as UNreachable, but then the callback // gets fired a second time reporting the host as reachable let reachability: Reachability let validHostName = "google.com" do { try reachability = Reachability(hostname: validHostName) } catch { XCTAssert(false, "Unable to create reachability") return } let expectation = expectationWithDescription("Check valid host") reachability.whenReachable = { reachability in dispatch_async(dispatch_get_main_queue()) { print("Pass: \(validHostName) is reachable - \(reachability)") // Only fulfill the expectaion on host reachable expectation.fulfill() } } reachability.whenUnreachable = { reachability in dispatch_async(dispatch_get_main_queue()) { print("\(validHostName) is initially unreachable - \(reachability)") // Expectation isn't fulfilled here, so wait will time out if this is the only closure called } } do { try reachability.startNotifier() } catch { XCTAssert(false, "Unable to start notifier") return } waitForExpectationsWithTimeout(5, handler: nil) reachability.stopNotifier() } func testInvalidHost() { let reachability: Reachability let invalidHostName = "invalidhost" do { try reachability = Reachability(hostname: invalidHostName) } catch { XCTAssert(false, "Unable to create reachability") return } let expectation = expectationWithDescription("Check invalid host") reachability.whenReachable = { reachability in dispatch_async(dispatch_get_main_queue()) { XCTAssert(false, "\(invalidHostName) should never be reachable - \(reachability))") } } reachability.whenUnreachable = { reachability in dispatch_async(dispatch_get_main_queue()) { print("Pass: \(invalidHostName) is unreachable - \(reachability))") expectation.fulfill() } } do { try reachability.startNotifier() } catch { XCTAssert(false, "Unable to start notifier") return } waitForExpectationsWithTimeout(5, handler: nil) reachability.stopNotifier() } }
bsd-2-clause
0b12cf40229b6311719b5238b9feb63b
28.980583
109
0.563472
5.739777
false
true
false
false
kentaiwami/FiNote
ios/FiNote/FiNote/Movie/MovieCommon.swift
1
2649
// // MovieCommon.swift // FiNote // // Created by 岩見建汰 on 2018/01/28. // Copyright © 2018年 Kenta. All rights reserved. // import UIKit import NVActivityIndicatorView import Alamofire import SwiftyJSON class MovieCommon { fileprivate let utility = Utility() func GetChoosingOnomatopoeia(values: [String:Any?]) -> [String] { // オノマトペとタグ番号の辞書を生成 var choosing: [String:Int] = [:] for dict in values { var tmp_matches: [String] = [] if dict.key.pregMatche(pattern: "onomatopoeia_([0-9]+)", matches: &tmp_matches) { choosing[dict.value as! String] = Int(tmp_matches[1])! } } // タグ番号の昇順でオノマトペを返す return choosing.sorted(by: {$0.value < $1.value}).map({$0.key}) } func GetOnomatopoeiaNewChoices(ignore: String = "", values: [String:Any?], choices: [String]) -> [String] { var new_choices = choices // 選択済みのオノマトペ名を選択肢配列から削除 for name in GetChoosingOnomatopoeia(values: values) { let index = new_choices.firstIndex(of: name) // ignoreと同じ場合は候補から削除しない if index != nil && name != ignore { new_choices.remove(at: index!.advanced(by: 0)) } } return new_choices } func CallGetOnomatopoeiaAPI(act: @escaping (JSON) -> Void, vc: UIViewController) { let urlString = API.base.rawValue+API.v1.rawValue+API.onomatopoeia.rawValue+API.choice.rawValue let activityData = ActivityData(message: "Get Onomatopoeia", type: .lineScaleParty) NVActivityIndicatorPresenter.sharedInstance.startAnimating(activityData, nil) DispatchQueue(label: "get-onomatopoeia").async { Alamofire.request(urlString, method: .get).responseJSON { (response) in NVActivityIndicatorPresenter.sharedInstance.stopAnimating(nil) guard let res = response.result.value else{return} let obj = JSON(res) print("***** API results *****") print(obj) print("***** API results *****") if self.utility.isHTTPStatus(statusCode: response.response?.statusCode) { act(obj) }else { self.utility.showStandardAlert(title: "Error", msg: obj.arrayValue[0].stringValue, vc: vc) } } } } }
mit
3e772ff724967a8c6463c829c336e77c
33.75
111
0.566347
4.135537
false
false
false
false
bugfender/BugfenderSDK-iOS-swift-sample
Pods/BugfenderSDK/Swift/Bugfender.swift
1
4838
// // Bugfender.swift // Bugfender // // This is a helper file for easier logging with Swift. // Copyright © 2017 Bugfender. All rights reserved. // import Foundation #if swift(>=3.1) extension Bugfender { public class func print(_ items: Any..., separator: String = " ", terminator: String = "\n", tag: String? = nil, level: BFLogLevel = .default, filename: String = #file, line: Int = #line, funcname: String = #function) { log(items: items, separator: separator, terminator: terminator, tag: tag, filename: filename, line: line, funcname: funcname) } public class func error(_ items: Any..., separator: String = " ", terminator: String = "\n", tag: String? = nil, filename: String = #file, line: Int = #line, funcname: String = #function) { log(items: items, separator: separator, terminator: terminator, tag: tag, level: .error, filename: filename, line: line, funcname: funcname) } public class func warning(_ items: Any..., separator: String = " ", terminator: String = "\n", tag: String? = nil, filename: String = #file, line: Int = #line, funcname: String = #function) { log(items: items, separator: separator, terminator: terminator, tag: tag, level: .warning, filename: filename, line: line, funcname: funcname) } private class func log(items: [Any], separator: String = " ", terminator: String = "\n", tag: String? = nil, level: BFLogLevel = .default, filename: String = #file, line: Int = #line, funcname: String = #function) { let message = items.map{String(describing: $0)}.joined(separator: separator) let file = ("\(filename)" as NSString).lastPathComponent as String Bugfender.log(lineNumber: line, method: funcname, file: file, level: level, tag: tag, message: message) } } public func BFLog(_ format: String, _ args: CVarArg..., tag: String? = nil, level: BFLogLevel = .default, filename: String = #file, line: Int = #line, funcname: String = #function) { let message = String(format: format, arguments: args) Bugfender.log(lineNumber: line, method: funcname, file: filename, level: level, tag: tag, message: message) } #elseif swift(>=3.0) extension Bugfender { public class func print(_ items: Any..., separator: String = " ", terminator: String = "\n", tag: String? = nil, level: BFLogLevel = .default, filename: String = #file, line: Int = #line, funcname: String = #function) { log(items: items, separator: separator, terminator: terminator, tag: tag, filename: filename, line: line, funcname: funcname) } public class func error(_ items: Any..., separator: String = " ", terminator: String = "\n", tag: String? = nil, filename: String = #file, line: Int = #line, funcname: String = #function) { log(items: items, separator: separator, terminator: terminator, tag: tag, level: .error, filename: filename, line: line, funcname: funcname) } public class func warning(_ items: Any..., separator: String = " ", terminator: String = "\n", tag: String? = nil, filename: String = #file, line: Int = #line, funcname: String = #function) { log(items: items, separator: separator, terminator: terminator, tag: tag, level: .warning, filename: filename, line: line, funcname: funcname) } private class func log(items: [Any], separator: String = " ", terminator: String = "\n", tag: String? = nil, level: BFLogLevel = .default, filename: String = #file, line: Int = #line, funcname: String = #function) { let message = items.map{String(describing: $0)}.joined(separator: separator) let file = ("\(filename)" as NSString).lastPathComponent as String Bugfender.log(lineNumber: line, method: funcname, file: file, level: level, tag: tag, message: message) } } public func BFLog(_ format: String, _ args: CVarArg..., tag: String? = nil, level: BFLogLevel = .default, filename: String = #file, line: Int = #line, funcname: String = #function) { let message = String(format: format, arguments: args) Bugfender.log(lineNumber: line, method: funcname, file: filename, level: level, tag: tag, message: message) } #elseif swift(>=2.3) func BFLog(_ message: String, filename: String = #file, line: Int = #line, funcname: String = #function) { let file = ("\(filename)" as NSString).lastPathComponent as String Bugfender.logLineNumber(line, method: funcname, file: file, level: BFLogLevel.default, tag: nil, message: message) #if DEBUG NSLog("[\(file):\(line)] \(funcname) - %@", message) #endif } #endif
apache-2.0
a592c81660b4d3ed5139404a7f37619d
61.012821
225
0.62332
4.113095
false
false
false
false
eoger/firefox-ios
Client/Frontend/Browser/TemporaryDocument.swift
3
3211
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Deferred import Shared private let temporaryDocumentOperationQueue = OperationQueue() class TemporaryDocument: NSObject { fileprivate let request: URLRequest fileprivate let filename: String fileprivate var session: URLSession? fileprivate var downloadTask: URLSessionDownloadTask? fileprivate var localFileURL: URL? fileprivate var pendingResult: Deferred<URL>? init(preflightResponse: URLResponse, request: URLRequest) { self.request = request self.filename = preflightResponse.suggestedFilename ?? "unknown" super.init() self.session = URLSession(configuration: .default, delegate: self, delegateQueue: temporaryDocumentOperationQueue) } deinit { // Delete the temp file. if let url = localFileURL { try? FileManager.default.removeItem(at: url) } } func getURL() -> Deferred<URL> { if let url = localFileURL { let result = Deferred<URL>() result.fill(url) return result } if let result = pendingResult { return result } let result = Deferred<URL>() pendingResult = result downloadTask = session?.downloadTask(with: request) downloadTask?.resume() UIApplication.shared.isNetworkActivityIndicatorVisible = true return result } } extension TemporaryDocument: URLSessionTaskDelegate, URLSessionDownloadDelegate { func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { ensureMainThread { UIApplication.shared.isNetworkActivityIndicatorVisible = false } // If we encounter an error downloading the temp file, just return with the // original remote URL so it can still be shared as a web URL. if error != nil, let remoteURL = request.url { pendingResult?.fill(remoteURL) pendingResult = nil } } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { let tempDirectory = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("TempDocs") let url = tempDirectory.appendingPathComponent(filename) try? FileManager.default.createDirectory(at: tempDirectory, withIntermediateDirectories: true, attributes: nil) try? FileManager.default.removeItem(at: url) do { try FileManager.default.moveItem(at: location, to: url) localFileURL = url pendingResult?.fill(url) pendingResult = nil } catch { // If we encounter an error downloading the temp file, just return with the // original remote URL so it can still be shared as a web URL. if let remoteURL = request.url { pendingResult?.fill(remoteURL) pendingResult = nil } } } }
mpl-2.0
76fdaaa84680d720e3282e98bf2bf9c5
32.8
122
0.657428
5.433164
false
false
false
false
mobgeek/swift
Swift em 4 Semanas/App Lista (7.0)/ListaData Solução 2/Lista/ListaTableViewController.swift
1
4378
// // ListaTableViewController.swift // Lista // // Created by Fabio Santos on 11/3/14. // Copyright (c) 2014 Fabio Santos. All rights reserved. // import UIKit class ListaTableViewController: UITableViewController { // MARK - Propriedades var itens: [ItemLista] = [] lazy var dateFormatter: NSDateFormatter = { let dateFormatter = NSDateFormatter() // Configure o estilo dateFormatter.dateStyle = .ShortStyle // Outros: NoStyle, ShortStyle, MediumStyle, FullStyle // Eventualmente: // dateFormatter.timeStyle = .ShortStyle // Cool Stuff: Hoje, Amanhã, etc.. // dateFormatter.doesRelativeDateFormatting = true // Alternativa: Há também a opção de criar formatos customizados...Para uma lista de especificadores consulte a documentação Data Formatting Guide: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1 // dateFormatter.dateFormat = "'Criado em' dd/MM/yyyy 'às' HH:mm" // dateFormatter.dateFormat = "EEE, MMM d" // Estabeleça o Português como preferência. NSLocale dateFormatter.locale = NSLocale(localeIdentifier:"pt_BR") return dateFormatter } () func timeSinceDate(date: NSDate) -> String { let startDate = date let endDate = NSDate() var calendar = NSCalendar.currentCalendar() let unidades: NSCalendarUnit = [.Day, .Hour, .Minute] let components = calendar.components(unidades, fromDate: startDate, toDate: endDate, options: []) return "Criado há \(components.day) dia(s) e \(components.minute) minuto(s) atrás" } // MARK - Helper Methods func carregarDadosIniciais() { var item1 = ItemLista(nome: "Comprar Maças") itens.append(item1) var item2 = ItemLista(nome: "Estudar Swift") itens.append(item2) var item3 = ItemLista(nome: "Ligar para o Banco") itens.append(item3) } // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() carregarDadosIniciais() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return itens.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ListaPrototypeCell", forIndexPath: indexPath) // Configure the cell... var itemDaLista = itens[indexPath.row] cell.textLabel!.text = itemDaLista.nome cell.accessoryType = itemDaLista.concluido ? UITableViewCellAccessoryType.Checkmark :UITableViewCellAccessoryType.None cell.detailTextLabel?.text = timeSinceDate(itemDaLista.dataCriacao) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) var itemTocado = itens[indexPath.row] itemTocado.concluido = !itemTocado.concluido tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None) } // MARK: - Navigation @IBAction func voltaParaLista(segue: UIStoryboardSegue!) { var sourceVC = segue.sourceViewController as! AdicionarItemViewController if let item = sourceVC.novoItemDaLista { itens.append(item) tableView.reloadData() } } }
mit
bee5e2c2dc9c85ef22723f0ab7be33fe
27.337662
311
0.613428
5.074419
false
false
false
false
onmyway133/Github.swift
Sources/Classes/PullRequest/PullRequest.swift
1
4165
// // PullRequest.swift // GithubSwift // // Created by Khoa Pham on 19/04/16. // Copyright © 2016 Fantageek. All rights reserved. // import Foundation import Tailor import Sugar // A pull request on a repository. public class PullRequest: Object { // The state of the pull request. open or closed. // // OCTPullRequestStateOpen - The pull request is open. // OCTPullRequestStateClosed - The pull request is closed. public enum State: String { case Open = "open" case Closed = "closed" } // The api URL for this pull request. public private(set) var URL: NSURL? // The webpage URL for this pull request. public private(set) var HTMLURL: NSURL? // The diff URL for this pull request. public private(set) var diffURL: NSURL? // The patch URL for this pull request. public private(set) var patchURL: NSURL? // The issue URL for this pull request. public private(set) var issueURL: NSURL? // The user that opened this pull request. public private(set) var user: User? // The title of this pull request. public private(set) var title: String = "" // The body text for this pull request. public private(set) var body: String = "" // The user this pull request is assigned to. public private(set) var assignee: User? // The date/time this pull request was created. public private(set) var creationDate: NSDate? // The date/time this pull request was last updated. public private(set) var updatedDate: NSDate? // The date/time this pull request was closed. nil if the // pull request has not been closed. public private(set) var closedDate: NSDate? // The date/time this pull request was merged. nil if the // pull request has not been merged. public private(set) var mergedDate: NSDate? // The state of this pull request. public private(set) var state: State = .Closed // The repository that contains the pull request's changes. public private(set) var headRepository: Repository? // The repository that the pull request's changes should be pulled into. public private(set) var baseRepository: Repository? /// The name of the branch which contains the pull request's changes. public private(set) var headBranch: String = "" /// The name of the branch into which the changes will be merged. public private(set) var baseBranch: String = "" /// The number of commits included in this pull request. public private(set) var commits: Int = 0 /// The number of additions included in this pull request. public private(set) var additions: Int = 0 /// The number of deletions included in this pull request. public private(set) var deletions: Int = 0 public required init(_ map: JSONDictionary) { super.init(map) self.objectID <- map.property("number") self.URL <- map.transform("url", transformer: NSURL.init(string: )) self.HTMLURL <- map.transform("html_url", transformer: NSURL.init(string: )) self.diffURL <- map.transform("diff_url", transformer: NSURL.init(string: )) self.patchURL <- map.transform("patch_url", transformer: NSURL.init(string: )) self.issueURL <- map.transform("issue_url", transformer: NSURL.init(string: )) self.user <- map.relation("user") self.title <- map.property("title") self.body <- map.property("body") self.assignee <- map.relation("assignee") self.creationDate <- map.transform("created_at", transformer: Transformer.stringToDate) self.updatedDate <- map.transform("updated_at", transformer: Transformer.stringToDate) self.closedDate <- map.transform("closed_at", transformer: Transformer.stringToDate) self.mergedDate <- map.transform("merged_at", transformer: Transformer.stringToDate) self.state <- map.`enum`("state") let head = map.dictionary("head") let base = map.dictionary("base") self.headRepository <- head?.property("repo") self.headBranch <- head?.property("ref") self.baseRepository <- base?.property("repo") self.baseBranch <- base?.property("ref") self.commits <- map.property("commits") self.additions <- map.property("additions") self.deletions <- map.property("deletions") } }
mit
64fda043d518d4d6dffab16e72648a6a
32.580645
91
0.701489
4.034884
false
false
false
false
FlyKite/DYJW-Swift
DYJW/iPhone/EduSystem/Controller/ScoreController.swift
1
1623
// // ScoreController.swift // DYJW // // Created by FlyKite on 2020/6/25. // Copyright © 2020 Doge Studio. All rights reserved. // import UIKit class ScoreController: UIViewController { private let dropdownList: MDDropdownList = MDDropdownList() private let tableView: UITableView = UITableView() private let scoreLabel: UILabel = UILabel() // private var dataArray override func viewDidLoad() { super.viewDidLoad() setupViews() getSchoolTermsList() } private func getSchoolTermsList() { EduSystemManager.shared.getSchoolTermList { (result) in switch result { case let .success(termList): self.dropdownList.data = termList case let .failure(error): print(error) } } } } extension ScoreController: MDDropdownListDelegate { func dropdownList(_ dropdownList: MDDropdownList, didSelectItemAt index: Int) { } } extension ScoreController { private func setupViews() { title = "成绩查询" view.backgroundColor = UIColor.grey50 let label = UILabel(frame: CGRect(x: 16, y: 88, width: 80, height: 48)) label.text = "开课学期" label.textColor = UIColor.grey800 dropdownList.frame = CGRect(x: 96, y: 88, width: view.frame.size.width - 96 - 16, height: 48) dropdownList.data = ["---请选择---"] dropdownList.delegate = self dropdownList.shownRows = 8 view.addSubview(label) view.addSubview(dropdownList) } }
gpl-3.0
8e92cd4b82d77a7485b17ee05b45ad70
24.806452
101
0.608125
4.359673
false
false
false
false
cwoloszynski/XCGLogger
Sources/XCGLogger/Destinations/AntennaDestination.swift
1
3493
// // AntennaDestination.swift // GotYourBackServer // // Created by Charlie Woloszynski on 1/15/17. // // import Dispatch import Foundation import libc open class AntennaDestination: BaseDestination { open var logQueue: DispatchQueue? = nil let formatter: DateFormatter var target: URL public init(target: URL) { self.target = target formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US") formatter.timeZone = TimeZone(abbreviation: "GMT") formatter.dateFormat = "EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'" } open override func output(logDetails: LogDetails, message: String) { let outputClosure = { var logDetails = logDetails var message = message // Apply filters, if any indicate we should drop the message, we abort before doing the actual logging if self.shouldExclude(logDetails: &logDetails, message: &message) { return } let parameters = self.logDetailParameters(logDetails) //create the session object let session = URLSession.shared //now create the URLRequest object using the url object var request = URLRequest(url: self.target) request.httpMethod = "POST" //set http method as POST do { request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body } catch let error { print(error.localizedDescription) } request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") //create dataTask using the session object to send data to the server let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in guard error == nil else { return } guard let data = data else { return } do { //create json object from data if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] { print(json) } } catch let error { print(error.localizedDescription) } }) task.resume() } if let logQueue = logQueue { logQueue.async(execute: outputClosure) } else { outputClosure() } } func logDetailParameters(_ logDetails: LogDetails) -> Dictionary<String, String> { let retvalue : [String: String] = ["level": logDetails.level.rawValue.description, "date" : formatter.string(from: logDetails.date), "message" : logDetails.message, "functionName" : logDetails.functionName, "fileName" : logDetails.fileName, "lineNumber" : logDetails.lineNumber.description ] return retvalue } }
mit
97dc317fbb156296316e6b918e42da44
32.266667
177
0.537933
5.624799
false
false
false
false
docopt/docopt.swift
Sources/Tokens.swift
2
1401
// // Tokens.swift // docopt // // Created by Pavel S. Mazurin on 3/1/15. // Copyright (c) 2015 kovpas. All rights reserved. // import Foundation internal class Tokens: Equatable, CustomStringConvertible { fileprivate var tokensArray: [String] var error: DocoptError var description: String { get { return "Tokens:\(tokensArray.joined(separator: " "))" } } convenience init(_ source: String, error: DocoptError = DocoptExit()) { self.init(source.split(), error: error) } init(_ source: [String], error: DocoptError = DocoptExit() ) { tokensArray = source self.error = error } static func fromPattern(_ source: String) -> Tokens { let res = source.replacingOccurrences(of: "([\\[\\]\\(\\)\\|]|\\.\\.\\.)", with: " $1 ", options: .regularExpression) let result = res.split("\\s+|(\\S*<.*?>)").filter { !$0.isEmpty } return Tokens(result, error: DocoptLanguageError()) } func current() -> String? { if tokensArray.isEmpty { return nil } return tokensArray[0] } func move() -> String? { if tokensArray.isEmpty { return nil } return tokensArray.remove(at: 0) } } func ==(lhs: Tokens, rhs: Tokens) -> Bool { return lhs.tokensArray == rhs.tokensArray }
mit
5e49a089a4d2a22e7ece7f16dd37d7bd
24.472727
125
0.560314
4.245455
false
false
false
false
nathanlentz/rivals
Rivals/Rivals/RivalriesInProgressTableViewController.swift
1
6373
// // RivalriesInProgressTableViewController.swift // Rivals // // Created by Nate Lentz on 4/17/17. // Copyright © 2017 ntnl.design. All rights reserved. // import UIKit import Firebase class RivalriesInProgressTableViewController: UITableViewController { var rivalries = [Rivalry]() var rivalriesCreatedByOthers = [Rivalry]() var sectionHeaders = ["Created By Me", "Created By Others"] override func viewWillAppear(_ animated: Bool) { ref.child("rivalries").observe(.childChanged, with: { (snapshot) in if let dict = snapshot.value as? [String: AnyObject] { let rivalry = Rivalry() rivalry.title = dict["game_name"] as? String rivalry.inProgress = dict["in_progress"] as? Bool rivalry.creatorId = dict["creator_id"] as? String rivalry.dateCreated = dict["creation_date"] as? String rivalry.rivalryKey = dict["rivalry_key"] as? String rivalry.players = dict["players"] as? [String] if rivalry.inProgress == false{ var index: Int = 0 for i in 0...self.rivalries.count - 1 { if rivalry.rivalryKey == self.rivalries[i].rivalryKey { index = i } } if index != -1 { self.rivalries.remove(at: index) } } DispatchQueue.main.async(execute: { self.tableView.reloadData() }) } }) } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Rivalries In Progress" getRivalriesInProgress() } @IBAction func doneButtonDidPress(_ sender: Any) { dismiss(animated: true, completion: nil) } func getRivalriesInProgress() { ref.child("rivalries").observe(.childAdded, with: { (snapshot) in // Add users into array and use that to populate rows if let dict = snapshot.value as? [String: AnyObject] { let uid = FIRAuth.auth()?.currentUser?.uid let rivalry = Rivalry() rivalry.title = dict["game_name"] as? String rivalry.inProgress = dict["in_progress"] as? Bool rivalry.creatorId = dict["creator_id"] as? String rivalry.dateCreated = dict["creation_date"] as? String rivalry.rivalryKey = dict["rivalry_key"] as? String rivalry.players = dict["players"] as? [String] if uid == rivalry.creatorId && rivalry.inProgress == true{ self.rivalries.append(rivalry) } // If you are included in players but are not the creator id, append rivalry to rivalriesNotCreatedByMe if uid != rivalry.creatorId && rivalry.players!.contains(uid!) { self.rivalriesCreatedByOthers.append(rivalry) } DispatchQueue.main.async(execute: { self.tableView.reloadData() }) } }, withCancel: nil) } // MARK: - Table view data source override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.sectionHeaders[section] } override func numberOfSections(in tableView: UITableView) -> Int { return self.sectionHeaders.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return self.rivalries.count } else { return self.rivalriesCreatedByOthers.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "rivalryCell") as! RivalryTableViewCell if indexPath.section == 0 { let rivalry = rivalries[indexPath.row] cell.gameTitleLabel.text = rivalry.title! cell.dateLabel.text = "Rivalry Created: " + rivalry.dateCreated! for i in 0...rivalry.players!.count - 1 { ref.child("profiles").child(rivalry.players![i]).observeSingleEvent(of: .value, with: { (snapshot) in if let dict = snapshot.value as? [String : Any] { if !cell.playersLabel.text!.contains(dict["name"] as! String) { cell.playersLabel.text! += " \(dict["name"] as! String) " } } }) } } // Second section - else { let rivalry = rivalriesCreatedByOthers[indexPath.row] cell.gameTitleLabel.text = rivalry.title! cell.dateLabel.text = "Rivalry Created: " + rivalry.dateCreated! for i in 0...rivalry.players!.count - 1 { ref.child("profiles").child(rivalry.players![i]).observeSingleEvent(of: .value, with: { (snapshot) in if let dict = snapshot.value as? [String : Any] { if !cell.playersLabel.text!.contains(dict["name"] as! String) { cell.playersLabel.text! += " \(dict["name"] as! String) " } } }) } } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 0 { performSegue(withIdentifier: "rivalryDetailSegue", sender: rivalries[indexPath.row]) } else { performSegue(withIdentifier: "rivalryDetailSegue", sender: rivalriesCreatedByOthers[indexPath.row]) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let segueVC = segue.destination as! EditRivalryViewController segueVC.rivalry = sender as! Rivalry } }
apache-2.0
91c8c8ad2ac7226aad60deaf16ff5052
35.411429
119
0.534683
5.126307
false
false
false
false
rodrigok/wwdc-2016-shcolarship
Rodrigo Nascimento/ViewController.swift
1
7429
// // ViewController.swift // Rodrigo Nascimento // // Created by Rodrigo Nascimento on 20/04/16. // Copyright (c) 2016 Rodrigo Nascimento. All rights reserved. // import UIKit import MessageUI class ViewController: UIViewController, MFMailComposeViewControllerDelegate { @IBOutlet weak var avatar: UIImageView! @IBOutlet weak var content: UIView! @IBOutlet weak var aboutMeScrollView: UIScrollView! @IBOutlet weak var projectsScrollView: UIScrollView! @IBOutlet weak var educationScrollView: UIScrollView! @IBOutlet weak var mainScrollView: UIScrollView! @IBOutlet weak var brasiliaMapImageView: UIImageView! @IBOutlet weak var trescoroasMapImageView: UIImageView! @IBOutlet weak var poaMapImageView: UIImageView! @IBOutlet weak var taquaraMapImageView: UIImageView! @IBOutlet weak var sanfranciscoMapImageView: UIImageView! @IBAction func contactMeAction(sender: AnyObject) { let emailTitle = "Scholarship App Contact" let toRecipents = ["[email protected]"] let mc: MFMailComposeViewController = MFMailComposeViewController() mc.mailComposeDelegate = self mc.setSubject(emailTitle) mc.setToRecipients(toRecipents) self.presentViewController(mc, animated: true, completion: nil) } @IBAction func startTutorialAction(sender: AnyObject) { NSUserDefaults.standardUserDefaults().setInteger(0, forKey: "TutorialCompleted") startTutorial() } func startTutorial() { if (NSUserDefaults.standardUserDefaults().integerForKey("TutorialCompleted") != 1) { self.performSegueWithIdentifier("segueTutorial", sender: self) } } func mailComposeController(controller:MFMailComposeViewController, didFinishWithResult result:MFMailComposeResult, error:NSError?) { switch result.rawValue { case MFMailComposeResultSent.rawValue: let alert = UIAlertController(title: "Mail sent", message:"Thanks for your contact", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in }) self.presentViewController(alert, animated: true){} case MFMailComposeResultFailed.rawValue: let alert = UIAlertController(title: "Ooops, mail sent failure", message:error!.localizedDescription, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in }) self.presentViewController(alert, animated: true){} default: break } self.dismissViewControllerAnimated(true, completion: nil) } func setCardStyle (view: AnyObject) { view.subviews.first?.layer.masksToBounds = true view.subviews.first?.layer.backgroundColor = UIColor(rgba: "#292b36").CGColor view.subviews.first?.layer.borderColor = UIColor(rgba: "#3A3E4F").CGColor view.subviews.first?.layer.borderWidth = 1 if let title:UILabel = view.subviews.first?.subviews[1] as? UILabel { let mutableAttributedString = NSMutableAttributedString(string: title.text!) if mutableAttributedString.mutableString.containsString("print(") { mutableAttributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor(rgba: "#00aba7"), range: NSRange(location:0, length:5)) mutableAttributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor(rgba: "#FFFFFF"), range: NSRange(location:5, length:1)) mutableAttributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor(rgba: "#FFFFFF"), range: NSRange(location:mutableAttributedString.length-1, length:1)) } title.attributedText = mutableAttributedString title.font = UIFont(name: "Menlo-Regular", size: 18) } } func mapImageTaped(sender: UITapGestureRecognizer) { self.performSegueWithIdentifier("segueMapView", sender: sender.view) } func handleMapImageTap(view: UIImageView) { let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.mapImageTaped(_:))) tap.numberOfTapsRequired = 1 tap.numberOfTouchesRequired = 1 view.addGestureRecognizer(tap) view.userInteractionEnabled = true } func setContentViewShadow() { self.content.layer.shadowColor = UIColor.blackColor().CGColor self.content.layer.shadowOffset = CGSize(width: 0, height: -50) self.content.layer.shadowOpacity = 0.8 self.content.layer.shadowRadius = 30 } func setAvatarShadowAndBorder() { self.avatar.layer.cornerRadius = self.avatar.frame.size.width / 2 self.avatar.clipsToBounds = true self.avatar.superview!.layer.cornerRadius = self.avatar.superview!.frame.size.width / 2 self.avatar.superview!.layer.shadowColor = UIColor.blackColor().CGColor self.avatar.superview!.layer.shadowOffset = CGSize(width: 0.4, height: 1) self.avatar.superview!.layer.shadowOpacity = 0.2 self.avatar.superview!.layer.shadowRadius = 0.5 } override func viewDidLoad() { super.viewDidLoad() // Remove comments to start tutorial always // NSUserDefaults.standardUserDefaults().setInteger(0, forKey: "TutorialCompleted") self.setAvatarShadowAndBorder() self.setContentViewShadow() for view in aboutMeScrollView.subviews { setCardStyle(view) } for view in educationScrollView.subviews { setCardStyle(view) } for view in projectsScrollView.subviews { setCardStyle(view) } handleMapImageTap(brasiliaMapImageView) handleMapImageTap(trescoroasMapImageView) handleMapImageTap(poaMapImageView) handleMapImageTap(taquaraMapImageView) handleMapImageTap(sanfranciscoMapImageView) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.startTutorial(); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "segueTutorial") { return; } let vc = segue.destinationViewController as! MapViewController switch sender!.tag { case 0: vc.setCoord(-15.8363347, lng: -47.8095463) vc.title = "Brasília, DF, Brazil" case 1: vc.setCoord(-29.4716888, lng: -50.7839087, delta: 2) vc.title = "Três Coroas, RS, Brazil" case 2: vc.setCoord(-30.060472, lng: -51.175532, delta: 2) vc.title = "Porto Alegre, RS, Brazil" case 3: vc.setCoord(-29.6556283, lng: -50.7740479, delta: 2) vc.title = "Taquara, RS, Brazil" case 4: vc.setCoord(37.783879, lng: -122.401254, delta: 2) vc.title = "San Francisco, CA, USA" default: NSLog("invalid map") } } override func prefersStatusBarHidden() -> Bool { return true } }
mit
3467fc6d17064dd6b08d7097e717de53
38.716578
186
0.657601
4.857423
false
false
false
false
naithar/Kitura-net
Sources/KituraNet/SPIUtils.swift
1
3754
/* * Copyright IBM Corporation 2016 * * 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(OSX) import Darwin #elseif os(Linux) import Glibc #endif import Foundation // MARK: SPIUtils /// A set of utility functions. public class SPIUtils { /// Abbreviations for month names private static let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] /// Abbreviations for days of the week private static let days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] /// Format the given time for use in HTTP, default value is current time. /// /// - Parameter timestamp: the time ( default value is current timestamp ) /// /// - Returns: string representation of timestamp public static func httpDate(from timestamp: time_t = time(nil)) -> String { var theTime = timestamp var timeStruct: tm = tm() gmtime_r(&theTime, &timeStruct) let wday = Int(timeStruct.tm_wday) let mday = Int(timeStruct.tm_mday) let mon = Int(timeStruct.tm_mon) let year = Int(timeStruct.tm_year) + 1900 let hour = Int(timeStruct.tm_hour) let min = Int(timeStruct.tm_min) let sec = Int(timeStruct.tm_sec) var s = days[wday] s.reserveCapacity(30) s.append(", ") s.append(twoDigit[mday]) s.append(" ") s.append(months[mon]) s.append(" ") s.append(twoDigit[year/100]) s.append(twoDigit[year%100]) s.append(" ") s.append(twoDigit[hour]) s.append(":") s.append(twoDigit[min]) s.append(":") s.append(twoDigit[sec]) s.append(" GMT") return s } /// Format the given date for use in HTTP /// /// - Parameter date: the date /// /// - Returns: string representation of Date public static func httpDate(_ date: Date) -> String { return httpDate(from: time_t(date.timeIntervalSince1970)) } /// Fast Int to String conversion private static let twoDigit = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99"] } extension Date { /// Format the date for use in HTTP /// /// - Returns: string representation of Date var httpDate: String { return SPIUtils.httpDate(self) } }
apache-2.0
b4f021f154d0bda5c5975be8000e82a8
34.415094
94
0.509323
3.691249
false
false
false
false
overtake/TelegramSwift
submodules/AppCenter-sdk/Vendor/OHHTTPStubs/Examples/SwiftPackageManager/OHHTTPStubsDemo/MainViewController.swift
3
5237
// // ViewController.swift // OHHTTPStubsDemo // // Created by Olivier Halligon on 18/04/2015. // Copyright (c) 2015 AliSoftware. All rights reserved. // import UIKit import OHHTTPStubs import OHHTTPStubsSwift class MainViewController: UIViewController { //////////////////////////////////////////////////////////////////////////////// // MARK: - Outlets @IBOutlet var delaySwitch: UISwitch! @IBOutlet var textView: UITextView! @IBOutlet var installTextStubSwitch: UISwitch! @IBOutlet var imageView: UIImageView! @IBOutlet var installImageStubSwitch: UISwitch! //////////////////////////////////////////////////////////////////////////////// // MARK: - Init & Dealloc override func viewDidLoad() { super.viewDidLoad() installTextStub(self.installTextStubSwitch) installImageStub(self.installImageStubSwitch) HTTPStubs.onStubActivation { (request: URLRequest, stub: HTTPStubsDescriptor, response: HTTPStubsResponse) in print("[OHHTTPStubs] Request to \(request.url!) has been stubbed with \(String(describing: stub.name))") } } //////////////////////////////////////////////////////////////////////////////// // MARK: - Global stubs activation @IBAction func toggleStubs(_ sender: UISwitch) { HTTPStubs.setEnabled(sender.isOn) self.delaySwitch.isEnabled = sender.isOn self.installTextStubSwitch.isEnabled = sender.isOn self.installImageStubSwitch.isEnabled = sender.isOn let state = sender.isOn ? "and enabled" : "but disabled" print("Installed (\(state)) stubs: \(HTTPStubs.allStubs())") } //////////////////////////////////////////////////////////////////////////////// // MARK: - Text Download and Stub @IBAction func downloadText(_ sender: UIButton) { sender.isEnabled = false self.textView.text = nil let urlString = "http://www.opensource.apple.com/source/Git/Git-26/src/git-htmldocs/git-commit.txt?txt" let req = URLRequest(url: URL(string: urlString)!) URLSession.shared.dataTask(with: req) { [weak self] (data, _, _) in DispatchQueue.main.async { guard let self = self else { return } sender.isEnabled = true if let receivedData = data, let receivedText = NSString(data: receivedData, encoding: String.Encoding.ascii.rawValue) { self.textView.text = receivedText as String } } }.resume() } weak var textStub: HTTPStubsDescriptor? @IBAction func installTextStub(_ sender: UISwitch) { if sender.isOn { // Install let stubPath = OHPathForFile("stub.txt", type(of: self)) textStub = stub(condition: isExtension("txt")) { [weak self] _ in let useDelay = DispatchQueue.main.sync { self?.delaySwitch.isOn ?? false } return fixture(filePath: stubPath!, headers: ["Content-Type":"text/plain"]) .requestTime(useDelay ? 2.0 : 0.0, responseTime:OHHTTPStubsDownloadSpeedWifi) } textStub?.name = "Text stub" } else { // Uninstall HTTPStubs.removeStub(textStub!) } } //////////////////////////////////////////////////////////////////////////////// // MARK: - Image Download and Stub @IBAction func downloadImage(_ sender: UIButton) { sender.isEnabled = false self.imageView.image = nil let urlString = "http://images.apple.com/support/assets/images/products/iphone/hero_iphone4-5_wide.png" let req = URLRequest(url: URL(string: urlString)!) URLSession.shared.dataTask(with: req) { [weak self] (data, _, _) in guard let self = self else { return } DispatchQueue.main.async { sender.isEnabled = true if let receivedData = data { self.imageView.image = UIImage(data: receivedData) } } }.resume() } weak var imageStub: HTTPStubsDescriptor? @IBAction func installImageStub(_ sender: UISwitch) { if sender.isOn { // Install let stubPath = OHPathForFile("stub.jpg", type(of: self)) imageStub = stub(condition: isExtension("png") || isExtension("jpg") || isExtension("gif")) { [weak self] _ in let useDelay = DispatchQueue.main.sync { self?.delaySwitch.isOn ?? false } return fixture(filePath: stubPath!, headers: ["Content-Type":"image/jpeg"]) .requestTime(useDelay ? 2.0 : 0.0, responseTime: OHHTTPStubsDownloadSpeedWifi) } imageStub?.name = "Image stub" } else { // Uninstall HTTPStubs.removeStub(imageStub!) } } //////////////////////////////////////////////////////////////////////////////// // MARK: - Cleaning @IBAction func clearResults() { self.textView.text = "" self.imageView.image = nil } }
gpl-2.0
8e35e3791ec222e8b0d1561cdcca5628
35.622378
135
0.531984
5.084466
false
false
false
false
huangboju/Moots
Examples/Lumia/Lumia/Component/SafeArea/Views/CollectionView/CollectionViewCellItem.swift
1
597
// // CollectionViewCellItem.swift // SafeAreaExample // // Created by Evgeny Mikhaylov on 13/10/2017. // Copyright © 2017 Rosberry. All rights reserved. // import UIKit class CollectionViewCellItem { typealias Handler = (() -> Void) var title: String var enabled: Bool var size: CGSize var selectionHandler: Handler? init(title: String, enabled: Bool = false, size: CGSize = .zero, selectionHandler: Handler? = nil) { self.title = title self.enabled = enabled self.size = size self.selectionHandler = selectionHandler } }
mit
e711c68de899671181bd3d65d21f6a09
21.923077
104
0.654362
4.167832
false
false
false
false
jphacks/TK_08
iOS/AirMeet/AirMeet/Source/BounceView.swift
5
2111
// // ENPullToBounseView.swift // BezierPathAnimation // // Created by Takuya Okamoto on 2015/08/11. // Copyright (c) 2015年 Uniface. All rights reserved. // import UIKit class BounceView: UIView { let ballView : BallView! let waveView : WaveView! init( frame:CGRect, bounceDuration: CFTimeInterval = 0.8, ballSize:CGFloat = 28,//32, ballMoveTimingFunc:CAMediaTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut), moveUpDuration:CFTimeInterval = 0.2, moveUpDist: CGFloat = 32 * 1.5, var color: UIColor! = UIColor.whiteColor() ) { if color == nil { color = UIColor.whiteColor() } let ballViewHeight: CGFloat = 100 ballView = BallView( frame: CGRectMake(0, -(ballViewHeight + 1), frame.width, ballViewHeight), circleSize: ballSize, timingFunc: ballMoveTimingFunc, moveUpDuration: moveUpDuration, moveUpDist: moveUpDist, color: color ) waveView = WaveView( frame:CGRectMake(0, 0, ballView.frame.width, frame.height), bounceDuration: bounceDuration, color: color ) super.init(frame: frame) ballView.hidden = true self.addSubview(ballView) self.addSubview(waveView) waveView.didEndPull = { NSTimer.schedule(delay: 0.2) { timer in self.ballView.hidden = false self.ballView.startAnimation() } } } func endingAnimation(complition:(()->())? = nil) { ballView.endAnimation { self.ballView.hidden = true complition?() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func wave(y: CGFloat) { waveView.wave(y) } func didRelease(y: CGFloat) { waveView.didRelease(amountX: 0, amountY: y) } }
mit
de06753e6c139257ccb265ba778db1da
25.375
110
0.557136
4.564935
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/Macie2/Macie2_Shapes.swift
1
122192
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import Foundation import SotoCore extension Macie2 { // MARK: Enums public enum AdminStatus: String, CustomStringConvertible, Codable { case disablingInProgress = "DISABLING_IN_PROGRESS" case enabled = "ENABLED" public var description: String { return self.rawValue } } public enum Currency: String, CustomStringConvertible, Codable { case usd = "USD" public var description: String { return self.rawValue } } public enum DayOfWeek: String, CustomStringConvertible, Codable { case friday = "FRIDAY" case monday = "MONDAY" case saturday = "SATURDAY" case sunday = "SUNDAY" case thursday = "THURSDAY" case tuesday = "TUESDAY" case wednesday = "WEDNESDAY" public var description: String { return self.rawValue } } public enum EffectivePermission: String, CustomStringConvertible, Codable { case notPublic = "NOT_PUBLIC" case `public` = "PUBLIC" case unknown = "UNKNOWN" public var description: String { return self.rawValue } } public enum EncryptionType: String, CustomStringConvertible, Codable { case aes256 = "AES256" case awsKms = "aws:kms" case none = "NONE" case unknown = "UNKNOWN" public var description: String { return self.rawValue } } public enum ErrorCode: String, CustomStringConvertible, Codable { case clienterror = "ClientError" case internalerror = "InternalError" public var description: String { return self.rawValue } } public enum FindingActionType: String, CustomStringConvertible, Codable { case awsApiCall = "AWS_API_CALL" public var description: String { return self.rawValue } } public enum FindingCategory: String, CustomStringConvertible, Codable { case classification = "CLASSIFICATION" case policy = "POLICY" public var description: String { return self.rawValue } } public enum FindingPublishingFrequency: String, CustomStringConvertible, Codable { case fifteenMinutes = "FIFTEEN_MINUTES" case oneHour = "ONE_HOUR" case sixHours = "SIX_HOURS" public var description: String { return self.rawValue } } public enum FindingStatisticsSortAttributeName: String, CustomStringConvertible, Codable { case count case groupkey = "groupKey" public var description: String { return self.rawValue } } public enum FindingType: String, CustomStringConvertible, Codable { case policyIamuserS3Blockpublicaccessdisabled = "Policy:IAMUser/S3BlockPublicAccessDisabled" case policyIamuserS3Bucketencryptiondisabled = "Policy:IAMUser/S3BucketEncryptionDisabled" case policyIamuserS3Bucketpublic = "Policy:IAMUser/S3BucketPublic" case policyIamuserS3Bucketreplicatedexternally = "Policy:IAMUser/S3BucketReplicatedExternally" case policyIamuserS3Bucketsharedexternally = "Policy:IAMUser/S3BucketSharedExternally" case sensitivedataS3ObjectCredentials = "SensitiveData:S3Object/Credentials" case sensitivedataS3ObjectCustomidentifier = "SensitiveData:S3Object/CustomIdentifier" case sensitivedataS3ObjectFinancial = "SensitiveData:S3Object/Financial" case sensitivedataS3ObjectMultiple = "SensitiveData:S3Object/Multiple" case sensitivedataS3ObjectPersonal = "SensitiveData:S3Object/Personal" public var description: String { return self.rawValue } } public enum FindingsFilterAction: String, CustomStringConvertible, Codable { case archive = "ARCHIVE" case noop = "NOOP" public var description: String { return self.rawValue } } public enum GroupBy: String, CustomStringConvertible, Codable { case classificationdetailsJobid = "classificationDetails.jobId" case resourcesaffectedS3BucketName = "resourcesAffected.s3Bucket.name" case severityDescription = "severity.description" case type public var description: String { return self.rawValue } } public enum JobComparator: String, CustomStringConvertible, Codable { case contains = "CONTAINS" case eq = "EQ" case gt = "GT" case gte = "GTE" case lt = "LT" case lte = "LTE" case ne = "NE" public var description: String { return self.rawValue } } public enum JobStatus: String, CustomStringConvertible, Codable { case cancelled = "CANCELLED" case complete = "COMPLETE" case idle = "IDLE" case paused = "PAUSED" case running = "RUNNING" case userPaused = "USER_PAUSED" public var description: String { return self.rawValue } } public enum JobType: String, CustomStringConvertible, Codable { case oneTime = "ONE_TIME" case scheduled = "SCHEDULED" public var description: String { return self.rawValue } } public enum ListJobsFilterKey: String, CustomStringConvertible, Codable { case createdat = "createdAt" case jobstatus = "jobStatus" case jobtype = "jobType" case name public var description: String { return self.rawValue } } public enum ListJobsSortAttributeName: String, CustomStringConvertible, Codable { case createdat = "createdAt" case jobstatus = "jobStatus" case jobtype = "jobType" case name public var description: String { return self.rawValue } } public enum MacieStatus: String, CustomStringConvertible, Codable { case enabled = "ENABLED" case paused = "PAUSED" public var description: String { return self.rawValue } } public enum OrderBy: String, CustomStringConvertible, Codable { case asc = "ASC" case desc = "DESC" public var description: String { return self.rawValue } } public enum RelationshipStatus: String, CustomStringConvertible, Codable { case accountsuspended = "AccountSuspended" case created = "Created" case emailverificationfailed = "EmailVerificationFailed" case emailverificationinprogress = "EmailVerificationInProgress" case enabled = "Enabled" case invited = "Invited" case paused = "Paused" case regiondisabled = "RegionDisabled" case removed = "Removed" case resigned = "Resigned" public var description: String { return self.rawValue } } public enum ScopeFilterKey: String, CustomStringConvertible, Codable { case bucketCreationDate = "BUCKET_CREATION_DATE" case objectExtension = "OBJECT_EXTENSION" case objectLastModifiedDate = "OBJECT_LAST_MODIFIED_DATE" case objectSize = "OBJECT_SIZE" case tag = "TAG" public var description: String { return self.rawValue } } public enum SensitiveDataItemCategory: String, CustomStringConvertible, Codable { case credentials = "CREDENTIALS" case customIdentifier = "CUSTOM_IDENTIFIER" case financialInformation = "FINANCIAL_INFORMATION" case personalInformation = "PERSONAL_INFORMATION" public var description: String { return self.rawValue } } public enum SeverityDescription: String, CustomStringConvertible, Codable { case high = "High" case low = "Low" case medium = "Medium" public var description: String { return self.rawValue } } public enum SharedAccess: String, CustomStringConvertible, Codable { case external = "EXTERNAL" case `internal` = "INTERNAL" case notShared = "NOT_SHARED" case unknown = "UNKNOWN" public var description: String { return self.rawValue } } public enum StorageClass: String, CustomStringConvertible, Codable { case deepArchive = "DEEP_ARCHIVE" case glacier = "GLACIER" case intelligentTiering = "INTELLIGENT_TIERING" case onezoneIa = "ONEZONE_IA" case reducedRedundancy = "REDUCED_REDUNDANCY" case standard = "STANDARD" case standardIa = "STANDARD_IA" public var description: String { return self.rawValue } } public enum TagTarget: String, CustomStringConvertible, Codable { case s3Object = "S3_OBJECT" public var description: String { return self.rawValue } } public enum Unit: String, CustomStringConvertible, Codable { case terabytes = "TERABYTES" public var description: String { return self.rawValue } } public enum UsageStatisticsFilterComparator: String, CustomStringConvertible, Codable { case contains = "CONTAINS" case eq = "EQ" case gt = "GT" case gte = "GTE" case lt = "LT" case lte = "LTE" case ne = "NE" public var description: String { return self.rawValue } } public enum UsageStatisticsFilterKey: String, CustomStringConvertible, Codable { case accountid = "accountId" case freetrialstartdate = "freeTrialStartDate" case servicelimit = "serviceLimit" case total public var description: String { return self.rawValue } } public enum UsageStatisticsSortKey: String, CustomStringConvertible, Codable { case accountid = "accountId" case freetrialstartdate = "freeTrialStartDate" case servicelimitvalue = "serviceLimitValue" case total public var description: String { return self.rawValue } } public enum UsageType: String, CustomStringConvertible, Codable { case dataInventoryEvaluation = "DATA_INVENTORY_EVALUATION" case sensitiveDataDiscovery = "SENSITIVE_DATA_DISCOVERY" public var description: String { return self.rawValue } } public enum UserIdentityType: String, CustomStringConvertible, Codable { case assumedrole = "AssumedRole" case awsaccount = "AWSAccount" case awsservice = "AWSService" case federateduser = "FederatedUser" case iamuser = "IAMUser" case root = "Root" public var description: String { return self.rawValue } } // MARK: Shapes public struct AcceptInvitationRequest: AWSEncodableShape { public let invitationId: String public let masterAccount: String public init(invitationId: String, masterAccount: String) { self.invitationId = invitationId self.masterAccount = masterAccount } private enum CodingKeys: String, CodingKey { case invitationId case masterAccount } } public struct AcceptInvitationResponse: AWSDecodableShape { public init() {} } public struct AccessControlList: AWSDecodableShape { public let allowsPublicReadAccess: Bool? public let allowsPublicWriteAccess: Bool? public init(allowsPublicReadAccess: Bool? = nil, allowsPublicWriteAccess: Bool? = nil) { self.allowsPublicReadAccess = allowsPublicReadAccess self.allowsPublicWriteAccess = allowsPublicWriteAccess } private enum CodingKeys: String, CodingKey { case allowsPublicReadAccess case allowsPublicWriteAccess } } public struct AccountDetail: AWSEncodableShape { public let accountId: String public let email: String public init(accountId: String, email: String) { self.accountId = accountId self.email = email } private enum CodingKeys: String, CodingKey { case accountId case email } } public struct AccountLevelPermissions: AWSDecodableShape { public let blockPublicAccess: BlockPublicAccess? public init(blockPublicAccess: BlockPublicAccess? = nil) { self.blockPublicAccess = blockPublicAccess } private enum CodingKeys: String, CodingKey { case blockPublicAccess } } public struct AdminAccount: AWSDecodableShape { public let accountId: String? public let status: AdminStatus? public init(accountId: String? = nil, status: AdminStatus? = nil) { self.accountId = accountId self.status = status } private enum CodingKeys: String, CodingKey { case accountId case status } } public struct ApiCallDetails: AWSDecodableShape { public let api: String? public let apiServiceName: String? @OptionalCustomCoding<ISO8601DateCoder> public var firstSeen: Date? @OptionalCustomCoding<ISO8601DateCoder> public var lastSeen: Date? public init(api: String? = nil, apiServiceName: String? = nil, firstSeen: Date? = nil, lastSeen: Date? = nil) { self.api = api self.apiServiceName = apiServiceName self.firstSeen = firstSeen self.lastSeen = lastSeen } private enum CodingKeys: String, CodingKey { case api case apiServiceName case firstSeen case lastSeen } } public struct AssumedRole: AWSDecodableShape { public let accessKeyId: String? public let accountId: String? public let arn: String? public let principalId: String? public let sessionContext: SessionContext? public init(accessKeyId: String? = nil, accountId: String? = nil, arn: String? = nil, principalId: String? = nil, sessionContext: SessionContext? = nil) { self.accessKeyId = accessKeyId self.accountId = accountId self.arn = arn self.principalId = principalId self.sessionContext = sessionContext } private enum CodingKeys: String, CodingKey { case accessKeyId case accountId case arn case principalId case sessionContext } } public struct AwsAccount: AWSDecodableShape { public let accountId: String? public let principalId: String? public init(accountId: String? = nil, principalId: String? = nil) { self.accountId = accountId self.principalId = principalId } private enum CodingKeys: String, CodingKey { case accountId case principalId } } public struct AwsService: AWSDecodableShape { public let invokedBy: String? public init(invokedBy: String? = nil) { self.invokedBy = invokedBy } private enum CodingKeys: String, CodingKey { case invokedBy } } public struct BatchGetCustomDataIdentifierSummary: AWSDecodableShape { public let arn: String? @OptionalCustomCoding<ISO8601DateCoder> public var createdAt: Date? public let deleted: Bool? public let description: String? public let id: String? public let name: String? public init(arn: String? = nil, createdAt: Date? = nil, deleted: Bool? = nil, description: String? = nil, id: String? = nil, name: String? = nil) { self.arn = arn self.createdAt = createdAt self.deleted = deleted self.description = description self.id = id self.name = name } private enum CodingKeys: String, CodingKey { case arn case createdAt case deleted case description case id case name } } public struct BatchGetCustomDataIdentifiersRequest: AWSEncodableShape { public let ids: [String]? public init(ids: [String]? = nil) { self.ids = ids } private enum CodingKeys: String, CodingKey { case ids } } public struct BatchGetCustomDataIdentifiersResponse: AWSDecodableShape { public let customDataIdentifiers: [BatchGetCustomDataIdentifierSummary]? public let notFoundIdentifierIds: [String]? public init(customDataIdentifiers: [BatchGetCustomDataIdentifierSummary]? = nil, notFoundIdentifierIds: [String]? = nil) { self.customDataIdentifiers = customDataIdentifiers self.notFoundIdentifierIds = notFoundIdentifierIds } private enum CodingKeys: String, CodingKey { case customDataIdentifiers case notFoundIdentifierIds } } public struct BlockPublicAccess: AWSDecodableShape { public let blockPublicAcls: Bool? public let blockPublicPolicy: Bool? public let ignorePublicAcls: Bool? public let restrictPublicBuckets: Bool? public init(blockPublicAcls: Bool? = nil, blockPublicPolicy: Bool? = nil, ignorePublicAcls: Bool? = nil, restrictPublicBuckets: Bool? = nil) { self.blockPublicAcls = blockPublicAcls self.blockPublicPolicy = blockPublicPolicy self.ignorePublicAcls = ignorePublicAcls self.restrictPublicBuckets = restrictPublicBuckets } private enum CodingKeys: String, CodingKey { case blockPublicAcls case blockPublicPolicy case ignorePublicAcls case restrictPublicBuckets } } public struct BucketCountByEffectivePermission: AWSDecodableShape { public let publiclyAccessible: Int64? public let publiclyReadable: Int64? public let publiclyWritable: Int64? public let unknown: Int64? public init(publiclyAccessible: Int64? = nil, publiclyReadable: Int64? = nil, publiclyWritable: Int64? = nil, unknown: Int64? = nil) { self.publiclyAccessible = publiclyAccessible self.publiclyReadable = publiclyReadable self.publiclyWritable = publiclyWritable self.unknown = unknown } private enum CodingKeys: String, CodingKey { case publiclyAccessible case publiclyReadable case publiclyWritable case unknown } } public struct BucketCountByEncryptionType: AWSDecodableShape { public let kmsManaged: Int64? public let s3Managed: Int64? public let unencrypted: Int64? public init(kmsManaged: Int64? = nil, s3Managed: Int64? = nil, unencrypted: Int64? = nil) { self.kmsManaged = kmsManaged self.s3Managed = s3Managed self.unencrypted = unencrypted } private enum CodingKeys: String, CodingKey { case kmsManaged case s3Managed case unencrypted } } public struct BucketCountBySharedAccessType: AWSDecodableShape { public let external: Int64? public let `internal`: Int64? public let notShared: Int64? public let unknown: Int64? public init(external: Int64? = nil, internal: Int64? = nil, notShared: Int64? = nil, unknown: Int64? = nil) { self.external = external self.`internal` = `internal` self.notShared = notShared self.unknown = unknown } private enum CodingKeys: String, CodingKey { case external case `internal` case notShared case unknown } } public struct BucketCriteriaAdditionalProperties: AWSEncodableShape { public let eq: [String]? public let gt: Int64? public let gte: Int64? public let lt: Int64? public let lte: Int64? public let neq: [String]? public let prefix: String? public init(eq: [String]? = nil, gt: Int64? = nil, gte: Int64? = nil, lt: Int64? = nil, lte: Int64? = nil, neq: [String]? = nil, prefix: String? = nil) { self.eq = eq self.gt = gt self.gte = gte self.lt = lt self.lte = lte self.neq = neq self.prefix = prefix } private enum CodingKeys: String, CodingKey { case eq case gt case gte case lt case lte case neq case prefix } } public struct BucketLevelPermissions: AWSDecodableShape { public let accessControlList: AccessControlList? public let blockPublicAccess: BlockPublicAccess? public let bucketPolicy: BucketPolicy? public init(accessControlList: AccessControlList? = nil, blockPublicAccess: BlockPublicAccess? = nil, bucketPolicy: BucketPolicy? = nil) { self.accessControlList = accessControlList self.blockPublicAccess = blockPublicAccess self.bucketPolicy = bucketPolicy } private enum CodingKeys: String, CodingKey { case accessControlList case blockPublicAccess case bucketPolicy } } public struct BucketMetadata: AWSDecodableShape { public let accountId: String? public let bucketArn: String? @OptionalCustomCoding<ISO8601DateCoder> public var bucketCreatedAt: Date? public let bucketName: String? public let classifiableObjectCount: Int64? public let classifiableSizeInBytes: Int64? @OptionalCustomCoding<ISO8601DateCoder> public var lastUpdated: Date? public let objectCount: Int64? public let objectCountByEncryptionType: ObjectCountByEncryptionType? public let publicAccess: BucketPublicAccess? public let region: String? public let replicationDetails: ReplicationDetails? public let sharedAccess: SharedAccess? public let sizeInBytes: Int64? public let sizeInBytesCompressed: Int64? public let tags: [KeyValuePair]? public let unclassifiableObjectCount: ObjectLevelStatistics? public let unclassifiableObjectSizeInBytes: ObjectLevelStatistics? public let versioning: Bool? public init(accountId: String? = nil, bucketArn: String? = nil, bucketCreatedAt: Date? = nil, bucketName: String? = nil, classifiableObjectCount: Int64? = nil, classifiableSizeInBytes: Int64? = nil, lastUpdated: Date? = nil, objectCount: Int64? = nil, objectCountByEncryptionType: ObjectCountByEncryptionType? = nil, publicAccess: BucketPublicAccess? = nil, region: String? = nil, replicationDetails: ReplicationDetails? = nil, sharedAccess: SharedAccess? = nil, sizeInBytes: Int64? = nil, sizeInBytesCompressed: Int64? = nil, tags: [KeyValuePair]? = nil, unclassifiableObjectCount: ObjectLevelStatistics? = nil, unclassifiableObjectSizeInBytes: ObjectLevelStatistics? = nil, versioning: Bool? = nil) { self.accountId = accountId self.bucketArn = bucketArn self.bucketCreatedAt = bucketCreatedAt self.bucketName = bucketName self.classifiableObjectCount = classifiableObjectCount self.classifiableSizeInBytes = classifiableSizeInBytes self.lastUpdated = lastUpdated self.objectCount = objectCount self.objectCountByEncryptionType = objectCountByEncryptionType self.publicAccess = publicAccess self.region = region self.replicationDetails = replicationDetails self.sharedAccess = sharedAccess self.sizeInBytes = sizeInBytes self.sizeInBytesCompressed = sizeInBytesCompressed self.tags = tags self.unclassifiableObjectCount = unclassifiableObjectCount self.unclassifiableObjectSizeInBytes = unclassifiableObjectSizeInBytes self.versioning = versioning } private enum CodingKeys: String, CodingKey { case accountId case bucketArn case bucketCreatedAt case bucketName case classifiableObjectCount case classifiableSizeInBytes case lastUpdated case objectCount case objectCountByEncryptionType case publicAccess case region case replicationDetails case sharedAccess case sizeInBytes case sizeInBytesCompressed case tags case unclassifiableObjectCount case unclassifiableObjectSizeInBytes case versioning } } public struct BucketPermissionConfiguration: AWSDecodableShape { public let accountLevelPermissions: AccountLevelPermissions? public let bucketLevelPermissions: BucketLevelPermissions? public init(accountLevelPermissions: AccountLevelPermissions? = nil, bucketLevelPermissions: BucketLevelPermissions? = nil) { self.accountLevelPermissions = accountLevelPermissions self.bucketLevelPermissions = bucketLevelPermissions } private enum CodingKeys: String, CodingKey { case accountLevelPermissions case bucketLevelPermissions } } public struct BucketPolicy: AWSDecodableShape { public let allowsPublicReadAccess: Bool? public let allowsPublicWriteAccess: Bool? public init(allowsPublicReadAccess: Bool? = nil, allowsPublicWriteAccess: Bool? = nil) { self.allowsPublicReadAccess = allowsPublicReadAccess self.allowsPublicWriteAccess = allowsPublicWriteAccess } private enum CodingKeys: String, CodingKey { case allowsPublicReadAccess case allowsPublicWriteAccess } } public struct BucketPublicAccess: AWSDecodableShape { public let effectivePermission: EffectivePermission? public let permissionConfiguration: BucketPermissionConfiguration? public init(effectivePermission: EffectivePermission? = nil, permissionConfiguration: BucketPermissionConfiguration? = nil) { self.effectivePermission = effectivePermission self.permissionConfiguration = permissionConfiguration } private enum CodingKeys: String, CodingKey { case effectivePermission case permissionConfiguration } } public struct BucketSortCriteria: AWSEncodableShape { public let attributeName: String? public let orderBy: OrderBy? public init(attributeName: String? = nil, orderBy: OrderBy? = nil) { self.attributeName = attributeName self.orderBy = orderBy } private enum CodingKeys: String, CodingKey { case attributeName case orderBy } } public struct Cell: AWSDecodableShape { public let cellReference: String? public let column: Int64? public let columnName: String? public let row: Int64? public init(cellReference: String? = nil, column: Int64? = nil, columnName: String? = nil, row: Int64? = nil) { self.cellReference = cellReference self.column = column self.columnName = columnName self.row = row } private enum CodingKeys: String, CodingKey { case cellReference case column case columnName case row } } public struct ClassificationDetails: AWSDecodableShape { public let detailedResultsLocation: String? public let jobArn: String? public let jobId: String? public let result: ClassificationResult? public init(detailedResultsLocation: String? = nil, jobArn: String? = nil, jobId: String? = nil, result: ClassificationResult? = nil) { self.detailedResultsLocation = detailedResultsLocation self.jobArn = jobArn self.jobId = jobId self.result = result } private enum CodingKeys: String, CodingKey { case detailedResultsLocation case jobArn case jobId case result } } public struct ClassificationExportConfiguration: AWSEncodableShape & AWSDecodableShape { public let s3Destination: S3Destination? public init(s3Destination: S3Destination? = nil) { self.s3Destination = s3Destination } private enum CodingKeys: String, CodingKey { case s3Destination } } public struct ClassificationResult: AWSDecodableShape { public let additionalOccurrences: Bool? public let customDataIdentifiers: CustomDataIdentifiers? public let mimeType: String? public let sensitiveData: [SensitiveDataItem]? public let sizeClassified: Int64? public let status: ClassificationResultStatus? public init(additionalOccurrences: Bool? = nil, customDataIdentifiers: CustomDataIdentifiers? = nil, mimeType: String? = nil, sensitiveData: [SensitiveDataItem]? = nil, sizeClassified: Int64? = nil, status: ClassificationResultStatus? = nil) { self.additionalOccurrences = additionalOccurrences self.customDataIdentifiers = customDataIdentifiers self.mimeType = mimeType self.sensitiveData = sensitiveData self.sizeClassified = sizeClassified self.status = status } private enum CodingKeys: String, CodingKey { case additionalOccurrences case customDataIdentifiers case mimeType case sensitiveData case sizeClassified case status } } public struct ClassificationResultStatus: AWSDecodableShape { public let code: String? public let reason: String? public init(code: String? = nil, reason: String? = nil) { self.code = code self.reason = reason } private enum CodingKeys: String, CodingKey { case code case reason } } public struct CreateClassificationJobRequest: AWSEncodableShape { public let clientToken: String public let customDataIdentifierIds: [String]? public let description: String? public let initialRun: Bool? public let jobType: JobType public let name: String public let s3JobDefinition: S3JobDefinition public let samplingPercentage: Int? public let scheduleFrequency: JobScheduleFrequency? public let tags: [String: String]? public init(clientToken: String = CreateClassificationJobRequest.idempotencyToken(), customDataIdentifierIds: [String]? = nil, description: String? = nil, initialRun: Bool? = nil, jobType: JobType, name: String, s3JobDefinition: S3JobDefinition, samplingPercentage: Int? = nil, scheduleFrequency: JobScheduleFrequency? = nil, tags: [String: String]? = nil) { self.clientToken = clientToken self.customDataIdentifierIds = customDataIdentifierIds self.description = description self.initialRun = initialRun self.jobType = jobType self.name = name self.s3JobDefinition = s3JobDefinition self.samplingPercentage = samplingPercentage self.scheduleFrequency = scheduleFrequency self.tags = tags } private enum CodingKeys: String, CodingKey { case clientToken case customDataIdentifierIds case description case initialRun case jobType case name case s3JobDefinition case samplingPercentage case scheduleFrequency case tags } } public struct CreateClassificationJobResponse: AWSDecodableShape { public let jobArn: String? public let jobId: String? public init(jobArn: String? = nil, jobId: String? = nil) { self.jobArn = jobArn self.jobId = jobId } private enum CodingKeys: String, CodingKey { case jobArn case jobId } } public struct CreateCustomDataIdentifierRequest: AWSEncodableShape { public let clientToken: String? public let description: String? public let ignoreWords: [String]? public let keywords: [String]? public let maximumMatchDistance: Int? public let name: String? public let regex: String? public let tags: [String: String]? public init(clientToken: String? = CreateCustomDataIdentifierRequest.idempotencyToken(), description: String? = nil, ignoreWords: [String]? = nil, keywords: [String]? = nil, maximumMatchDistance: Int? = nil, name: String? = nil, regex: String? = nil, tags: [String: String]? = nil) { self.clientToken = clientToken self.description = description self.ignoreWords = ignoreWords self.keywords = keywords self.maximumMatchDistance = maximumMatchDistance self.name = name self.regex = regex self.tags = tags } private enum CodingKeys: String, CodingKey { case clientToken case description case ignoreWords case keywords case maximumMatchDistance case name case regex case tags } } public struct CreateCustomDataIdentifierResponse: AWSDecodableShape { public let customDataIdentifierId: String? public init(customDataIdentifierId: String? = nil) { self.customDataIdentifierId = customDataIdentifierId } private enum CodingKeys: String, CodingKey { case customDataIdentifierId } } public struct CreateFindingsFilterRequest: AWSEncodableShape { public let action: FindingsFilterAction public let clientToken: String? public let description: String? public let findingCriteria: FindingCriteria public let name: String public let position: Int? public let tags: [String: String]? public init(action: FindingsFilterAction, clientToken: String? = CreateFindingsFilterRequest.idempotencyToken(), description: String? = nil, findingCriteria: FindingCriteria, name: String, position: Int? = nil, tags: [String: String]? = nil) { self.action = action self.clientToken = clientToken self.description = description self.findingCriteria = findingCriteria self.name = name self.position = position self.tags = tags } private enum CodingKeys: String, CodingKey { case action case clientToken case description case findingCriteria case name case position case tags } } public struct CreateFindingsFilterResponse: AWSDecodableShape { public let arn: String? public let id: String? public init(arn: String? = nil, id: String? = nil) { self.arn = arn self.id = id } private enum CodingKeys: String, CodingKey { case arn case id } } public struct CreateInvitationsRequest: AWSEncodableShape { public let accountIds: [String] public let disableEmailNotification: Bool? public let message: String? public init(accountIds: [String], disableEmailNotification: Bool? = nil, message: String? = nil) { self.accountIds = accountIds self.disableEmailNotification = disableEmailNotification self.message = message } private enum CodingKeys: String, CodingKey { case accountIds case disableEmailNotification case message } } public struct CreateInvitationsResponse: AWSDecodableShape { public let unprocessedAccounts: [UnprocessedAccount]? public init(unprocessedAccounts: [UnprocessedAccount]? = nil) { self.unprocessedAccounts = unprocessedAccounts } private enum CodingKeys: String, CodingKey { case unprocessedAccounts } } public struct CreateMemberRequest: AWSEncodableShape { public let account: AccountDetail public let tags: [String: String]? public init(account: AccountDetail, tags: [String: String]? = nil) { self.account = account self.tags = tags } private enum CodingKeys: String, CodingKey { case account case tags } } public struct CreateMemberResponse: AWSDecodableShape { public let arn: String? public init(arn: String? = nil) { self.arn = arn } private enum CodingKeys: String, CodingKey { case arn } } public struct CreateSampleFindingsRequest: AWSEncodableShape { public let findingTypes: [FindingType]? public init(findingTypes: [FindingType]? = nil) { self.findingTypes = findingTypes } private enum CodingKeys: String, CodingKey { case findingTypes } } public struct CreateSampleFindingsResponse: AWSDecodableShape { public init() {} } public struct CriterionAdditionalProperties: AWSEncodableShape & AWSDecodableShape { public let eq: [String]? public let gt: Int64? public let gte: Int64? public let lt: Int64? public let lte: Int64? public let neq: [String]? public init(eq: [String]? = nil, gt: Int64? = nil, gte: Int64? = nil, lt: Int64? = nil, lte: Int64? = nil, neq: [String]? = nil) { self.eq = eq self.gt = gt self.gte = gte self.lt = lt self.lte = lte self.neq = neq } private enum CodingKeys: String, CodingKey { case eq case gt case gte case lt case lte case neq } } public struct CustomDataIdentifierSummary: AWSDecodableShape { public let arn: String? @OptionalCustomCoding<ISO8601DateCoder> public var createdAt: Date? public let description: String? public let id: String? public let name: String? public init(arn: String? = nil, createdAt: Date? = nil, description: String? = nil, id: String? = nil, name: String? = nil) { self.arn = arn self.createdAt = createdAt self.description = description self.id = id self.name = name } private enum CodingKeys: String, CodingKey { case arn case createdAt case description case id case name } } public struct CustomDataIdentifiers: AWSDecodableShape { public let detections: [CustomDetection]? public let totalCount: Int64? public init(detections: [CustomDetection]? = nil, totalCount: Int64? = nil) { self.detections = detections self.totalCount = totalCount } private enum CodingKeys: String, CodingKey { case detections case totalCount } } public struct CustomDetection: AWSDecodableShape { public let arn: String? public let count: Int64? public let name: String? public let occurrences: Occurrences? public init(arn: String? = nil, count: Int64? = nil, name: String? = nil, occurrences: Occurrences? = nil) { self.arn = arn self.count = count self.name = name self.occurrences = occurrences } private enum CodingKeys: String, CodingKey { case arn case count case name case occurrences } } public struct DailySchedule: AWSEncodableShape & AWSDecodableShape { public init() {} } public struct DeclineInvitationsRequest: AWSEncodableShape { public let accountIds: [String] public init(accountIds: [String]) { self.accountIds = accountIds } private enum CodingKeys: String, CodingKey { case accountIds } } public struct DeclineInvitationsResponse: AWSDecodableShape { public let unprocessedAccounts: [UnprocessedAccount]? public init(unprocessedAccounts: [UnprocessedAccount]? = nil) { self.unprocessedAccounts = unprocessedAccounts } private enum CodingKeys: String, CodingKey { case unprocessedAccounts } } public struct DefaultDetection: AWSDecodableShape { public let count: Int64? public let occurrences: Occurrences? public let type: String? public init(count: Int64? = nil, occurrences: Occurrences? = nil, type: String? = nil) { self.count = count self.occurrences = occurrences self.type = type } private enum CodingKeys: String, CodingKey { case count case occurrences case type } } public struct DeleteCustomDataIdentifierRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "id", location: .uri(locationName: "id")) ] public let id: String public init(id: String) { self.id = id } private enum CodingKeys: CodingKey {} } public struct DeleteCustomDataIdentifierResponse: AWSDecodableShape { public init() {} } public struct DeleteFindingsFilterRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "id", location: .uri(locationName: "id")) ] public let id: String public init(id: String) { self.id = id } private enum CodingKeys: CodingKey {} } public struct DeleteFindingsFilterResponse: AWSDecodableShape { public init() {} } public struct DeleteInvitationsRequest: AWSEncodableShape { public let accountIds: [String] public init(accountIds: [String]) { self.accountIds = accountIds } private enum CodingKeys: String, CodingKey { case accountIds } } public struct DeleteInvitationsResponse: AWSDecodableShape { public let unprocessedAccounts: [UnprocessedAccount]? public init(unprocessedAccounts: [UnprocessedAccount]? = nil) { self.unprocessedAccounts = unprocessedAccounts } private enum CodingKeys: String, CodingKey { case unprocessedAccounts } } public struct DeleteMemberRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "id", location: .uri(locationName: "id")) ] public let id: String public init(id: String) { self.id = id } private enum CodingKeys: CodingKey {} } public struct DeleteMemberResponse: AWSDecodableShape { public init() {} } public struct DescribeBucketsRequest: AWSEncodableShape { public let criteria: [String: BucketCriteriaAdditionalProperties]? public let maxResults: Int? public let nextToken: String? public let sortCriteria: BucketSortCriteria? public init(criteria: [String: BucketCriteriaAdditionalProperties]? = nil, maxResults: Int? = nil, nextToken: String? = nil, sortCriteria: BucketSortCriteria? = nil) { self.criteria = criteria self.maxResults = maxResults self.nextToken = nextToken self.sortCriteria = sortCriteria } private enum CodingKeys: String, CodingKey { case criteria case maxResults case nextToken case sortCriteria } } public struct DescribeBucketsResponse: AWSDecodableShape { public let buckets: [BucketMetadata]? public let nextToken: String? public init(buckets: [BucketMetadata]? = nil, nextToken: String? = nil) { self.buckets = buckets self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case buckets case nextToken } } public struct DescribeClassificationJobRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "jobId", location: .uri(locationName: "jobId")) ] public let jobId: String public init(jobId: String) { self.jobId = jobId } private enum CodingKeys: CodingKey {} } public struct DescribeClassificationJobResponse: AWSDecodableShape { public let clientToken: String? @OptionalCustomCoding<ISO8601DateCoder> public var createdAt: Date? public let customDataIdentifierIds: [String]? public let description: String? public let initialRun: Bool? public let jobArn: String? public let jobId: String? public let jobStatus: JobStatus? public let jobType: JobType? @OptionalCustomCoding<ISO8601DateCoder> public var lastRunTime: Date? public let name: String? public let s3JobDefinition: S3JobDefinition? public let samplingPercentage: Int? public let scheduleFrequency: JobScheduleFrequency? public let statistics: Statistics? public let tags: [String: String]? public let userPausedDetails: UserPausedDetails? public init(clientToken: String? = DescribeClassificationJobResponse.idempotencyToken(), createdAt: Date? = nil, customDataIdentifierIds: [String]? = nil, description: String? = nil, initialRun: Bool? = nil, jobArn: String? = nil, jobId: String? = nil, jobStatus: JobStatus? = nil, jobType: JobType? = nil, lastRunTime: Date? = nil, name: String? = nil, s3JobDefinition: S3JobDefinition? = nil, samplingPercentage: Int? = nil, scheduleFrequency: JobScheduleFrequency? = nil, statistics: Statistics? = nil, tags: [String: String]? = nil, userPausedDetails: UserPausedDetails? = nil) { self.clientToken = clientToken self.createdAt = createdAt self.customDataIdentifierIds = customDataIdentifierIds self.description = description self.initialRun = initialRun self.jobArn = jobArn self.jobId = jobId self.jobStatus = jobStatus self.jobType = jobType self.lastRunTime = lastRunTime self.name = name self.s3JobDefinition = s3JobDefinition self.samplingPercentage = samplingPercentage self.scheduleFrequency = scheduleFrequency self.statistics = statistics self.tags = tags self.userPausedDetails = userPausedDetails } private enum CodingKeys: String, CodingKey { case clientToken case createdAt case customDataIdentifierIds case description case initialRun case jobArn case jobId case jobStatus case jobType case lastRunTime case name case s3JobDefinition case samplingPercentage case scheduleFrequency case statistics case tags case userPausedDetails } } public struct DescribeOrganizationConfigurationRequest: AWSEncodableShape { public init() {} } public struct DescribeOrganizationConfigurationResponse: AWSDecodableShape { public let autoEnable: Bool? public let maxAccountLimitReached: Bool? public init(autoEnable: Bool? = nil, maxAccountLimitReached: Bool? = nil) { self.autoEnable = autoEnable self.maxAccountLimitReached = maxAccountLimitReached } private enum CodingKeys: String, CodingKey { case autoEnable case maxAccountLimitReached } } public struct DisableMacieRequest: AWSEncodableShape { public init() {} } public struct DisableMacieResponse: AWSDecodableShape { public init() {} } public struct DisableOrganizationAdminAccountRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "adminAccountId", location: .querystring(locationName: "adminAccountId")) ] public let adminAccountId: String public init(adminAccountId: String) { self.adminAccountId = adminAccountId } private enum CodingKeys: CodingKey {} } public struct DisableOrganizationAdminAccountResponse: AWSDecodableShape { public init() {} } public struct DisassociateFromMasterAccountRequest: AWSEncodableShape { public init() {} } public struct DisassociateFromMasterAccountResponse: AWSDecodableShape { public init() {} } public struct DisassociateMemberRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "id", location: .uri(locationName: "id")) ] public let id: String public init(id: String) { self.id = id } private enum CodingKeys: CodingKey {} } public struct DisassociateMemberResponse: AWSDecodableShape { public init() {} } public struct DomainDetails: AWSDecodableShape { public let domainName: String? public init(domainName: String? = nil) { self.domainName = domainName } private enum CodingKeys: String, CodingKey { case domainName } } public struct EnableMacieRequest: AWSEncodableShape { public let clientToken: String? public let findingPublishingFrequency: FindingPublishingFrequency? public let status: MacieStatus? public init(clientToken: String? = EnableMacieRequest.idempotencyToken(), findingPublishingFrequency: FindingPublishingFrequency? = nil, status: MacieStatus? = nil) { self.clientToken = clientToken self.findingPublishingFrequency = findingPublishingFrequency self.status = status } private enum CodingKeys: String, CodingKey { case clientToken case findingPublishingFrequency case status } } public struct EnableMacieResponse: AWSDecodableShape { public init() {} } public struct EnableOrganizationAdminAccountRequest: AWSEncodableShape { public let adminAccountId: String public let clientToken: String? public init(adminAccountId: String, clientToken: String? = EnableOrganizationAdminAccountRequest.idempotencyToken()) { self.adminAccountId = adminAccountId self.clientToken = clientToken } private enum CodingKeys: String, CodingKey { case adminAccountId case clientToken } } public struct EnableOrganizationAdminAccountResponse: AWSDecodableShape { public init() {} } public struct FederatedUser: AWSDecodableShape { public let accessKeyId: String? public let accountId: String? public let arn: String? public let principalId: String? public let sessionContext: SessionContext? public init(accessKeyId: String? = nil, accountId: String? = nil, arn: String? = nil, principalId: String? = nil, sessionContext: SessionContext? = nil) { self.accessKeyId = accessKeyId self.accountId = accountId self.arn = arn self.principalId = principalId self.sessionContext = sessionContext } private enum CodingKeys: String, CodingKey { case accessKeyId case accountId case arn case principalId case sessionContext } } public struct Finding: AWSDecodableShape { public let accountId: String? public let archived: Bool? public let category: FindingCategory? public let classificationDetails: ClassificationDetails? public let count: Int64? @OptionalCustomCoding<ISO8601DateCoder> public var createdAt: Date? public let description: String? public let id: String? public let partition: String? public let policyDetails: PolicyDetails? public let region: String? public let resourcesAffected: ResourcesAffected? public let sample: Bool? public let schemaVersion: String? public let severity: Severity? public let title: String? public let type: FindingType? @OptionalCustomCoding<ISO8601DateCoder> public var updatedAt: Date? public init(accountId: String? = nil, archived: Bool? = nil, category: FindingCategory? = nil, classificationDetails: ClassificationDetails? = nil, count: Int64? = nil, createdAt: Date? = nil, description: String? = nil, id: String? = nil, partition: String? = nil, policyDetails: PolicyDetails? = nil, region: String? = nil, resourcesAffected: ResourcesAffected? = nil, sample: Bool? = nil, schemaVersion: String? = nil, severity: Severity? = nil, title: String? = nil, type: FindingType? = nil, updatedAt: Date? = nil) { self.accountId = accountId self.archived = archived self.category = category self.classificationDetails = classificationDetails self.count = count self.createdAt = createdAt self.description = description self.id = id self.partition = partition self.policyDetails = policyDetails self.region = region self.resourcesAffected = resourcesAffected self.sample = sample self.schemaVersion = schemaVersion self.severity = severity self.title = title self.type = type self.updatedAt = updatedAt } private enum CodingKeys: String, CodingKey { case accountId case archived case category case classificationDetails case count case createdAt case description case id case partition case policyDetails case region case resourcesAffected case sample case schemaVersion case severity case title case type case updatedAt } } public struct FindingAction: AWSDecodableShape { public let actionType: FindingActionType? public let apiCallDetails: ApiCallDetails? public init(actionType: FindingActionType? = nil, apiCallDetails: ApiCallDetails? = nil) { self.actionType = actionType self.apiCallDetails = apiCallDetails } private enum CodingKeys: String, CodingKey { case actionType case apiCallDetails } } public struct FindingActor: AWSDecodableShape { public let domainDetails: DomainDetails? public let ipAddressDetails: IpAddressDetails? public let userIdentity: UserIdentity? public init(domainDetails: DomainDetails? = nil, ipAddressDetails: IpAddressDetails? = nil, userIdentity: UserIdentity? = nil) { self.domainDetails = domainDetails self.ipAddressDetails = ipAddressDetails self.userIdentity = userIdentity } private enum CodingKeys: String, CodingKey { case domainDetails case ipAddressDetails case userIdentity } } public struct FindingCriteria: AWSEncodableShape & AWSDecodableShape { public let criterion: [String: CriterionAdditionalProperties]? public init(criterion: [String: CriterionAdditionalProperties]? = nil) { self.criterion = criterion } private enum CodingKeys: String, CodingKey { case criterion } } public struct FindingStatisticsSortCriteria: AWSEncodableShape { public let attributeName: FindingStatisticsSortAttributeName? public let orderBy: OrderBy? public init(attributeName: FindingStatisticsSortAttributeName? = nil, orderBy: OrderBy? = nil) { self.attributeName = attributeName self.orderBy = orderBy } private enum CodingKeys: String, CodingKey { case attributeName case orderBy } } public struct FindingsFilterListItem: AWSDecodableShape { public let action: FindingsFilterAction? public let arn: String? public let id: String? public let name: String? public let tags: [String: String]? public init(action: FindingsFilterAction? = nil, arn: String? = nil, id: String? = nil, name: String? = nil, tags: [String: String]? = nil) { self.action = action self.arn = arn self.id = id self.name = name self.tags = tags } private enum CodingKeys: String, CodingKey { case action case arn case id case name case tags } } public struct GetBucketStatisticsRequest: AWSEncodableShape { public let accountId: String? public init(accountId: String? = nil) { self.accountId = accountId } private enum CodingKeys: String, CodingKey { case accountId } } public struct GetBucketStatisticsResponse: AWSDecodableShape { public let bucketCount: Int64? public let bucketCountByEffectivePermission: BucketCountByEffectivePermission? public let bucketCountByEncryptionType: BucketCountByEncryptionType? public let bucketCountBySharedAccessType: BucketCountBySharedAccessType? public let classifiableObjectCount: Int64? public let classifiableSizeInBytes: Int64? @OptionalCustomCoding<ISO8601DateCoder> public var lastUpdated: Date? public let objectCount: Int64? public let sizeInBytes: Int64? public let sizeInBytesCompressed: Int64? public let unclassifiableObjectCount: ObjectLevelStatistics? public let unclassifiableObjectSizeInBytes: ObjectLevelStatistics? public init(bucketCount: Int64? = nil, bucketCountByEffectivePermission: BucketCountByEffectivePermission? = nil, bucketCountByEncryptionType: BucketCountByEncryptionType? = nil, bucketCountBySharedAccessType: BucketCountBySharedAccessType? = nil, classifiableObjectCount: Int64? = nil, classifiableSizeInBytes: Int64? = nil, lastUpdated: Date? = nil, objectCount: Int64? = nil, sizeInBytes: Int64? = nil, sizeInBytesCompressed: Int64? = nil, unclassifiableObjectCount: ObjectLevelStatistics? = nil, unclassifiableObjectSizeInBytes: ObjectLevelStatistics? = nil) { self.bucketCount = bucketCount self.bucketCountByEffectivePermission = bucketCountByEffectivePermission self.bucketCountByEncryptionType = bucketCountByEncryptionType self.bucketCountBySharedAccessType = bucketCountBySharedAccessType self.classifiableObjectCount = classifiableObjectCount self.classifiableSizeInBytes = classifiableSizeInBytes self.lastUpdated = lastUpdated self.objectCount = objectCount self.sizeInBytes = sizeInBytes self.sizeInBytesCompressed = sizeInBytesCompressed self.unclassifiableObjectCount = unclassifiableObjectCount self.unclassifiableObjectSizeInBytes = unclassifiableObjectSizeInBytes } private enum CodingKeys: String, CodingKey { case bucketCount case bucketCountByEffectivePermission case bucketCountByEncryptionType case bucketCountBySharedAccessType case classifiableObjectCount case classifiableSizeInBytes case lastUpdated case objectCount case sizeInBytes case sizeInBytesCompressed case unclassifiableObjectCount case unclassifiableObjectSizeInBytes } } public struct GetClassificationExportConfigurationRequest: AWSEncodableShape { public init() {} } public struct GetClassificationExportConfigurationResponse: AWSDecodableShape { public let configuration: ClassificationExportConfiguration? public init(configuration: ClassificationExportConfiguration? = nil) { self.configuration = configuration } private enum CodingKeys: String, CodingKey { case configuration } } public struct GetCustomDataIdentifierRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "id", location: .uri(locationName: "id")) ] public let id: String public init(id: String) { self.id = id } private enum CodingKeys: CodingKey {} } public struct GetCustomDataIdentifierResponse: AWSDecodableShape { public let arn: String? @OptionalCustomCoding<ISO8601DateCoder> public var createdAt: Date? public let deleted: Bool? public let description: String? public let id: String? public let ignoreWords: [String]? public let keywords: [String]? public let maximumMatchDistance: Int? public let name: String? public let regex: String? public let tags: [String: String]? public init(arn: String? = nil, createdAt: Date? = nil, deleted: Bool? = nil, description: String? = nil, id: String? = nil, ignoreWords: [String]? = nil, keywords: [String]? = nil, maximumMatchDistance: Int? = nil, name: String? = nil, regex: String? = nil, tags: [String: String]? = nil) { self.arn = arn self.createdAt = createdAt self.deleted = deleted self.description = description self.id = id self.ignoreWords = ignoreWords self.keywords = keywords self.maximumMatchDistance = maximumMatchDistance self.name = name self.regex = regex self.tags = tags } private enum CodingKeys: String, CodingKey { case arn case createdAt case deleted case description case id case ignoreWords case keywords case maximumMatchDistance case name case regex case tags } } public struct GetFindingStatisticsRequest: AWSEncodableShape { public let findingCriteria: FindingCriteria? public let groupBy: GroupBy public let size: Int? public let sortCriteria: FindingStatisticsSortCriteria? public init(findingCriteria: FindingCriteria? = nil, groupBy: GroupBy, size: Int? = nil, sortCriteria: FindingStatisticsSortCriteria? = nil) { self.findingCriteria = findingCriteria self.groupBy = groupBy self.size = size self.sortCriteria = sortCriteria } private enum CodingKeys: String, CodingKey { case findingCriteria case groupBy case size case sortCriteria } } public struct GetFindingStatisticsResponse: AWSDecodableShape { public let countsByGroup: [GroupCount]? public init(countsByGroup: [GroupCount]? = nil) { self.countsByGroup = countsByGroup } private enum CodingKeys: String, CodingKey { case countsByGroup } } public struct GetFindingsFilterRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "id", location: .uri(locationName: "id")) ] public let id: String public init(id: String) { self.id = id } private enum CodingKeys: CodingKey {} } public struct GetFindingsFilterResponse: AWSDecodableShape { public let action: FindingsFilterAction? public let arn: String? public let description: String? public let findingCriteria: FindingCriteria? public let id: String? public let name: String? public let position: Int? public let tags: [String: String]? public init(action: FindingsFilterAction? = nil, arn: String? = nil, description: String? = nil, findingCriteria: FindingCriteria? = nil, id: String? = nil, name: String? = nil, position: Int? = nil, tags: [String: String]? = nil) { self.action = action self.arn = arn self.description = description self.findingCriteria = findingCriteria self.id = id self.name = name self.position = position self.tags = tags } private enum CodingKeys: String, CodingKey { case action case arn case description case findingCriteria case id case name case position case tags } } public struct GetFindingsRequest: AWSEncodableShape { public let findingIds: [String] public let sortCriteria: SortCriteria? public init(findingIds: [String], sortCriteria: SortCriteria? = nil) { self.findingIds = findingIds self.sortCriteria = sortCriteria } private enum CodingKeys: String, CodingKey { case findingIds case sortCriteria } } public struct GetFindingsResponse: AWSDecodableShape { public let findings: [Finding]? public init(findings: [Finding]? = nil) { self.findings = findings } private enum CodingKeys: String, CodingKey { case findings } } public struct GetInvitationsCountRequest: AWSEncodableShape { public init() {} } public struct GetInvitationsCountResponse: AWSDecodableShape { public let invitationsCount: Int64? public init(invitationsCount: Int64? = nil) { self.invitationsCount = invitationsCount } private enum CodingKeys: String, CodingKey { case invitationsCount } } public struct GetMacieSessionRequest: AWSEncodableShape { public init() {} } public struct GetMacieSessionResponse: AWSDecodableShape { @OptionalCustomCoding<ISO8601DateCoder> public var createdAt: Date? public let findingPublishingFrequency: FindingPublishingFrequency? public let serviceRole: String? public let status: MacieStatus? @OptionalCustomCoding<ISO8601DateCoder> public var updatedAt: Date? public init(createdAt: Date? = nil, findingPublishingFrequency: FindingPublishingFrequency? = nil, serviceRole: String? = nil, status: MacieStatus? = nil, updatedAt: Date? = nil) { self.createdAt = createdAt self.findingPublishingFrequency = findingPublishingFrequency self.serviceRole = serviceRole self.status = status self.updatedAt = updatedAt } private enum CodingKeys: String, CodingKey { case createdAt case findingPublishingFrequency case serviceRole case status case updatedAt } } public struct GetMasterAccountRequest: AWSEncodableShape { public init() {} } public struct GetMasterAccountResponse: AWSDecodableShape { public let master: Invitation? public init(master: Invitation? = nil) { self.master = master } private enum CodingKeys: String, CodingKey { case master } } public struct GetMemberRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "id", location: .uri(locationName: "id")) ] public let id: String public init(id: String) { self.id = id } private enum CodingKeys: CodingKey {} } public struct GetMemberResponse: AWSDecodableShape { public let accountId: String? public let arn: String? public let email: String? @OptionalCustomCoding<ISO8601DateCoder> public var invitedAt: Date? public let masterAccountId: String? public let relationshipStatus: RelationshipStatus? public let tags: [String: String]? @OptionalCustomCoding<ISO8601DateCoder> public var updatedAt: Date? public init(accountId: String? = nil, arn: String? = nil, email: String? = nil, invitedAt: Date? = nil, masterAccountId: String? = nil, relationshipStatus: RelationshipStatus? = nil, tags: [String: String]? = nil, updatedAt: Date? = nil) { self.accountId = accountId self.arn = arn self.email = email self.invitedAt = invitedAt self.masterAccountId = masterAccountId self.relationshipStatus = relationshipStatus self.tags = tags self.updatedAt = updatedAt } private enum CodingKeys: String, CodingKey { case accountId case arn case email case invitedAt case masterAccountId case relationshipStatus case tags case updatedAt } } public struct GetUsageStatisticsRequest: AWSEncodableShape { public let filterBy: [UsageStatisticsFilter]? public let maxResults: Int? public let nextToken: String? public let sortBy: UsageStatisticsSortBy? public init(filterBy: [UsageStatisticsFilter]? = nil, maxResults: Int? = nil, nextToken: String? = nil, sortBy: UsageStatisticsSortBy? = nil) { self.filterBy = filterBy self.maxResults = maxResults self.nextToken = nextToken self.sortBy = sortBy } private enum CodingKeys: String, CodingKey { case filterBy case maxResults case nextToken case sortBy } } public struct GetUsageStatisticsResponse: AWSDecodableShape { public let nextToken: String? public let records: [UsageRecord]? public init(nextToken: String? = nil, records: [UsageRecord]? = nil) { self.nextToken = nextToken self.records = records } private enum CodingKeys: String, CodingKey { case nextToken case records } } public struct GetUsageTotalsRequest: AWSEncodableShape { public init() {} } public struct GetUsageTotalsResponse: AWSDecodableShape { public let usageTotals: [UsageTotal]? public init(usageTotals: [UsageTotal]? = nil) { self.usageTotals = usageTotals } private enum CodingKeys: String, CodingKey { case usageTotals } } public struct GroupCount: AWSDecodableShape { public let count: Int64? public let groupKey: String? public init(count: Int64? = nil, groupKey: String? = nil) { self.count = count self.groupKey = groupKey } private enum CodingKeys: String, CodingKey { case count case groupKey } } public struct IamUser: AWSDecodableShape { public let accountId: String? public let arn: String? public let principalId: String? public let userName: String? public init(accountId: String? = nil, arn: String? = nil, principalId: String? = nil, userName: String? = nil) { self.accountId = accountId self.arn = arn self.principalId = principalId self.userName = userName } private enum CodingKeys: String, CodingKey { case accountId case arn case principalId case userName } } public struct Invitation: AWSDecodableShape { public let accountId: String? public let invitationId: String? @OptionalCustomCoding<ISO8601DateCoder> public var invitedAt: Date? public let relationshipStatus: RelationshipStatus? public init(accountId: String? = nil, invitationId: String? = nil, invitedAt: Date? = nil, relationshipStatus: RelationshipStatus? = nil) { self.accountId = accountId self.invitationId = invitationId self.invitedAt = invitedAt self.relationshipStatus = relationshipStatus } private enum CodingKeys: String, CodingKey { case accountId case invitationId case invitedAt case relationshipStatus } } public struct IpAddressDetails: AWSDecodableShape { public let ipAddressV4: String? public let ipCity: IpCity? public let ipCountry: IpCountry? public let ipGeoLocation: IpGeoLocation? public let ipOwner: IpOwner? public init(ipAddressV4: String? = nil, ipCity: IpCity? = nil, ipCountry: IpCountry? = nil, ipGeoLocation: IpGeoLocation? = nil, ipOwner: IpOwner? = nil) { self.ipAddressV4 = ipAddressV4 self.ipCity = ipCity self.ipCountry = ipCountry self.ipGeoLocation = ipGeoLocation self.ipOwner = ipOwner } private enum CodingKeys: String, CodingKey { case ipAddressV4 case ipCity case ipCountry case ipGeoLocation case ipOwner } } public struct IpCity: AWSDecodableShape { public let name: String? public init(name: String? = nil) { self.name = name } private enum CodingKeys: String, CodingKey { case name } } public struct IpCountry: AWSDecodableShape { public let code: String? public let name: String? public init(code: String? = nil, name: String? = nil) { self.code = code self.name = name } private enum CodingKeys: String, CodingKey { case code case name } } public struct IpGeoLocation: AWSDecodableShape { public let lat: Double? public let lon: Double? public init(lat: Double? = nil, lon: Double? = nil) { self.lat = lat self.lon = lon } private enum CodingKeys: String, CodingKey { case lat case lon } } public struct IpOwner: AWSDecodableShape { public let asn: String? public let asnOrg: String? public let isp: String? public let org: String? public init(asn: String? = nil, asnOrg: String? = nil, isp: String? = nil, org: String? = nil) { self.asn = asn self.asnOrg = asnOrg self.isp = isp self.org = org } private enum CodingKeys: String, CodingKey { case asn case asnOrg case isp case org } } public struct JobScheduleFrequency: AWSEncodableShape & AWSDecodableShape { public let dailySchedule: DailySchedule? public let monthlySchedule: MonthlySchedule? public let weeklySchedule: WeeklySchedule? public init(dailySchedule: DailySchedule? = nil, monthlySchedule: MonthlySchedule? = nil, weeklySchedule: WeeklySchedule? = nil) { self.dailySchedule = dailySchedule self.monthlySchedule = monthlySchedule self.weeklySchedule = weeklySchedule } private enum CodingKeys: String, CodingKey { case dailySchedule case monthlySchedule case weeklySchedule } } public struct JobScopeTerm: AWSEncodableShape & AWSDecodableShape { public let simpleScopeTerm: SimpleScopeTerm? public let tagScopeTerm: TagScopeTerm? public init(simpleScopeTerm: SimpleScopeTerm? = nil, tagScopeTerm: TagScopeTerm? = nil) { self.simpleScopeTerm = simpleScopeTerm self.tagScopeTerm = tagScopeTerm } private enum CodingKeys: String, CodingKey { case simpleScopeTerm case tagScopeTerm } } public struct JobScopingBlock: AWSEncodableShape & AWSDecodableShape { public let and: [JobScopeTerm]? public init(and: [JobScopeTerm]? = nil) { self.and = and } private enum CodingKeys: String, CodingKey { case and } } public struct JobSummary: AWSDecodableShape { public let bucketDefinitions: [S3BucketDefinitionForJob]? @OptionalCustomCoding<ISO8601DateCoder> public var createdAt: Date? public let jobId: String? public let jobStatus: JobStatus? public let jobType: JobType? public let name: String? public let userPausedDetails: UserPausedDetails? public init(bucketDefinitions: [S3BucketDefinitionForJob]? = nil, createdAt: Date? = nil, jobId: String? = nil, jobStatus: JobStatus? = nil, jobType: JobType? = nil, name: String? = nil, userPausedDetails: UserPausedDetails? = nil) { self.bucketDefinitions = bucketDefinitions self.createdAt = createdAt self.jobId = jobId self.jobStatus = jobStatus self.jobType = jobType self.name = name self.userPausedDetails = userPausedDetails } private enum CodingKeys: String, CodingKey { case bucketDefinitions case createdAt case jobId case jobStatus case jobType case name case userPausedDetails } } public struct KeyValuePair: AWSDecodableShape { public let key: String? public let value: String? public init(key: String? = nil, value: String? = nil) { self.key = key self.value = value } private enum CodingKeys: String, CodingKey { case key case value } } public struct ListClassificationJobsRequest: AWSEncodableShape { public let filterCriteria: ListJobsFilterCriteria? public let maxResults: Int? public let nextToken: String? public let sortCriteria: ListJobsSortCriteria? public init(filterCriteria: ListJobsFilterCriteria? = nil, maxResults: Int? = nil, nextToken: String? = nil, sortCriteria: ListJobsSortCriteria? = nil) { self.filterCriteria = filterCriteria self.maxResults = maxResults self.nextToken = nextToken self.sortCriteria = sortCriteria } private enum CodingKeys: String, CodingKey { case filterCriteria case maxResults case nextToken case sortCriteria } } public struct ListClassificationJobsResponse: AWSDecodableShape { public let items: [JobSummary]? public let nextToken: String? public init(items: [JobSummary]? = nil, nextToken: String? = nil) { self.items = items self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case items case nextToken } } public struct ListCustomDataIdentifiersRequest: AWSEncodableShape { public let maxResults: Int? public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case maxResults case nextToken } } public struct ListCustomDataIdentifiersResponse: AWSDecodableShape { public let items: [CustomDataIdentifierSummary]? public let nextToken: String? public init(items: [CustomDataIdentifierSummary]? = nil, nextToken: String? = nil) { self.items = items self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case items case nextToken } } public struct ListFindingsFiltersRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")) ] 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: 25) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct ListFindingsFiltersResponse: AWSDecodableShape { public let findingsFilterListItems: [FindingsFilterListItem]? public let nextToken: String? public init(findingsFilterListItems: [FindingsFilterListItem]? = nil, nextToken: String? = nil) { self.findingsFilterListItems = findingsFilterListItems self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case findingsFilterListItems case nextToken } } public struct ListFindingsRequest: AWSEncodableShape { public let findingCriteria: FindingCriteria? public let maxResults: Int? public let nextToken: String? public let sortCriteria: SortCriteria? public init(findingCriteria: FindingCriteria? = nil, maxResults: Int? = nil, nextToken: String? = nil, sortCriteria: SortCriteria? = nil) { self.findingCriteria = findingCriteria self.maxResults = maxResults self.nextToken = nextToken self.sortCriteria = sortCriteria } private enum CodingKeys: String, CodingKey { case findingCriteria case maxResults case nextToken case sortCriteria } } public struct ListFindingsResponse: AWSDecodableShape { public let findingIds: [String]? public let nextToken: String? public init(findingIds: [String]? = nil, nextToken: String? = nil) { self.findingIds = findingIds self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case findingIds case nextToken } } public struct ListInvitationsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")) ] 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: 25) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct ListInvitationsResponse: AWSDecodableShape { public let invitations: [Invitation]? public let nextToken: String? public init(invitations: [Invitation]? = nil, nextToken: String? = nil) { self.invitations = invitations self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case invitations case nextToken } } public struct ListJobsFilterCriteria: AWSEncodableShape { public let excludes: [ListJobsFilterTerm]? public let includes: [ListJobsFilterTerm]? public init(excludes: [ListJobsFilterTerm]? = nil, includes: [ListJobsFilterTerm]? = nil) { self.excludes = excludes self.includes = includes } private enum CodingKeys: String, CodingKey { case excludes case includes } } public struct ListJobsFilterTerm: AWSEncodableShape { public let comparator: JobComparator? public let key: ListJobsFilterKey? public let values: [String]? public init(comparator: JobComparator? = nil, key: ListJobsFilterKey? = nil, values: [String]? = nil) { self.comparator = comparator self.key = key self.values = values } private enum CodingKeys: String, CodingKey { case comparator case key case values } } public struct ListJobsSortCriteria: AWSEncodableShape { public let attributeName: ListJobsSortAttributeName? public let orderBy: OrderBy? public init(attributeName: ListJobsSortAttributeName? = nil, orderBy: OrderBy? = nil) { self.attributeName = attributeName self.orderBy = orderBy } private enum CodingKeys: String, CodingKey { case attributeName case orderBy } } public struct ListMembersRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")), AWSMemberEncoding(label: "onlyAssociated", location: .querystring(locationName: "onlyAssociated")) ] public let maxResults: Int? public let nextToken: String? public let onlyAssociated: String? public init(maxResults: Int? = nil, nextToken: String? = nil, onlyAssociated: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken self.onlyAssociated = onlyAssociated } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 25) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct ListMembersResponse: AWSDecodableShape { public let members: [Member]? public let nextToken: String? public init(members: [Member]? = nil, nextToken: String? = nil) { self.members = members self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case members case nextToken } } public struct ListOrganizationAdminAccountsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")) ] 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: 25) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct ListOrganizationAdminAccountsResponse: AWSDecodableShape { public let adminAccounts: [AdminAccount]? public let nextToken: String? public init(adminAccounts: [AdminAccount]? = nil, nextToken: String? = nil) { self.adminAccounts = adminAccounts self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case adminAccounts case nextToken } } public struct ListTagsForResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resourceArn")) ] public let resourceArn: String public init(resourceArn: String) { self.resourceArn = resourceArn } private enum CodingKeys: CodingKey {} } public struct ListTagsForResourceResponse: AWSDecodableShape { public let tags: [String: String]? public init(tags: [String: String]? = nil) { self.tags = tags } private enum CodingKeys: String, CodingKey { case tags } } public struct Member: AWSDecodableShape { public let accountId: String? public let arn: String? public let email: String? @OptionalCustomCoding<ISO8601DateCoder> public var invitedAt: Date? public let masterAccountId: String? public let relationshipStatus: RelationshipStatus? public let tags: [String: String]? @OptionalCustomCoding<ISO8601DateCoder> public var updatedAt: Date? public init(accountId: String? = nil, arn: String? = nil, email: String? = nil, invitedAt: Date? = nil, masterAccountId: String? = nil, relationshipStatus: RelationshipStatus? = nil, tags: [String: String]? = nil, updatedAt: Date? = nil) { self.accountId = accountId self.arn = arn self.email = email self.invitedAt = invitedAt self.masterAccountId = masterAccountId self.relationshipStatus = relationshipStatus self.tags = tags self.updatedAt = updatedAt } private enum CodingKeys: String, CodingKey { case accountId case arn case email case invitedAt case masterAccountId case relationshipStatus case tags case updatedAt } } public struct MonthlySchedule: AWSEncodableShape & AWSDecodableShape { public let dayOfMonth: Int? public init(dayOfMonth: Int? = nil) { self.dayOfMonth = dayOfMonth } private enum CodingKeys: String, CodingKey { case dayOfMonth } } public struct ObjectCountByEncryptionType: AWSDecodableShape { public let customerManaged: Int64? public let kmsManaged: Int64? public let s3Managed: Int64? public let unencrypted: Int64? public init(customerManaged: Int64? = nil, kmsManaged: Int64? = nil, s3Managed: Int64? = nil, unencrypted: Int64? = nil) { self.customerManaged = customerManaged self.kmsManaged = kmsManaged self.s3Managed = s3Managed self.unencrypted = unencrypted } private enum CodingKeys: String, CodingKey { case customerManaged case kmsManaged case s3Managed case unencrypted } } public struct ObjectLevelStatistics: AWSDecodableShape { public let fileType: Int64? public let storageClass: Int64? public let total: Int64? public init(fileType: Int64? = nil, storageClass: Int64? = nil, total: Int64? = nil) { self.fileType = fileType self.storageClass = storageClass self.total = total } private enum CodingKeys: String, CodingKey { case fileType case storageClass case total } } public struct Occurrences: AWSDecodableShape { public let cells: [Cell]? public let lineRanges: [Range]? public let offsetRanges: [Range]? public let pages: [Page]? public let records: [Record]? public init(cells: [Cell]? = nil, lineRanges: [Range]? = nil, offsetRanges: [Range]? = nil, pages: [Page]? = nil, records: [Record]? = nil) { self.cells = cells self.lineRanges = lineRanges self.offsetRanges = offsetRanges self.pages = pages self.records = records } private enum CodingKeys: String, CodingKey { case cells case lineRanges case offsetRanges case pages case records } } public struct Page: AWSDecodableShape { public let lineRange: Range? public let offsetRange: Range? public let pageNumber: Int64? public init(lineRange: Range? = nil, offsetRange: Range? = nil, pageNumber: Int64? = nil) { self.lineRange = lineRange self.offsetRange = offsetRange self.pageNumber = pageNumber } private enum CodingKeys: String, CodingKey { case lineRange case offsetRange case pageNumber } } public struct PolicyDetails: AWSDecodableShape { public let action: FindingAction? public let actor: FindingActor? public init(action: FindingAction? = nil, actor: FindingActor? = nil) { self.action = action self.actor = actor } private enum CodingKeys: String, CodingKey { case action case actor } } public struct PutClassificationExportConfigurationRequest: AWSEncodableShape { public let configuration: ClassificationExportConfiguration public init(configuration: ClassificationExportConfiguration) { self.configuration = configuration } private enum CodingKeys: String, CodingKey { case configuration } } public struct PutClassificationExportConfigurationResponse: AWSDecodableShape { public let configuration: ClassificationExportConfiguration? public init(configuration: ClassificationExportConfiguration? = nil) { self.configuration = configuration } private enum CodingKeys: String, CodingKey { case configuration } } public struct Range: AWSDecodableShape { public let end: Int64? public let start: Int64? public let startColumn: Int64? public init(end: Int64? = nil, start: Int64? = nil, startColumn: Int64? = nil) { self.end = end self.start = start self.startColumn = startColumn } private enum CodingKeys: String, CodingKey { case end case start case startColumn } } public struct Record: AWSDecodableShape { public let recordIndex: Int64? public init(recordIndex: Int64? = nil) { self.recordIndex = recordIndex } private enum CodingKeys: String, CodingKey { case recordIndex } } public struct ReplicationDetails: AWSDecodableShape { public let replicated: Bool? public let replicatedExternally: Bool? public let replicationAccounts: [String]? public init(replicated: Bool? = nil, replicatedExternally: Bool? = nil, replicationAccounts: [String]? = nil) { self.replicated = replicated self.replicatedExternally = replicatedExternally self.replicationAccounts = replicationAccounts } private enum CodingKeys: String, CodingKey { case replicated case replicatedExternally case replicationAccounts } } public struct ResourcesAffected: AWSDecodableShape { public let s3Bucket: S3Bucket? public let s3Object: S3Object? public init(s3Bucket: S3Bucket? = nil, s3Object: S3Object? = nil) { self.s3Bucket = s3Bucket self.s3Object = s3Object } private enum CodingKeys: String, CodingKey { case s3Bucket case s3Object } } public struct S3Bucket: AWSDecodableShape { public let arn: String? @OptionalCustomCoding<ISO8601DateCoder> public var createdAt: Date? public let defaultServerSideEncryption: ServerSideEncryption? public let name: String? public let owner: S3BucketOwner? public let publicAccess: BucketPublicAccess? public let tags: [KeyValuePair]? public init(arn: String? = nil, createdAt: Date? = nil, defaultServerSideEncryption: ServerSideEncryption? = nil, name: String? = nil, owner: S3BucketOwner? = nil, publicAccess: BucketPublicAccess? = nil, tags: [KeyValuePair]? = nil) { self.arn = arn self.createdAt = createdAt self.defaultServerSideEncryption = defaultServerSideEncryption self.name = name self.owner = owner self.publicAccess = publicAccess self.tags = tags } private enum CodingKeys: String, CodingKey { case arn case createdAt case defaultServerSideEncryption case name case owner case publicAccess case tags } } public struct S3BucketDefinitionForJob: AWSEncodableShape & AWSDecodableShape { public let accountId: String? public let buckets: [String]? public init(accountId: String? = nil, buckets: [String]? = nil) { self.accountId = accountId self.buckets = buckets } private enum CodingKeys: String, CodingKey { case accountId case buckets } } public struct S3BucketOwner: AWSDecodableShape { public let displayName: String? public let id: String? public init(displayName: String? = nil, id: String? = nil) { self.displayName = displayName self.id = id } private enum CodingKeys: String, CodingKey { case displayName case id } } public struct S3Destination: AWSEncodableShape & AWSDecodableShape { public let bucketName: String public let keyPrefix: String? public let kmsKeyArn: String public init(bucketName: String, keyPrefix: String? = nil, kmsKeyArn: String) { self.bucketName = bucketName self.keyPrefix = keyPrefix self.kmsKeyArn = kmsKeyArn } private enum CodingKeys: String, CodingKey { case bucketName case keyPrefix case kmsKeyArn } } public struct S3JobDefinition: AWSEncodableShape & AWSDecodableShape { public let bucketDefinitions: [S3BucketDefinitionForJob]? public let scoping: Scoping? public init(bucketDefinitions: [S3BucketDefinitionForJob]? = nil, scoping: Scoping? = nil) { self.bucketDefinitions = bucketDefinitions self.scoping = scoping } private enum CodingKeys: String, CodingKey { case bucketDefinitions case scoping } } public struct S3Object: AWSDecodableShape { public let bucketArn: String? public let eTag: String? public let `extension`: String? public let key: String? @OptionalCustomCoding<ISO8601DateCoder> public var lastModified: Date? public let path: String? public let publicAccess: Bool? public let serverSideEncryption: ServerSideEncryption? public let size: Int64? public let storageClass: StorageClass? public let tags: [KeyValuePair]? public let versionId: String? public init(bucketArn: String? = nil, eTag: String? = nil, extension: String? = nil, key: String? = nil, lastModified: Date? = nil, path: String? = nil, publicAccess: Bool? = nil, serverSideEncryption: ServerSideEncryption? = nil, size: Int64? = nil, storageClass: StorageClass? = nil, tags: [KeyValuePair]? = nil, versionId: String? = nil) { self.bucketArn = bucketArn self.eTag = eTag self.`extension` = `extension` self.key = key self.lastModified = lastModified self.path = path self.publicAccess = publicAccess self.serverSideEncryption = serverSideEncryption self.size = size self.storageClass = storageClass self.tags = tags self.versionId = versionId } private enum CodingKeys: String, CodingKey { case bucketArn case eTag case `extension` case key case lastModified case path case publicAccess case serverSideEncryption case size case storageClass case tags case versionId } } public struct Scoping: AWSEncodableShape & AWSDecodableShape { public let excludes: JobScopingBlock? public let includes: JobScopingBlock? public init(excludes: JobScopingBlock? = nil, includes: JobScopingBlock? = nil) { self.excludes = excludes self.includes = includes } private enum CodingKeys: String, CodingKey { case excludes case includes } } public struct SensitiveDataItem: AWSDecodableShape { public let category: SensitiveDataItemCategory? public let detections: [DefaultDetection]? public let totalCount: Int64? public init(category: SensitiveDataItemCategory? = nil, detections: [DefaultDetection]? = nil, totalCount: Int64? = nil) { self.category = category self.detections = detections self.totalCount = totalCount } private enum CodingKeys: String, CodingKey { case category case detections case totalCount } } public struct ServerSideEncryption: AWSDecodableShape { public let encryptionType: EncryptionType? public let kmsMasterKeyId: String? public init(encryptionType: EncryptionType? = nil, kmsMasterKeyId: String? = nil) { self.encryptionType = encryptionType self.kmsMasterKeyId = kmsMasterKeyId } private enum CodingKeys: String, CodingKey { case encryptionType case kmsMasterKeyId } } public struct ServiceLimit: AWSDecodableShape { public let isServiceLimited: Bool? public let unit: Unit? public let value: Int64? public init(isServiceLimited: Bool? = nil, unit: Unit? = nil, value: Int64? = nil) { self.isServiceLimited = isServiceLimited self.unit = unit self.value = value } private enum CodingKeys: String, CodingKey { case isServiceLimited case unit case value } } public struct SessionContext: AWSDecodableShape { public let attributes: SessionContextAttributes? public let sessionIssuer: SessionIssuer? public init(attributes: SessionContextAttributes? = nil, sessionIssuer: SessionIssuer? = nil) { self.attributes = attributes self.sessionIssuer = sessionIssuer } private enum CodingKeys: String, CodingKey { case attributes case sessionIssuer } } public struct SessionContextAttributes: AWSDecodableShape { @OptionalCustomCoding<ISO8601DateCoder> public var creationDate: Date? public let mfaAuthenticated: Bool? public init(creationDate: Date? = nil, mfaAuthenticated: Bool? = nil) { self.creationDate = creationDate self.mfaAuthenticated = mfaAuthenticated } private enum CodingKeys: String, CodingKey { case creationDate case mfaAuthenticated } } public struct SessionIssuer: AWSDecodableShape { public let accountId: String? public let arn: String? public let principalId: String? public let type: String? public let userName: String? public init(accountId: String? = nil, arn: String? = nil, principalId: String? = nil, type: String? = nil, userName: String? = nil) { self.accountId = accountId self.arn = arn self.principalId = principalId self.type = type self.userName = userName } private enum CodingKeys: String, CodingKey { case accountId case arn case principalId case type case userName } } public struct Severity: AWSDecodableShape { public let description: SeverityDescription? public let score: Int64? public init(description: SeverityDescription? = nil, score: Int64? = nil) { self.description = description self.score = score } private enum CodingKeys: String, CodingKey { case description case score } } public struct SimpleScopeTerm: AWSEncodableShape & AWSDecodableShape { public let comparator: JobComparator? public let key: ScopeFilterKey? public let values: [String]? public init(comparator: JobComparator? = nil, key: ScopeFilterKey? = nil, values: [String]? = nil) { self.comparator = comparator self.key = key self.values = values } private enum CodingKeys: String, CodingKey { case comparator case key case values } } public struct SortCriteria: AWSEncodableShape { public let attributeName: String? public let orderBy: OrderBy? public init(attributeName: String? = nil, orderBy: OrderBy? = nil) { self.attributeName = attributeName self.orderBy = orderBy } private enum CodingKeys: String, CodingKey { case attributeName case orderBy } } public struct Statistics: AWSDecodableShape { public let approximateNumberOfObjectsToProcess: Double? public let numberOfRuns: Double? public init(approximateNumberOfObjectsToProcess: Double? = nil, numberOfRuns: Double? = nil) { self.approximateNumberOfObjectsToProcess = approximateNumberOfObjectsToProcess self.numberOfRuns = numberOfRuns } private enum CodingKeys: String, CodingKey { case approximateNumberOfObjectsToProcess case numberOfRuns } } public struct TagResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resourceArn")) ] public let resourceArn: String public let tags: [String: String] public init(resourceArn: String, tags: [String: String]) { self.resourceArn = resourceArn self.tags = tags } private enum CodingKeys: String, CodingKey { case tags } } public struct TagResourceResponse: AWSDecodableShape { public init() {} } public struct TagScopeTerm: AWSEncodableShape & AWSDecodableShape { public let comparator: JobComparator? public let key: String? public let tagValues: [TagValuePair]? public let target: TagTarget? public init(comparator: JobComparator? = nil, key: String? = nil, tagValues: [TagValuePair]? = nil, target: TagTarget? = nil) { self.comparator = comparator self.key = key self.tagValues = tagValues self.target = target } private enum CodingKeys: String, CodingKey { case comparator case key case tagValues case target } } public struct TagValuePair: AWSEncodableShape & AWSDecodableShape { public let key: String? public let value: String? public init(key: String? = nil, value: String? = nil) { self.key = key self.value = value } private enum CodingKeys: String, CodingKey { case key case value } } public struct TestCustomDataIdentifierRequest: AWSEncodableShape { public let ignoreWords: [String]? public let keywords: [String]? public let maximumMatchDistance: Int? public let regex: String public let sampleText: String public init(ignoreWords: [String]? = nil, keywords: [String]? = nil, maximumMatchDistance: Int? = nil, regex: String, sampleText: String) { self.ignoreWords = ignoreWords self.keywords = keywords self.maximumMatchDistance = maximumMatchDistance self.regex = regex self.sampleText = sampleText } private enum CodingKeys: String, CodingKey { case ignoreWords case keywords case maximumMatchDistance case regex case sampleText } } public struct TestCustomDataIdentifierResponse: AWSDecodableShape { public let matchCount: Int? public init(matchCount: Int? = nil) { self.matchCount = matchCount } private enum CodingKeys: String, CodingKey { case matchCount } } public struct UnprocessedAccount: AWSDecodableShape { public let accountId: String? public let errorCode: ErrorCode? public let errorMessage: String? public init(accountId: String? = nil, errorCode: ErrorCode? = nil, errorMessage: String? = nil) { self.accountId = accountId self.errorCode = errorCode self.errorMessage = errorMessage } private enum CodingKeys: String, CodingKey { case accountId case errorCode case errorMessage } } public struct UntagResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resourceArn")), AWSMemberEncoding(label: "tagKeys", location: .querystring(locationName: "tagKeys")) ] public let resourceArn: String public let tagKeys: [String] public init(resourceArn: String, tagKeys: [String]) { self.resourceArn = resourceArn self.tagKeys = tagKeys } private enum CodingKeys: CodingKey {} } public struct UntagResourceResponse: AWSDecodableShape { public init() {} } public struct UpdateClassificationJobRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "jobId", location: .uri(locationName: "jobId")) ] public let jobId: String public let jobStatus: JobStatus public init(jobId: String, jobStatus: JobStatus) { self.jobId = jobId self.jobStatus = jobStatus } private enum CodingKeys: String, CodingKey { case jobStatus } } public struct UpdateClassificationJobResponse: AWSDecodableShape { public init() {} } public struct UpdateFindingsFilterRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "id", location: .uri(locationName: "id")) ] public let action: FindingsFilterAction? public let description: String? public let findingCriteria: FindingCriteria? public let id: String public let name: String? public let position: Int? public init(action: FindingsFilterAction? = nil, description: String? = nil, findingCriteria: FindingCriteria? = nil, id: String, name: String? = nil, position: Int? = nil) { self.action = action self.description = description self.findingCriteria = findingCriteria self.id = id self.name = name self.position = position } private enum CodingKeys: String, CodingKey { case action case description case findingCriteria case name case position } } public struct UpdateFindingsFilterResponse: AWSDecodableShape { public let arn: String? public let id: String? public init(arn: String? = nil, id: String? = nil) { self.arn = arn self.id = id } private enum CodingKeys: String, CodingKey { case arn case id } } public struct UpdateMacieSessionRequest: AWSEncodableShape { public let findingPublishingFrequency: FindingPublishingFrequency? public let status: MacieStatus? public init(findingPublishingFrequency: FindingPublishingFrequency? = nil, status: MacieStatus? = nil) { self.findingPublishingFrequency = findingPublishingFrequency self.status = status } private enum CodingKeys: String, CodingKey { case findingPublishingFrequency case status } } public struct UpdateMacieSessionResponse: AWSDecodableShape { public init() {} } public struct UpdateMemberSessionRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "id", location: .uri(locationName: "id")) ] public let id: String public let status: MacieStatus public init(id: String, status: MacieStatus) { self.id = id self.status = status } private enum CodingKeys: String, CodingKey { case status } } public struct UpdateMemberSessionResponse: AWSDecodableShape { public init() {} } public struct UpdateOrganizationConfigurationRequest: AWSEncodableShape { public let autoEnable: Bool public init(autoEnable: Bool) { self.autoEnable = autoEnable } private enum CodingKeys: String, CodingKey { case autoEnable } } public struct UpdateOrganizationConfigurationResponse: AWSDecodableShape { public init() {} } public struct UsageByAccount: AWSDecodableShape { public let currency: Currency? public let estimatedCost: String? public let serviceLimit: ServiceLimit? public let type: UsageType? public init(currency: Currency? = nil, estimatedCost: String? = nil, serviceLimit: ServiceLimit? = nil, type: UsageType? = nil) { self.currency = currency self.estimatedCost = estimatedCost self.serviceLimit = serviceLimit self.type = type } private enum CodingKeys: String, CodingKey { case currency case estimatedCost case serviceLimit case type } } public struct UsageRecord: AWSDecodableShape { public let accountId: String? @OptionalCustomCoding<ISO8601DateCoder> public var freeTrialStartDate: Date? public let usage: [UsageByAccount]? public init(accountId: String? = nil, freeTrialStartDate: Date? = nil, usage: [UsageByAccount]? = nil) { self.accountId = accountId self.freeTrialStartDate = freeTrialStartDate self.usage = usage } private enum CodingKeys: String, CodingKey { case accountId case freeTrialStartDate case usage } } public struct UsageStatisticsFilter: AWSEncodableShape { public let comparator: UsageStatisticsFilterComparator? public let key: UsageStatisticsFilterKey? public let values: [String]? public init(comparator: UsageStatisticsFilterComparator? = nil, key: UsageStatisticsFilterKey? = nil, values: [String]? = nil) { self.comparator = comparator self.key = key self.values = values } private enum CodingKeys: String, CodingKey { case comparator case key case values } } public struct UsageStatisticsSortBy: AWSEncodableShape { public let key: UsageStatisticsSortKey? public let orderBy: OrderBy? public init(key: UsageStatisticsSortKey? = nil, orderBy: OrderBy? = nil) { self.key = key self.orderBy = orderBy } private enum CodingKeys: String, CodingKey { case key case orderBy } } public struct UsageTotal: AWSDecodableShape { public let currency: Currency? public let estimatedCost: String? public let type: UsageType? public init(currency: Currency? = nil, estimatedCost: String? = nil, type: UsageType? = nil) { self.currency = currency self.estimatedCost = estimatedCost self.type = type } private enum CodingKeys: String, CodingKey { case currency case estimatedCost case type } } public struct UserIdentity: AWSDecodableShape { public let assumedRole: AssumedRole? public let awsAccount: AwsAccount? public let awsService: AwsService? public let federatedUser: FederatedUser? public let iamUser: IamUser? public let root: UserIdentityRoot? public let type: UserIdentityType? public init(assumedRole: AssumedRole? = nil, awsAccount: AwsAccount? = nil, awsService: AwsService? = nil, federatedUser: FederatedUser? = nil, iamUser: IamUser? = nil, root: UserIdentityRoot? = nil, type: UserIdentityType? = nil) { self.assumedRole = assumedRole self.awsAccount = awsAccount self.awsService = awsService self.federatedUser = federatedUser self.iamUser = iamUser self.root = root self.type = type } private enum CodingKeys: String, CodingKey { case assumedRole case awsAccount case awsService case federatedUser case iamUser case root case type } } public struct UserIdentityRoot: AWSDecodableShape { public let accountId: String? public let arn: String? public let principalId: String? public init(accountId: String? = nil, arn: String? = nil, principalId: String? = nil) { self.accountId = accountId self.arn = arn self.principalId = principalId } private enum CodingKeys: String, CodingKey { case accountId case arn case principalId } } public struct UserPausedDetails: AWSDecodableShape { @OptionalCustomCoding<ISO8601DateCoder> public var jobExpiresAt: Date? public let jobImminentExpirationHealthEventArn: String? @OptionalCustomCoding<ISO8601DateCoder> public var jobPausedAt: Date? public init(jobExpiresAt: Date? = nil, jobImminentExpirationHealthEventArn: String? = nil, jobPausedAt: Date? = nil) { self.jobExpiresAt = jobExpiresAt self.jobImminentExpirationHealthEventArn = jobImminentExpirationHealthEventArn self.jobPausedAt = jobPausedAt } private enum CodingKeys: String, CodingKey { case jobExpiresAt case jobImminentExpirationHealthEventArn case jobPausedAt } } public struct WeeklySchedule: AWSEncodableShape & AWSDecodableShape { public let dayOfWeek: DayOfWeek? public init(dayOfWeek: DayOfWeek? = nil) { self.dayOfWeek = dayOfWeek } private enum CodingKeys: String, CodingKey { case dayOfWeek } } }
apache-2.0
6788662647dc92af8b2e03235033c1ce
32.698842
710
0.619951
5.569625
false
false
false
false
cp3hnu/CPImageViewer
CPImageViewer/ViewController.swift
1
2841
// // ViewController.swift // ImageViewer // // Created by ZhaoWei on 16/2/23. // Copyright © 2016年 cp3hnu. All rights reserved. // import UIKit class ViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. title = "CPImageViewer Demo" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! switch indexPath.row { case 0: cell.textLabel?.text = "General" case 1: cell.textLabel?.text = "TableView" case 2: cell.textLabel?.text = "CollectionVC" case 3: cell.textLabel?.text = "CollectionView" default: break } return cell } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "Present" default: return "Navigation" } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var isPresented = false if indexPath.section == 0 { isPresented = true } let storyboard = UIStoryboard(name: "Main", bundle: nil) var controller: UIViewController if indexPath.row == 0 { controller = storyboard.instantiateViewController(withIdentifier: "GeneralVC") (controller as! GeneralViewController).isPresented = isPresented } else if indexPath.row == 1 { controller = storyboard.instantiateViewController(withIdentifier: "TableVC") (controller as! TableViewController).isPresented = isPresented } else if indexPath.row == 2 { controller = storyboard.instantiateViewController(withIdentifier: "CollectionVC") (controller as! CollectionViewController).isPresented = isPresented } else { controller = storyboard.instantiateViewController(withIdentifier: "CollectionView") (controller as! CollectionVC).isPresented = isPresented } navigationController?.pushViewController(controller, animated: true) } }
mit
9c0fd41f78aa34fa0a95fb3939839c16
30.88764
109
0.616279
5.664671
false
false
false
false
IamAlchemist/Animations
Animations/PullToRefreshViewController.swift
2
4663
// // PullToRefreshViewController.swift // DemoAnimations // // still interesting animation speed = 0 // more cashapelayer with cgpath and strokeEnd // // Created by wizard lee on 7/17/16. // Copyright © 2016 Alchemist. All rights reserved. // import UIKit import SnapKit class PullToRefreshViewController: UICollectionViewController { var isLoading = false var primes = [Int]() override func viewDidLoad() { super.viewDidLoad() isLoading = false setupLoadingIndicator() } var loadingIndicator : UIView! lazy var textShapeLayer : CAShapeLayer = { let letters = CGPathCreateMutable() let font = CTFontCreateWithName("Helvetica" as NSString, 50, nil) let attrs = [NSFontAttributeName : font] let attrString = NSAttributedString(string: "Loading", attributes: attrs) let line = CTLineCreateWithAttributedString(attrString) let runArray = ((CTLineGetGlyphRuns(line) as [AnyObject]) as! [CTRunRef]) for index in 0..<CFArrayGetCount(runArray) { let run = runArray[index] for runGlyphIndex in 0..<CTRunGetGlyphCount(run) { let thisGlyphRange = CFRangeMake(runGlyphIndex, 1) var glyph = CGGlyph() var position = CGPoint() CTRunGetGlyphs(run, thisGlyphRange, &glyph) CTRunGetPositions(run, thisGlyphRange, &position) let letter = CTFontCreatePathForGlyph(font, glyph, nil) var t = CGAffineTransformMakeTranslation(position.x, position.y); CGPathAddPath(letters, &t, letter) } } let path = UIBezierPath() path.moveToPoint(CGPointZero) path.appendPath(UIBezierPath(CGPath: letters)) let pathLayer = CAShapeLayer() pathLayer.bounds = CGPathGetBoundingBox(path.CGPath) pathLayer.geometryFlipped = true pathLayer.path = path.CGPath pathLayer.strokeColor = UIColor.blackColor().CGColor pathLayer.fillColor = nil pathLayer.lineWidth = 1 pathLayer.lineJoin = kCALineJoinBevel return pathLayer }() private func setupLoadingIndicator() { loadingIndicator = UIView(frame: CGRect(x: 0, y: -45, width: 230, height: 70)) collectionView?.addSubview(loadingIndicator) loadingIndicator.snp_makeConstraints { (make) in make.width.equalTo(230) make.height.equalTo(70) make.centerX.equalTo(collectionView!) make.top.equalTo(collectionView!).offset(-70) } textShapeLayer.frame = loadingIndicator.bounds textShapeLayer.speed = 0 textShapeLayer.strokeEnd = 0 loadingIndicator.layer.addSublayer(textShapeLayer) let writeText = CABasicAnimation(keyPath: "strokeEnd") writeText.fromValue = NSNumber(float:0) writeText.toValue = NSNumber(float:1) writeText.fillMode = kCAFillModeForwards // writeText.removedOnCompletion = false textShapeLayer.addAnimation(writeText, forKey: nil) } } extension PullToRefreshViewController { override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return primes.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PullToRefreshCell", forIndexPath: indexPath) as! PullToRefreshCell cell.label.text = "\(primes[indexPath.row])" return cell } } extension PullToRefreshViewController { override func scrollViewDidScroll(scrollView: UIScrollView) { let offset = scrollView.contentOffset.y + scrollView.contentInset.top if offset <= 0 && !isLoading && isViewLoaded() { let threshold : CGFloat = 300 let fraction = -offset/threshold textShapeLayer.timeOffset = min(1.0, Double(fraction)) print("time off set : \(textShapeLayer.timeOffset)") if (fraction >= 1.0) { // startLoading() } } } }
mit
d57b2d411b3fed125ba0ced0a3d762ec
25.191011
140
0.613256
5.657767
false
false
false
false
yrchen/edx-app-ios
Source/UserProfileEditViewController.swift
1
15588
// // UserProfileEditViewController.swift // edX // // Created by Michael Katz on 9/28/15. // Copyright © 2015 edX. All rights reserved. // import UIKit let MiB = 1_048_576 extension UserProfile : FormData { func valueForField(key: String) -> String? { guard let field = ProfileFields(rawValue: key) else { return nil } switch field { case .YearOfBirth: return birthYear.flatMap{ String($0) } case .LanguagePreferences: return languageCode case .Country: return countryCode case .Bio: return bio case .AccountPrivacy: return accountPrivacy?.rawValue default: return nil } } func displayValueForKey(key: String) -> String? { guard let field = ProfileFields(rawValue: key) else { return nil } switch field { case .YearOfBirth: return birthYear.flatMap{ String($0) } case .LanguagePreferences: return language case .Country: return country case .Bio: return bio default: return nil } } func setValue(value: String?, key: String) { guard let field = ProfileFields(rawValue: key) else { return } switch field { case .YearOfBirth: let newValue = value.flatMap { Int($0) } if newValue != birthYear { updateDictionary[key] = newValue ?? NSNull() } birthYear = newValue case .LanguagePreferences: let changed = value != languageCode languageCode = value if changed { updateDictionary[key] = preferredLanguages ?? NSNull() } case .Country: if value != countryCode { updateDictionary[key] = value ?? NSNull() } countryCode = value case .Bio: if value != bio { updateDictionary[key] = value ?? NSNull() } bio = value case .AccountPrivacy: setLimitedProfile(NSString(string: value!).boolValue) default: break } } } class UserProfileEditViewController: UITableViewController { struct Environment { let networkManager: NetworkManager let userProfileManager: UserProfileManager init(networkManager: NetworkManager, userProfileManager: UserProfileManager) { self.networkManager = networkManager self.userProfileManager = userProfileManager } } var profile: UserProfile let environment: Environment var disabledFields = [String]() var imagePicker: ProfilePictureTaker? var banner: ProfileBanner! init(profile: UserProfile, environment: Environment) { self.profile = profile self.environment = environment super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var fields: [JSONFormBuilder.Field] = [] private let toast = ErrorToastView() private let headerHeight: CGFloat = 50 private let spinner = SpinnerView(size: SpinnerView.Size.Large, color: SpinnerView.Color.Primary) private func makeHeader() -> UIView { banner = ProfileBanner(editable: true) { [weak self] in self?.imagePicker = ProfilePictureTaker(delegate: self!) self?.imagePicker?.start(self!.profile.hasProfileImage) } banner.shortProfView.borderColor = OEXStyles.sharedStyles().neutralLight() banner.backgroundColor = tableView.backgroundColor let networkManager = environment.networkManager banner.showProfile(profile, networkManager: networkManager) let bannerWrapper = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: headerHeight)) bannerWrapper.addSubview(banner) bannerWrapper.addSubview(toast) toast.snp_makeConstraints { (make) -> Void in make.top.equalTo(bannerWrapper) make.trailing.equalTo(bannerWrapper) make.leading.equalTo(bannerWrapper) make.height.equalTo(0) } banner.snp_makeConstraints { (make) -> Void in make.trailing.equalTo(bannerWrapper) make.leading.equalTo(bannerWrapper) make.bottom.equalTo(bannerWrapper) make.top.equalTo(toast.snp_bottom) } let bottomLine = UIView() bottomLine.backgroundColor = OEXStyles.sharedStyles().neutralLight() bannerWrapper.addSubview(bottomLine) bottomLine.snp_makeConstraints { (make) -> Void in make.left.equalTo(bannerWrapper) make.right.equalTo(bannerWrapper) make.height.equalTo(1) make.bottom.equalTo(bannerWrapper) } return bannerWrapper } override func viewDidLoad() { super.viewDidLoad() title = Strings.Profile.editTitle tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 44 tableView.tableHeaderView = makeHeader() tableView.tableFooterView = UIView() //get rid of extra lines when the content is shorter than a screen if let form = JSONFormBuilder(jsonFile: "profiles") { JSONFormBuilder.registerCells(tableView) fields = form.fields! } } private func updateProfile() { if profile.hasUpdates { let fieldName = profile.updateDictionary.first!.0 let field = fields.filter{$0.name == fieldName}[0] let fieldDescription = field.title! view.addSubview(spinner) spinner.snp_makeConstraints { (make) -> Void in make.center.equalTo(view) } environment.userProfileManager.updateCurrentUserProfile(profile) {[weak self] result in self?.spinner.removeFromSuperview() if let newProf = result.value { self?.profile = newProf self?.reloadViews() } else { let message = Strings.Profile.unableToSend(fieldName: fieldDescription) self?.showToast(message) } } } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) hideToast() updateProfile() reloadViews() } func reloadViews() { disableLimitedProfileCells(profile.sharingLimitedProfile) self.tableView.reloadData() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fields.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let field = fields[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(field.cellIdentifier, forIndexPath: indexPath) cell.selectionStyle = UITableViewCellSelectionStyle.None guard let formCell = cell as? FormCell else { return cell } formCell.applyData(field, data: profile) guard let segmentCell = formCell as? JSONFormBuilder.SegmentCell else { return cell } //if it's a segmentCell add the callback directly to the control. When we add other types of controls, this should be made more re-usable //remove actions before adding so there's not a ton of actions segmentCell.typeControl.oex_removeAllActions() segmentCell.typeControl.oex_addAction({ [weak self] sender in let control = sender as! UISegmentedControl let limitedProfile = control.selectedSegmentIndex == 1 let newValue = String(limitedProfile) self?.profile.setValue(newValue, key: field.name) self?.updateProfile() self?.disableLimitedProfileCells(limitedProfile) self?.tableView.reloadData() }, forEvents: .ValueChanged) if let under13 = profile.parentalConsent where under13 == true { let descriptionStyle = OEXMutableTextStyle(weight: .Light, size: .XSmall, color: OEXStyles.sharedStyles().neutralDark()) segmentCell.descriptionLabel.attributedText = descriptionStyle.attributedStringWithText(Strings.Profile.under13.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet())) } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let field = fields[indexPath.row] field.takeAction(profile, controller: self) } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { let field = fields[indexPath.row] let enabled = !disabledFields.contains(field.name) cell.userInteractionEnabled = enabled cell.backgroundColor = enabled ? UIColor.clearColor() : OEXStyles.sharedStyles().neutralXLight() } private func disableLimitedProfileCells(disabled: Bool) { banner.changeButton.enabled = true if disabled { disabledFields = [UserProfile.ProfileFields.Country.rawValue, UserProfile.ProfileFields.LanguagePreferences.rawValue, UserProfile.ProfileFields.Bio.rawValue] if profile.parentalConsent ?? false { //If the user needs parental consent, they can only share a limited profile, so disable this field as well */ disabledFields.append(UserProfile.ProfileFields.AccountPrivacy.rawValue) banner.changeButton.enabled = false } } else { disabledFields.removeAll() } } //MARK: - Update the toast view private func showToast(message: String) { toast.setMessage(message) setToastHeight(50) } private func hideToast() { setToastHeight(0) } private func setToastHeight(toastHeight: CGFloat) { toast.hidden = toastHeight <= 1 toast.snp_updateConstraints(closure: { (make) -> Void in make.height.equalTo(toastHeight) }) var headerFrame = self.tableView.tableHeaderView!.frame headerFrame.size.height = headerHeight + toastHeight self.tableView.tableHeaderView!.frame = headerFrame self.tableView.tableHeaderView = self.tableView.tableHeaderView } } /** Error Toast */ private class ErrorToastView : UIView { let errorLabel = UILabel() let messageLabel = UILabel() init() { super.init(frame: CGRectZero) backgroundColor = OEXStyles.sharedStyles().neutralXLight() addSubview(errorLabel) addSubview(messageLabel) errorLabel.backgroundColor = OEXStyles.sharedStyles().errorBase() let errorStyle = OEXMutableTextStyle(weight: .Light, size: .XXLarge, color: OEXStyles.sharedStyles().neutralWhiteT()) errorStyle.alignment = .Center errorLabel.attributedText = Icon.Warning.attributedTextWithStyle(errorStyle) errorLabel.textAlignment = .Center messageLabel.adjustsFontSizeToFitWidth = true errorLabel.snp_makeConstraints { (make) -> Void in make.leading.equalTo(self) make.height.equalTo(self) make.width.equalTo(errorLabel.snp_height) } messageLabel.snp_makeConstraints { (make) -> Void in make.leading.equalTo(errorLabel.snp_trailing).offset(10) make.trailing.equalTo(self).offset(-10) make.centerY.equalTo(self.snp_centerY) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setMessage(message: String) { let messageStyle = OEXTextStyle(weight: .Normal, size: .Base, color: OEXStyles.sharedStyles().neutralBlackT()) messageLabel.attributedText = messageStyle.attributedStringWithText(message) } } extension UserProfileEditViewController : ProfilePictureTakerDelegate { func showImagePickerController(picker: UIImagePickerController) { self.presentViewController(picker, animated: true, completion: nil) } func showChooserAlert(alert: UIAlertController) { self.presentViewController(alert, animated: true, completion: nil) } func deleteImage() { let endBlurimate = banner.shortProfView.blurimate() let networkRequest = ProfileAPI.deleteProfilePhotoRequest(profile.username!) environment.networkManager.taskForRequest(networkRequest) { result in if let _ = result.error { endBlurimate.remove() self.showToast(Strings.Profile.unableToRemovePhoto) } else { //Was sucessful upload self.reloadProfileFromImageChange(endBlurimate) } } } func imagePicked(image: UIImage, picker: UIImagePickerController) { self.dismissViewControllerAnimated(true, completion: nil) let resizedImage = image.resizedTo(CGSize(width: 500, height: 500)) var quality: CGFloat = 1.0 var data = UIImageJPEGRepresentation(resizedImage, quality)! while data.length > MiB && quality > 0 { quality -= 0.1 data = UIImageJPEGRepresentation(resizedImage, quality)! } banner.shortProfView.image = image let endBlurimate = banner.shortProfView.blurimate() let networkRequest = ProfileAPI.uploadProfilePhotoRequest(profile.username!, imageData: data) environment.networkManager.taskForRequest(networkRequest) { result in let anaylticsSource = picker.sourceType == .Camera ? AnaylticsPhotoSource.Camera : AnaylticsPhotoSource.PhotoLibrary OEXAnalytics.sharedAnalytics().trackSetProfilePhoto(anaylticsSource) if let _ = result.error { endBlurimate.remove() self.showToast(Strings.Profile.unableToSetPhoto) } else { //Was sucessful delete self.reloadProfileFromImageChange(endBlurimate) } } } func cancelPicker(picker: UIImagePickerController) { self.dismissViewControllerAnimated(true, completion: nil) } private func reloadProfileFromImageChange(completionRemovable: Removable) { let feed = self.environment.userProfileManager.feedForCurrentUser() feed.refresh() feed.output.listenOnce(self, fireIfAlreadyLoaded: false) { result in completionRemovable.remove() if let newProf = result.value { self.profile = newProf self.reloadViews() self.banner.showProfile(newProf, networkManager: self.environment.networkManager) } else { self.showToast(Strings.Profile.unableToGet) } } } }
apache-2.0
b637ea9dc6bf0199ee7095336b2f5239
35.591549
193
0.623468
5.471042
false
false
false
false
kaideyi/KDYSample
LeetCode/LeetCode/7_ReverseInteger.swift
1
516
// // 7_ReverseInteger.swift // LeetCode // // Created by Mac on 2018/4/16. // Copyright © 2018年 Mac. All rights reserved. // import Foundation class ReverseInteger { func reverse(_ x: Int) -> Int { var result = 0 var x = x while x != 0 { result = x % 10 + result * 10 x /= 10 if result > Int(Int32.max) || result < Int(Int32.min) { return 0 } } return result } }
mit
eeb231f54d8b7f9dfa2fcf85ff4fb80c
18
67
0.454191
3.886364
false
false
false
false
zisko/swift
test/decl/init/resilience.swift
1
2858
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../../Inputs/resilient_protocol.swift // RUN: %target-swift-frontend -typecheck -swift-version 4 -verify -I %t %s // RUN: %target-swift-frontend -typecheck -swift-version 4 -verify -enable-resilience -I %t %s // RUN: %target-swift-frontend -typecheck -swift-version 5 -verify -I %t %s // RUN: %target-swift-frontend -typecheck -swift-version 5 -verify -enable-resilience -I %t %s import resilient_struct import resilient_protocol // Size is not @_fixed_layout, so we cannot define a new designated initializer extension Size { init(ww: Int, hh: Int) { self.w = ww self.h = hh // expected-error {{'let' property 'h' may not be initialized directly; use "self.init(...)" or "self = ..." instead}} } // This is OK init(www: Int, hhh: Int) { self.init(w: www, h: hhh) } // This is OK init(other: Size) { self = other } } // Animal is not @_fixed_layout, so we cannot define an @_inlineable // designated initializer public struct Animal { public let name: String // expected-note 3 {{declared here}} @_inlineable public init(name: String) { self.name = name // expected-error {{'let' property 'name' may not be initialized directly; use "self.init(...)" or "self = ..." instead}} } @inline(__always) public init(dog: String) { self.name = dog // expected-error {{'let' property 'name' may not be initialized directly; use "self.init(...)" or "self = ..." instead}} } @_transparent public init(cat: String) { self.name = cat // expected-error {{'let' property 'name' may not be initialized directly; use "self.init(...)" or "self = ..." instead}} } // This is OK @_inlineable public init(cow: String) { self.init(name: cow) } // This is OK @_inlineable public init(other: Animal) { self = other } } public class Widget { public let name: String public init(nonInlinableName name: String) { self.name = name } @_inlineable public init(name: String) { // expected-error@-1 {{initializer for class 'Widget' is '@_inlineable' and must delegate to another initializer}} self.name = name } @_inlineable public convenience init(goodName name: String) { // This is OK self.init(nonInlinableName: name) } } public protocol Gadget { init() } extension Gadget { @_inlineable public init(unused: Int) { // This is OK self.init() } } // Protocol extension initializers are OK too extension OtherResilientProtocol { public init(other: Self) { self = other } }
apache-2.0
838f813513adfc71124f8d230f87b0e2
29.084211
187
0.669699
3.604035
false
false
false
false
shitoudev/v2ex
v2exKit/STView.swift
2
1348
// // STView.swift // v2ex // // Created by zhenwen on 6/7/15. // Copyright (c) 2015 zhenwen. All rights reserved. // import UIKit extension UIView { public var left: CGFloat { get { return self.frame.origin.x } set { var frame = self.frame frame.origin.x = newValue self.frame = frame } } public var right: CGFloat { return self.left + self.width } public var top: CGFloat { return self.frame.origin.y } public var bottom: CGFloat { return self.top + self.height } public var width: CGFloat { return self.frame.size.width } public var height: CGFloat { return self.frame.size.height } public func traverseResponderChainForUIViewController() -> UIViewController? { if let nextResponder = self.nextResponder() { if nextResponder.isKindOfClass(UIViewController) { return (nextResponder as! UIViewController) }else if (nextResponder.isKindOfClass(UIView)){ let view = nextResponder as! UIView return view.traverseResponderChainForUIViewController() }else{ return nil } }else{ return nil } } }
mit
fab421776bce11733525713714657263
23.089286
82
0.554896
4.780142
false
false
false
false
silence0201/Swift-Study
SwiftLearn/MySwift11_class.playground/Sources/UI2.swift
1
1163
import UIKit enum Theme2{ case DayMode case NightMode } class UI2{ private var fontColor: UIColor! private var backgroundColor: UIColor! internal var themeMode: Theme2 = .DayMode{ //计算型属性 didSet{ self.changeTheme(themeMode: self.themeMode) } } init(){ self.themeMode = .DayMode self.changeTheme(themeMode: self.themeMode) } private func changeTheme(themeMode: Theme2){ switch(themeMode){ case .DayMode: fontColor = UIColor.black backgroundColor = UIColor.white case .NightMode: fontColor = UIColor.white backgroundColor = UIColor.black } } func show(){ print("The font color is \(fontColor == UIColor.white ? "WHITE" : "BLACK" )") print("The background color is \(backgroundColor == UIColor.white ? "WHITE" : "BLACK")") } } //Sources目录中只能定义, 不能执行语句. //let ui2 = UI2() //ui2.fontColor //ui2.backgroundColor //ui2.changeTheme(.NightMode) //Swift是以文件为单位的, 所以在本文件中可以访问private的方法.
mit
b8073bf7cee9f92934725bc4c8b8ccb8
23.613636
96
0.610342
4.117871
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/HCILERemoteConnectionParameterRequest.swift
1
2192
// // HCILERemoteConnectionParameterRequest.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// LE Remote Connection Parameter Request Event /// /// This event indicates to the master’s Host or the slave’s Host that the remote device is requesting /// a change in the connection parameters. The Host replies either with the HCI LE Remote Connection /// Parameter Request Reply command or the HCI LE Remote Connection Parameter Request Negative /// Reply command. @frozen public struct HCILERemoteConnectionParameterRequest: HCIEventParameter { public static let event = LowEnergyEvent.remoteConnectionParameterRequest // 0x06 public static let length: Int = 10 public let handle: UInt16 // Connection_Handle public let interval: LowEnergyConnectionIntervalRange public let connLatency: LowEnergyConnectionLatency public let supervisionTimeout: LowEnergySupervisionTimeout public init?(data: Data) { guard data.count == type(of: self).length else { return nil } let handle = UInt16(littleEndian: UInt16(bytes: (data[0], data[1]))) let intervalMinRawValue = UInt16(littleEndian: UInt16(bytes: (data[2], data[3]))) let intervalMaxRawValue = UInt16(littleEndian: UInt16(bytes: (data[4], data[5]))) let latencyRawValue = UInt16(littleEndian: UInt16(bytes: (data[6], data[7]))) let supervisionTimeoutRaw = UInt16(littleEndian: UInt16(bytes: (data[8], data[9]))) // Parse enums and values ranges guard let interval = LowEnergyConnectionIntervalRange(rawValue: intervalMinRawValue ... intervalMaxRawValue), let connLatency = LowEnergyConnectionLatency(rawValue: latencyRawValue), let supervisionTimeout = LowEnergySupervisionTimeout(rawValue: supervisionTimeoutRaw) else { return nil } self.handle = handle self.interval = interval self.connLatency = connLatency self.supervisionTimeout = supervisionTimeout } }
mit
4e369def2d4859838a4bb035edd397c0
36.706897
117
0.689529
4.947964
false
false
false
false
snakajima/vs-metal
src/VSController.swift
1
2671
// // VSController.swift // vs-metal // // Created by SATOSHI NAKAJIMA on 6/23/17. // Copyright © 2017 SATOSHI NAKAJIMA. All rights reserved. // import Foundation import MetalKit /// VSController is a concrete implemtation of VSNode prototol, which represents a controller node. /// A controller node manipulates the texture stack, and there are five variations: /// - fork: Duplicate the top most texture /// - swap: Swap two topmost textures /// - discard: Discard the top most texture /// - shift: Shift the topmost texture to the bottom /// - previous: Push a texture from previous frame struct VSController : VSNode { private var encoder:((MTLCommandBuffer, VSContext) -> (Void)) private static func fork(commandBuffer:MTLCommandBuffer, context:VSContext) { if let texture = context.pop() { context.push(texture:texture) context.push(texture:texture) } } private static func swap(commandBuffer:MTLCommandBuffer, context:VSContext) { if let texture1 = context.pop(), let texture2 = context.pop() { context.push(texture:texture1) context.push(texture:texture2) } } private static func discard(commandBuffer:MTLCommandBuffer, context:VSContext) { let _ = context.pop() } private static func shift(commandBuffer:MTLCommandBuffer, context:VSContext) { context.shift() } private static func previous(commandBuffer:MTLCommandBuffer, context:VSContext) { let texture = context.prev() context.push(texture: texture) } /// Make a controller node, which conforms to VSNode protocol /// This function is called by VSSCript during the compilation process. /// /// - Parameter name: name of the controller node /// - Returns: a new controller node object public static func makeNode(name:String) -> VSNode? { switch(name) { case "fork": return VSController(encoder: fork) case "swap": return VSController(encoder: swap) case "discard": return VSController(encoder: discard) case "shift": return VSController(encoder: shift) case "previous": return VSController(encoder: previous) default: return nil } } /// Manipulate texture stack (such as fork and swap). /// /// - Parameters: /// - commandBuffer: The command buffer to encode to /// - context: the video pipeline context /// - Throws: VSContextError.underUnderflow if pop() was called when the stack is empty func encode(commandBuffer:MTLCommandBuffer, context:VSContext) { encoder(commandBuffer,context) } }
mit
4af5a5ec53cf7094fe759eb4c9f018d5
35.081081
99
0.671161
4.525424
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureQRCodeScanner/Sources/FeatureQRCodeScannerUI/QRCodeScanner/QRCodeScannerViewController.swift
1
8836
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import ComposableArchitecture import DIKit import FeatureQRCodeScannerDomain import Localization import PlatformKit import PlatformUIKit import SwiftUI import ToolKit import UIKit public enum QRCodePresentationType { case modal(dismissWithAnimation: Bool) case child } final class QRCodeScannerViewController: UIViewController, UINavigationControllerDelegate { private var targetCoordinateSpace: UICoordinateSpace { guard isViewLoaded else { fatalError("viewFrame should only be accessed after the view is loaded.") } guard let window = UIApplication.shared.keyWindow else { fatalError("Trying to get key window before it was set!") } return window.coordinateSpace } private var scannerView: QRCodeScannerView! private let viewModel: QRCodeScannerViewModelProtocol private let presentationType: QRCodePresentationType private lazy var sheetPresenter = BottomSheetPresenting(ignoresBackgroundTouches: true) init( presentationType: QRCodePresentationType = .modal(dismissWithAnimation: true), viewModel: QRCodeScannerViewModelProtocol ) { self.presentationType = presentationType self.viewModel = viewModel super.init(nibName: nil, bundle: nil) switch presentationType { case .modal(dismissWithAnimation: let animated): modalTransitionStyle = .crossDissolve self.viewModel.closeButtonTapped = { [weak self] in guard let self = self else { return } self.dismiss( animated: animated, completion: { [weak self] in self?.viewModel.completed(.failure(.dismissed)) } ) } case .child: break } self.viewModel.scanningStarted = { [weak self] in self?.scanDidStart() Logger.shared.info("Scanning started") } self.viewModel.scanningStopped = { [weak self] in self?.scanDidStop() } self.viewModel.scanComplete = { [weak self] result in self?.handleScanComplete(with: result) } self.viewModel.overlayViewModel.cameraButtonTapped = { [weak self] in self?.showImagePicker() } self.viewModel.showInformationSheetTapped = { [weak self] informationalOnly in self?.showAllowAccessSheet(informationalOnly: informationalOnly) } self.viewModel.cameraConfigured = { [weak self] in guard let self = self else { return } self.viewModel.startReadingQRCode(from: self.scannerView) self.scannerView?.startReadingQRCode() } self.viewModel.showCameraAccessFailure = { [weak self] title, message in self?.showAlert(title: title, message: message) } self.viewModel.showCameraNotAuthorizedAlert = { [weak self] in self?.showNeedsCameraPermissionAlert() } } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.darkFadeBackground scannerView = QRCodeScannerView(viewModel: viewModel, targetCoordinateSpace: targetCoordinateSpace) scannerView.alpha = 1 view.addSubview(scannerView) scannerView.layoutToSuperview(.leading, .trailing, .top, .bottom) switch presentationType { case .modal: title = viewModel.headerText navigationItem.rightBarButtonItem = UIBarButtonItem( image: UIImage(named: "close"), style: .plain, target: self, action: #selector(closeButtonClicked) ) case .child: break } navigationItem.leftBarButtonItem = UIBarButtonItem( image: UIImage(named: "Info", in: .featureQRCodeScannerUI, with: nil), style: .plain, target: self, action: #selector(informationButtonClicked) ) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) viewModel.viewDidAppear() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) viewModel.viewWillDisappear() } @objc func closeButtonClicked(sender: AnyObject) { viewModel.closeButtonPressed() } @objc func informationButtonClicked(sender: AnyObject) { viewModel.showInformationSheet() } private func handleScanComplete(with result: Result<QRCodeScannerResultType, QRCodeScannerResultError>) { guard case .success = result else { return } switch presentationType { case .modal(dismissWithAnimation: let animated): presentedViewController?.dismiss(animated: true) dismiss(animated: animated) { [weak self] in self?.viewModel.completed(result) } case .child: viewModel.completed(result) } } private func scanDidStart() { UIView.animate( withDuration: 0.25, delay: 0, options: [.curveEaseIn, .transitionCrossDissolve, .beginFromCurrentState], animations: { self.scannerView?.alpha = 1 }, completion: nil ) } private func scanDidStop() {} private func showImagePicker() { let pickerController = UIImagePickerController() pickerController.delegate = self pickerController.mediaTypes = ["public.image"] pickerController.sourceType = .photoLibrary present(pickerController, animated: true, completion: nil) } private func showAllowAccessSheet(informationalOnly: Bool) { let environment = AllowAccessEnvironment( allowCameraAccess: { [viewModel] in viewModel.allowCameraAccess() }, cameraAccessDenied: { [viewModel] in viewModel.cameraAccessDenied() }, dismiss: { [weak self] in self?.dismiss(animated: true, completion: nil) }, showCameraDeniedAlert: { [viewModel] in viewModel.showCameraNotAuthorizedAlert?() }, showsWalletConnectRow: { [viewModel] in viewModel.showsWalletConnectRow() }, openWalletConnectUrl: { [viewModel] url in viewModel.openWalletConnectArticle(url: url) } ) let allowAccessStore = Store( initialState: AllowAccessState( informationalOnly: informationalOnly, showWalletConnectRow: true ), reducer: qrScannerAllowAccessReducer, environment: environment ) let view = QRCodeScannerAllowAccessView(store: allowAccessStore) let hostingController = UIHostingController(rootView: view) hostingController.transitioningDelegate = sheetPresenter hostingController.modalPresentationStyle = .custom present(hostingController, animated: true, completion: nil) } private func showAlert(title: String, message: String) { let alertController = UIAlertController( title: title, message: message, preferredStyle: .alert ) present(alertController, animated: true, completion: nil) } private func showNeedsCameraPermissionAlert() { let alert = UIAlertController( title: LocalizationConstants.Errors.cameraAccessDenied, message: LocalizationConstants.Errors.cameraAccessDeniedMessage, preferredStyle: .alert ) alert.addAction( UIAlertAction(title: LocalizationConstants.goToSettings, style: .default) { [viewModel] _ in viewModel.openAppSettings() } ) alert.addAction( UIAlertAction(title: LocalizationConstants.cancel, style: .cancel) ) present(alert, animated: true, completion: nil) } } extension QRCodeScannerViewController: UIImagePickerControllerDelegate { func imagePickerController( _ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any] ) { guard let pickedImage = info[.originalImage] as? UIImage else { return } picker.dismiss(animated: true) { [weak self] in self?.viewModel.handleSelectedQRImage(pickedImage) } } }
lgpl-3.0
317bc1698d9f29be59007ca81223d8b2
33.377432
109
0.62841
5.60241
false
false
false
false
movielala/TVOSButton
Pods/ALKit/ALKit/ALKit/ALKit.swift
1
3839
// // ALKit.swift // AutolayoutPlayground // // Created by Cem Olcay on 22/10/15. // Copyright © 2015 prototapp. All rights reserved. // // https://www.github.com/cemolcay/ALKit // import UIKit public extension UIEdgeInsets { /// Equal insets for all edges public init (inset: CGFloat) { top = inset bottom = inset left = inset right = inset } } public extension UIView{ public convenience init (withAutolayout: Bool) { self.init(frame: CGRect.zero) translatesAutoresizingMaskIntoConstraints = false } public class func AutoLayout() -> UIView { let view = UIView(frame: CGRect.zero) view.translatesAutoresizingMaskIntoConstraints = false return view } public func pin( edge: NSLayoutAttribute, toEdge: NSLayoutAttribute, ofView: UIView?, withInset: CGFloat = 0) { guard let view = superview else { return assertionFailure("view must be added as subview in view hierarchy") } view.addConstraint(NSLayoutConstraint( item: self, attribute: edge, relatedBy: .Equal, toItem: ofView, attribute: toEdge, multiplier: 1, constant: withInset)) } // MARK: Pin Super public func pinRight(toView toView: UIView, withInset: CGFloat = 0) { pin(.Right, toEdge: .Right, ofView: toView, withInset: -withInset) } public func pinLeft(toView toView: UIView, withInset: CGFloat = 0) { pin(.Left, toEdge: .Left, ofView: toView, withInset: withInset) } public func pinTop(toView toView: UIView, withInset: CGFloat = 0) { pin(.Top, toEdge: .Top, ofView: toView, withInset: withInset) } public func pinBottom(toView toView: UIView, withInset: CGFloat = 0) { pin(.Bottom, toEdge: .Bottom, ofView: toView, withInset: -withInset) } // MARK: Pin To Another View In Super public func pinToRight(ofView ofView: UIView, withOffset: CGFloat = 0) { pin(.Left, toEdge: .Right, ofView: ofView, withInset: withOffset) } public func pinToLeft(ofView ofView: UIView, withOffset: CGFloat = 0) { pin(.Right, toEdge: .Left, ofView: ofView, withInset: -withOffset) } public func pinToTop(ofView ofView: UIView, withOffset: CGFloat = 0) { pin(.Bottom, toEdge: .Top, ofView: ofView, withInset: -withOffset) } public func pinToBottom(ofView ofView: UIView, withOffset: CGFloat = 0) { pin(.Top, toEdge: .Bottom, ofView: ofView, withInset: withOffset) } // MARK: Fill In Super public func fill(toView view: UIView, withInset: UIEdgeInsets = UIEdgeInsetsZero) { pinLeft(toView: view, withInset: withInset.left) pinRight(toView: view, withInset: withInset.right) pinTop(toView: view, withInset: withInset.top) pinBottom(toView: view, withInset: withInset.bottom) } public func fillHorizontal(toView view: UIView, withInset: CGFloat = 0) { pinRight(toView: view, withInset: withInset) pinLeft(toView: view, withInset: withInset) } public func fillVertical(toView view: UIView, withInset: CGFloat = 0) { pinTop(toView: view, withInset: withInset) pinBottom(toView: view, withInset: withInset) } // MARK: Size public func pinSize(width width: CGFloat, height: CGFloat) { pinWidth(width) pinHeight(height) } public func pinWidth(width: CGFloat) { pin(.Width, toEdge: .NotAnAttribute, ofView: nil, withInset: width) } public func pinHeight(height: CGFloat) { pin(.Height, toEdge: .NotAnAttribute, ofView: nil, withInset: height) } // MARK: Center public func pinCenter(toView view: UIView) { pinCenterX(toView: view) pinCenterY(toView: view) } public func pinCenterX(toView view: UIView) { pin(.CenterX, toEdge: .CenterX, ofView: view) } public func pinCenterY(toView view: UIView) { pin(.CenterY, toEdge: .CenterY, ofView: view) } }
apache-2.0
372132411536386458a94b69d2c5b239
26.611511
85
0.681605
4.087327
false
false
false
false
kaojohnny/CoreStore
Sources/Observing/DataStack+Observing.swift
1
13016
// // DataStack+Observing.swift // CoreStore // // Copyright © 2015 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData #if USE_FRAMEWORKS import GCDKit #endif #if os(iOS) || os(watchOS) || os(tvOS) // MARK: - DataStack public extension DataStack { /** Creates an `ObjectMonitor` for the specified `NSManagedObject`. Multiple `ObjectObserver`s may then register themselves to be notified when changes are made to the `NSManagedObject`. - parameter object: the `NSManagedObject` to observe changes from - returns: a `ObjectMonitor` that monitors changes to `object` */ @warn_unused_result public func monitorObject<T: NSManagedObject>(object: T) -> ObjectMonitor<T> { CoreStore.assert( NSThread.isMainThread(), "Attempted to observe objects from \(cs_typeName(self)) outside the main thread." ) return ObjectMonitor(dataStack: self, object: object) } /** Creates a `ListMonitor` for a list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListMonitor` instance that monitors changes to the list */ @warn_unused_result public func monitorList<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> ListMonitor<T> { return self.monitorList(from, fetchClauses) } /** Creates a `ListMonitor` for a list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListMonitor` instance that monitors changes to the list */ @warn_unused_result public func monitorList<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> ListMonitor<T> { CoreStore.assert( NSThread.isMainThread(), "Attempted to observe objects from \(cs_typeName(self)) outside the main thread." ) return ListMonitor( dataStack: self, from: from, sectionBy: nil, applyFetchClauses: { fetchRequest in fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) } CoreStore.assert( fetchRequest.sortDescriptors?.isEmpty == false, "An \(cs_typeName(NSFetchedResultsController)) requires a sort information. Specify from a \(cs_typeName(OrderBy)) clause or any custom \(cs_typeName(FetchClause)) that provides a sort descriptor." ) } ) } /** Asynchronously creates a `ListMonitor` for a list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Since `NSFetchedResultsController` greedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed. - parameter createAsynchronously: the closure that receives the created `ListMonitor` instance - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. */ public func monitorList<T: NSManagedObject>(createAsynchronously createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ fetchClauses: FetchClause...) { self.monitorList(createAsynchronously: createAsynchronously, from, fetchClauses) } /** Asynchronously creates a `ListMonitor` for a list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Since `NSFetchedResultsController` greedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed. - parameter createAsynchronously: the closure that receives the created `ListMonitor` instance - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. */ public func monitorList<T: NSManagedObject>(createAsynchronously createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ fetchClauses: [FetchClause]) { CoreStore.assert( NSThread.isMainThread(), "Attempted to observe objects from \(cs_typeName(self)) outside the main thread." ) _ = ListMonitor( dataStack: self, from: from, sectionBy: nil, applyFetchClauses: { fetchRequest in fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) } CoreStore.assert( fetchRequest.sortDescriptors?.isEmpty == false, "An \(cs_typeName(NSFetchedResultsController)) requires a sort information. Specify from a \(cs_typeName(OrderBy)) clause or any custom \(cs_typeName(FetchClause)) that provides a sort descriptor." ) }, createAsynchronously: createAsynchronously ) } /** Creates a `ListMonitor` for a sectioned list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. - parameter from: a `From` clause indicating the entity type - parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListMonitor` instance that monitors changes to the list */ @warn_unused_result public func monitorSectionedList<T: NSManagedObject>(from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) -> ListMonitor<T> { return self.monitorSectionedList(from, sectionBy, fetchClauses) } /** Creates a `ListMonitor` for a sectioned list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. - parameter from: a `From` clause indicating the entity type - parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListMonitor` instance that monitors changes to the list */ @warn_unused_result public func monitorSectionedList<T: NSManagedObject>(from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) -> ListMonitor<T> { CoreStore.assert( NSThread.isMainThread(), "Attempted to observe objects from \(cs_typeName(self)) outside the main thread." ) return ListMonitor( dataStack: self, from: from, sectionBy: sectionBy, applyFetchClauses: { fetchRequest in fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) } CoreStore.assert( fetchRequest.sortDescriptors?.isEmpty == false, "An \(cs_typeName(NSFetchedResultsController)) requires a sort information. Specify from a \(cs_typeName(OrderBy)) clause or any custom \(cs_typeName(FetchClause)) that provides a sort descriptor." ) } ) } /** Asynchronously creates a `ListMonitor` for a sectioned list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Since `NSFetchedResultsController` greedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed. - parameter createAsynchronously: the closure that receives the created `ListMonitor` instance - parameter from: a `From` clause indicating the entity type - parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. */ public func monitorSectionedList<T: NSManagedObject>(createAsynchronously createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) { self.monitorSectionedList(createAsynchronously: createAsynchronously, from, sectionBy, fetchClauses) } /** Asynchronously creates a `ListMonitor` for a sectioned list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Since `NSFetchedResultsController` greedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed. - parameter createAsynchronously: the closure that receives the created `ListMonitor` instance - parameter from: a `From` clause indicating the entity type - parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. */ public func monitorSectionedList<T: NSManagedObject>(createAsynchronously createAsynchronously: (ListMonitor<T>) -> Void, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) { CoreStore.assert( NSThread.isMainThread(), "Attempted to observe objects from \(cs_typeName(self)) outside the main thread." ) _ = ListMonitor( dataStack: self, from: from, sectionBy: sectionBy, applyFetchClauses: { fetchRequest in fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) } CoreStore.assert( fetchRequest.sortDescriptors?.isEmpty == false, "An \(cs_typeName(NSFetchedResultsController)) requires a sort information. Specify from a \(cs_typeName(OrderBy)) clause or any custom \(cs_typeName(FetchClause)) that provides a sort descriptor." ) }, createAsynchronously: createAsynchronously ) } } #endif
mit
e83705437f6ecd40aba29221c22c74eb
55.099138
457
0.687207
5.312245
false
false
false
false
ndleon09/SwiftSample500px
pictures/Modules/Detail/DetailViewController.swift
1
1648
// // DetailViewController.swift // pictures // // Created by Nelson on 05/11/15. // Copyright © 2015 Nelson Dominguez. All rights reserved. // import UIKit import TableViewKit class DetailViewController: UIViewController, DetailViewProtocol { var detailPresenter : DetailPresenterProtocol? var photo: Double? var tableViewManager: TableViewManager? override func viewDidLoad() { super.viewDidLoad() title = "Detail" let tableView = UITableView(frame: self.view.frame, style: .grouped) tableView.backgroundColor = UIColor.white tableView.separatorStyle = .none view.addSubview(tableView) tableViewManager = TableViewManager(tableView: tableView) tableViewManager?.animation = .none } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) loadDetailPhoto() } private func loadDetailPhoto() { guard let photo = photo else { return } detailPresenter?.loadDetailFromIdentifier(identifier: photo) } func showNotFoundMessage() { let alertController = UIAlertController(title: "Error", message: "Picture not found", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) } func showDetailPicture(detailModel: DetailModel) { let section = DetailViewSection(model: detailModel) tableViewManager?.sections.replace(with: [section]) } }
mit
1ccad28f712a205755ef6b01aab51873
27.894737
117
0.660595
5.228571
false
false
false
false
felix91gr/swift
test/IRGen/big_types_corner_cases.swift
1
5709
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -enable-large-loadable-types %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize public struct BigStruct { var i0 : Int32 = 0 var i1 : Int32 = 1 var i2 : Int32 = 2 var i3 : Int32 = 3 var i4 : Int32 = 4 var i5 : Int32 = 5 var i6 : Int32 = 6 var i7 : Int32 = 7 var i8 : Int32 = 8 } func takeClosure(execute block: () -> Void) { } class OptionalInoutFuncType { private var lp : BigStruct? private var _handler : ((BigStruct?, Error?) -> ())? func execute(_ error: Error?) { var p : BigStruct? var handler: ((BigStruct?, Error?) -> ())? takeClosure { p = self.lp handler = self._handler self._handler = nil } handler?(p, error) } } // CHECK-LABEL: define{{( protected)?}} internal swiftcc void @_T022big_types_corner_cases21OptionalInoutFuncTypeC7executeys5Error_pSgFyycfU_(%T22big_types_corner_cases9BigStructVSg* nocapture dereferenceable({{.*}}), %T22big_types_corner_cases21OptionalInoutFuncTypeC*, %T22big_types_corner_cases9BigStructVSgs5Error_pSgIxcx_Sg* nocapture dereferenceable({{.*}}) // CHECK: call void @_T0SqWy // CHECK: call void @_T0SqWe // CHECK: ret void public func f1_returns_BigType(_ x: BigStruct) -> BigStruct { return x } public func f2_returns_f1() -> (_ x: BigStruct) -> BigStruct { return f1_returns_BigType } public func f3_uses_f2() { let x = BigStruct() let useOfF2 = f2_returns_f1() let _ = useOfF2(x) } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T022big_types_corner_cases10f3_uses_f2yyF() // CHECK: call swiftcc void @_T022big_types_corner_cases9BigStructVACycfC(%T22big_types_corner_cases9BigStructV* noalias nocapture sret // CHECK: call swiftcc { i8*, %swift.refcounted* } @_T022big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF() // CHECK: call swiftcc void {{.*}}(%T22big_types_corner_cases9BigStructV* noalias nocapture sret {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself {{.*}}) // CHECK: ret void public func f4_tuple_use_of_f2() { let x = BigStruct() let tupleWithFunc = (f2_returns_f1(), x) let useOfF2 = tupleWithFunc.0 let _ = useOfF2(x) } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T022big_types_corner_cases18f4_tuple_use_of_f2yyF() // CHECK: [[TUPLE:%.*]] = call swiftcc { i8*, %swift.refcounted* } @_T022big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF() // CHECK: [[TUPLE_EXTRACT:%.*]] = extractvalue { i8*, %swift.refcounted* } [[TUPLE]], 0 // CHECK: [[CAST_EXTRACT:%.*]] = bitcast i8* [[TUPLE_EXTRACT]] to void (%T22big_types_corner_cases9BigStructV*, %T22big_types_corner_cases9BigStructV*, %swift.refcounted*)* // CHECK: call swiftcc void [[CAST_EXTRACT]](%T22big_types_corner_cases9BigStructV* noalias nocapture sret {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself %{{.*}}) // CHECK: ret void public class BigClass { public init() { } public var optVar: ((BigStruct)-> Void)? = nil func useBigStruct(bigStruct: BigStruct) { optVar!(bigStruct) } } // CHECK-LABEL: define{{( protected)?}} hidden swiftcc void @_T022big_types_corner_cases8BigClassC03useE6StructyAA0eH0V0aH0_tF(%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}), %T22big_types_corner_cases8BigClassC* swiftself) #0 { // CHECK: getelementptr inbounds %T22big_types_corner_cases8BigClassC, %T22big_types_corner_cases8BigClassC* // CHECK: call void @_T0SqWy // CHECK: [[BITCAST:%.*]] = bitcast i8* {{.*}} to void (%T22big_types_corner_cases9BigStructV*, %swift.refcounted*)* // CHECK: call swiftcc void [[BITCAST]](%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) %0, %swift.refcounted* swiftself // CHECK: ret void public struct MyStruct { public let a: Int public let b: String? } typealias UploadFunction = ((MyStruct, Int?) -> Void) -> Void func takesUploader(_ u: UploadFunction) { } class Foo { func blam() { takesUploader(self.myMethod) // crash compiling this } func myMethod(_ callback: (MyStruct, Int) -> Void) -> Void { } } // CHECK-LABEL: define{{( protected)?}} linkonce_odr hidden swiftcc { i8*, %swift.refcounted* } @_T022big_types_corner_cases3FooC8myMethodyyAA8MyStructV_SitcFTc(%T22big_types_corner_cases3FooC*) // CHECK: getelementptr inbounds %T22big_types_corner_cases3FooC, %T22big_types_corner_cases3FooC* // CHECK: getelementptr inbounds void (i8*, %swift.refcounted*, %T22big_types_corner_cases3FooC*)*, void (i8*, %swift.refcounted*, %T22big_types_corner_cases3FooC*)** // CHECK: call noalias %swift.refcounted* @swift_rt_swift_allocObject(%swift.type* getelementptr inbounds (%swift.full_boxmetadata, %swift.full_boxmetadata* // CHECK: ret { i8*, %swift.refcounted* } public enum LargeEnum { public enum InnerEnum { case simple(Int64) case hard(Int64, String?) } case Empty1 case Empty2 case Full(InnerEnum) } public func enumCallee(_ x: LargeEnum) { switch x { case .Full(let inner): print(inner) case .Empty1: break case .Empty2: break } } // CHECK-LABEL-64: define{{( protected)?}} swiftcc void @_T022big_types_corner_cases10enumCalleeyAA9LargeEnumOF(%T22big_types_corner_cases9LargeEnumO* noalias nocapture dereferenceable(34)) #0 { // CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO05InnerF0O // CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO // CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64 // CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64 // CHECK-64: call %swift.type* @_T0ypMa() // CHECK-64: ret void
apache-2.0
53dc81a1022f002763d08ed1e1763e36
40.369565
363
0.703276
3.281034
false
false
false
false
AndrewBennet/readinglist
ReadingList/Api/GoogleBooksRequest.swift
1
2770
import Foundation enum GoogleBooksRequest { case searchText(String, LanguageIso639_1?) case searchIsbn(String) case fetch(String) case coverImage(String, CoverType) case webpage(String) enum CoverType: Int { case thumbnail = 1 case small = 2 } private static let apiBaseUrl = URL(string: { #if DEBUG if CommandLine.arguments.contains("--UITests_MockHttpCalls") { return "http://localhost:8080/" } #endif return "https://www.googleapis.com/" }())! private static let googleBooksBaseUrl = URL(string: { #if DEBUG if CommandLine.arguments.contains("--UITests_MockHttpCalls") { return "http://localhost:8080/" } #endif return "https://books.google.com/" }())! private static let searchResultFields = "items(id,volumeInfo(title,subtitle,authors,industryIdentifiers,categories,imageLinks/thumbnail))" var baseUrl: URL { switch self { case .coverImage, .webpage: return GoogleBooksRequest.googleBooksBaseUrl default: return GoogleBooksRequest.apiBaseUrl } } var path: String { switch self { case .searchIsbn, .searchText: return "books/v1/volumes" case let .fetch(id): return "books/v1/volumes/\(id)" case .coverImage: return "books/content" case .webpage: return "books" } } var queryString: String? { switch self { case let .searchText(searchString, languageRestriction): let encodedQuery = searchString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! let langQuery: String if let languageCode = languageRestriction { langQuery = "&langRestrict=\(languageCode.rawValue)" } else { langQuery = "" } return "q=\(encodedQuery)&maxResults=40&fields=\(GoogleBooksRequest.searchResultFields)\(langQuery)" case let .searchIsbn(isbn): return "q=isbn:\(isbn)&maxResults=40&fields=\(GoogleBooksRequest.searchResultFields)" case .fetch: return nil case let .coverImage(googleBooksId, coverType): return "id=\(googleBooksId)&printsec=frontcover&img=1&zoom=\(coverType.rawValue)" case let .webpage(googleBooksId): return "id=\(googleBooksId)" } } var pathAndQuery: String { if let queryString = queryString { return "\(path)?\(queryString)" } else { return path } } var url: URL? { return URL(string: pathAndQuery, relativeTo: baseUrl) } }
gpl-3.0
c16694d504d53a0555153d9d7bec2299
29.777778
142
0.593141
4.792388
false
false
false
false
wookay/Look
samples/LookSample/Pods/C4/C4/UI/C4AudioPlayer.swift
3
10111
// Copyright © 2014 C4 // // 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 import AVFoundation /// C4AudioPlayer provides playback of audio data from a file or memory. /// /// Using an audio player you can: /// /// Play sounds of any duration /// /// Play sounds from files or memory buffers /// /// Loop sounds /// /// Play multiple sounds simultaneously, one sound per audio player, with precise synchronization /// /// Control relative playback level, stereo positioning, and playback rate for each sound you are playing /// /// Seek to a particular point in a sound file, which supports such application features as fast forward and rewind /// /// Obtain data you can use for playback-level metering public class C4AudioPlayer : NSObject, AVAudioPlayerDelegate { internal var player: AVAudioPlayer! /// Initializes a new audio player from a given file name /// /// ```` /// let ap = C4AudioPlayer("audioTrackFileName") /// ```` public init?(_ name: String) { self.player = nil super.init() guard let url = NSBundle.mainBundle().URLForResource(name, withExtension:nil) else { return nil } guard let player = try? AVAudioPlayer(contentsOfURL: url) else { return nil } self.player = player player.delegate = self } /// Plays a sound asynchronously. public func play() { player.play() } /// Pauses playback; sound remains ready to resume playback from where it left off. /// Calling pause leaves the audio player prepared to play; it does not release the audio hardware that was acquired upon /// calling play or prepareToPlay. public func pause() { player.pause() } /// Stops playback and undoes the setup needed for playback. /// Calling this method, or allowing a sound to finish playing, undoes the setup performed upon calling the play or /// prepareToPlay methods. /// The stop method does not reset the value of the currentTime property to 0. In other words, if you call stop during /// playback and then call play, playback resumes at the point where it left off. public func stop() { player.stop() } /// Returns the total duration, in seconds, of the sound associated with the audio player. (read-only) public var duration : Double { get { return Double(player.duration) } } /// Returns true if the receiver's current playback rate > 0. Otherwise returns false. public var playing : Bool { get { return player.playing } } /// The audio player’s stereo pan position. /// By setting this property you can position a sound in the stereo field. A value of –1.0 is full left, 0.0 is center, and /// 1.0 is full right. public var pan : Double { get { return Double(player.pan) } set(val) { player.pan = clamp(Float(val), min: -1.0, max: 1.0) } } /// The playback volume for the audio player, ranging from 0.0 through 1.0 on a linear scale. /// A value of 0.0 indicates silence; a value of 1.0 (the default) indicates full volume for the audio player instance. /// Use this property to control an audio player’s volume relative to other audio output. /// To provide UI in iOS for adjusting system audio playback volume, use the MPVolumeView class, which provides media /// playback controls that users expect and whose appearance you can customize. public var volume : Double { get { return Double(player.volume) } set(val) { player.volume = Float(val) } } /// The playback point, in seconds, within the timeline of the sound associated with the audio player. /// If the sound is playing, currentTime is the offset of the current playback position, measured in seconds from the start /// of the sound. If the sound is not playing, currentTime is the offset of where playing starts upon calling the play /// method, measured in seconds from the start of the sound. /// By setting this property you can seek to a specific point in a sound file or implement audio fast-forward and rewind /// functions. public var currentTime: Double { get { return player.currentTime } set(val) { player.currentTime = NSTimeInterval(val) } } /// The audio player’s playback rate. /// This property’s default value of 1.0 provides normal playback rate. The available range is from 0.5 for half-speed /// playback through 2.0 for double-speed playback. /// To set an audio player’s playback rate, you must first enable rate adjustment as described in the enableRate property /// description. /// /// ```` /// let ap = C4AudioPlayer("audioTrackFileName") /// ap.enableRate = true /// ap.rate = 0.5 /// ap.play() /// ```` public var rate: Double { get { return Double(player.rate) } set(val) { player.rate = Float(rate) } } /// The number of times a sound will return to the beginning, upon reaching the end, to repeat playback. /// A value of 0, which is the default, means to play the sound once. Set a positive integer value to specify the number of /// times to return to the start and play again. For example, specifying a value of 1 results in a total of two plays of the /// sound. Set any negative integer value to loop the sound indefinitely until you call the stop method. /// /// Defaults to 1000000. public var loops : Bool { get { return player.numberOfLoops > 0 ? true : false } set(val) { if val { player.numberOfLoops = 1000000 } else { player.numberOfLoops = 0 } } } /// A Boolean value that specifies the audio-level metering on/off state for the audio player. /// The default value for the meteringEnabled property is off (Boolean false). Before using metering for an audio player, you need to enable it by setting this /// property to true. If player is an audio player instance variable of your controller class, you enable metering as shown here: /// /// ```` /// let ap = C4AudioPlayer("audioTrackFileName") /// ap.meteringEnabled = true /// ```` public var meteringEnabled : Bool { get { return player.meteringEnabled } set(v) { player.meteringEnabled = v } } /// A Boolean value that specifies whether playback rate adjustment is enabled for an audio player. /// To enable adjustable playback rate for an audio player, set this property to true after you initialize the player and before you call the prepareToPlay /// instance method for the player. public var enableRate : Bool { get { return player.enableRate } set(v) { player.enableRate = v } } /// Refreshes the average and peak power values for all channels of an audio player. /// To obtain current audio power values, you must call this method before calling averagePowerForChannel: or peakPowerForChannel:. /// /// ```` /// let t = NSTimer.scheduledTimerWithTimeInterval(1.0/60.0, /// target: self, /// selector: "update", /// userInfo: nil, /// repeats: true) /// /// let ap = C4AudioPlayer("audioTrackFileName") /// ap.meteringEnabled = true /// /// func update() { /// ap.updateMeters() /// } /// ```` public func updateMeters() { player.updateMeters() } /// Returns the average power for a given channel, in decibels, for the sound being played. /// /// ```` /// func update() { /// let av = player.averagePower(channel: 0) /// } /// ```` /// - parameter channelNumber: The audio channel whose average power value you want to obtain. /// /// - returns: A floating-point representation, in decibels, of a given audio channel’s current average power. public func averagePower(channel: Int) -> Double { return Double(player.averagePowerForChannel(channel)) } /// Returns the peak power for a given channel, in decibels, for the sound being played. /// /// ```` /// func update() { /// let pk = player.peakPower(channel: 0) /// } /// - parameter channelNumber: The audio channel whose peak power value you want to obtain. /// /// - returns: A floating-point representation, in decibels, of a given audio channel’s current peak power. public func peakPower(channel: Int) -> Double { return Double(player.peakPowerForChannel(channel)) } }
mit
8bfc3439160a55d7224f2cb0d0f29fe6
39.376
163
0.636319
4.747883
false
false
false
false
bizibizi/BIZViper-InitialProject-Swift
Chat/Classes/Common/SeparatedModules/User Interface/Wireframe/RootWireframe.swift
1
1670
// // RootWireframe.swift // // // Created by [email protected] on 5/15/16. // Copyright © 2016 [email protected]. All rights reserved. // import UIKit class RootWireframe { static func rootViewContollerFromWindow(window: UIWindow) -> UIViewController! { if window.rootViewController is UINavigationController { if let nvc = window.rootViewController as? UINavigationController { return nvc.viewControllers.first } return nil } else { return window.rootViewController } } func presentOkAlert(presentingViewController: UIViewController, title: String, message: String, okButtonEventHandler: (action: UIAlertAction) -> Void) { let alertController = UIAlertController.init(title: title, message: message, preferredStyle: .Alert) let actionOk = UIAlertAction.init(title: NSLocalizedString("OK", comment: ""), style: .Default, handler: okButtonEventHandler) alertController.addAction(actionOk) presentingViewController.presentViewController(alertController, animated: true, completion: nil) } //MARK: Create ViewControllers func createViewController(withKey key: String) -> UIViewController { let storyboard = UIStoryboard.init(name: "Main", bundle: NSBundle.mainBundle()) let viewController = storyboard.instantiateViewControllerWithIdentifier(key) return viewController } func createViewController(withXibName xibName: String) -> UIViewController { return NSBundle.mainBundle().loadNibNamed(xibName, owner: nil, options: nil).first as! UIViewController } }
mit
94bd4b4ace37cdb8c166142ab528779c
37.837209
156
0.699221
5.231975
false
false
false
false
piscoTech/GymTracker
Gym Tracker Core/GTSimpleSetsExerciseExport.swift
1
2072
// // GTSimpleSetsExerciseExport.swift // Gym Tracker // // Created by Marco Boschi on 22/04/2017. // Copyright © 2017 Marco Boschi. All rights reserved. // import Foundation import MBLibrary extension GTSimpleSetsExercise { static let exerciseTag = "exercize" static let nameTag = "name" static let isCircuitTag = "iscircuit" static let hasCircuitRestTag = "hascircuitrest" static let setsTag = "sets" override func export() -> String { var res = "<\(GTSimpleSetsExercise.exerciseTag)>" res += "<\(GTSimpleSetsExercise.nameTag)>\(name.toXML())</\(GTSimpleSetsExercise.nameTag)>" if isInCircuit { res += "<\(GTSimpleSetsExercise.hasCircuitRestTag)>\(hasCircuitRest)</\(GTSimpleSetsExercise.hasCircuitRestTag)>" } res += "<\(GTSimpleSetsExercise.setsTag)>\(self.setList.map { $0.export() }.reduce("") { $0 + $1 })</\(GTSimpleSetsExercise.setsTag)>" res += "</\(GTSimpleSetsExercise.exerciseTag)>" return res } override class func `import`(fromXML xml: XMLNode, withDataManager dataManager: DataManager) throws -> GTSimpleSetsExercise { guard xml.name == GTSimpleSetsExercise.exerciseTag, let name = xml.children.first(where: { $0.name == GTSimpleSetsExercise.nameTag })?.content?.fromXML(), let sets = xml.children.first(where: { $0.name == GTSimpleSetsExercise.setsTag })?.children else { throw GTError.importFailure([]) } let hasCircuitRest = xml.children.first(where: { $0.name == GTSimpleSetsExercise.hasCircuitRestTag })?.content ?? "false" == "true" let e = dataManager.newExercise() e.set(name: name) e.forceEnableCircuitRest(hasCircuitRest) for s in sets { do { let o = try GTDataObject.import(fromXML: s, withDataManager: dataManager) guard let repSet = o as? GTSet else { throw GTError.importFailure(e.subtreeNodes.union([o])) } e.add(set: repSet) } catch GTError.importFailure(let obj) { throw GTError.importFailure(e.subtreeNodes.union(obj)) } } if e.isSubtreeValid { return e } else { throw GTError.importFailure(e.subtreeNodes) } } }
mit
9713a93dcbb6edb9c8611d3380c54e30
31.873016
136
0.702559
3.685053
false
false
false
false
nathawes/swift
stdlib/public/Darwin/Foundation/Locale.swift
9
19710
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module @_implementationOnly import _SwiftFoundationOverlayShims /** `Locale` encapsulates information about linguistic, cultural, and technological conventions and standards. Examples of information encapsulated by a locale include the symbol used for the decimal separator in numbers and the way dates are formatted. Locales are typically used to provide, format, and interpret information about and according to the user's customs and preferences. They are frequently used in conjunction with formatters. Although you can use many locales, you usually use the one associated with the current user. */ public struct Locale : Hashable, Equatable, ReferenceConvertible { public typealias ReferenceType = NSLocale public typealias LanguageDirection = NSLocale.LanguageDirection fileprivate var _wrapped : NSLocale private var _autoupdating : Bool /// Returns a locale which tracks the user's current preferences. /// /// If mutated, this Locale will no longer track the user's preferences. /// /// - note: The autoupdating Locale will only compare equal to another autoupdating Locale. public static var autoupdatingCurrent : Locale { return Locale(adoptingReference: __NSLocaleAutoupdating() as! NSLocale, autoupdating: true) } /// Returns the user's current locale. public static var current : Locale { return Locale(adoptingReference: __NSLocaleCurrent() as! NSLocale, autoupdating: false) } @available(*, unavailable, message: "Consider using the user's locale or nil instead, depending on use case") public static var system : Locale { fatalError() } // MARK: - // /// Return a locale with the specified identifier. public init(identifier: String) { _wrapped = NSLocale(localeIdentifier: identifier) _autoupdating = false } fileprivate init(reference: __shared NSLocale) { _wrapped = reference.copy() as! NSLocale if __NSLocaleIsAutoupdating(reference) { _autoupdating = true } else { _autoupdating = false } } private init(adoptingReference reference: NSLocale, autoupdating: Bool) { _wrapped = reference _autoupdating = autoupdating } // MARK: - // /// Returns a localized string for a specified identifier. /// /// For example, in the "en" locale, the result for `"es"` is `"Spanish"`. public func localizedString(forIdentifier identifier: String) -> String? { return _wrapped.displayName(forKey: .identifier, value: identifier) } /// Returns a localized string for a specified language code. /// /// For example, in the "en" locale, the result for `"es"` is `"Spanish"`. public func localizedString(forLanguageCode languageCode: String) -> String? { return _wrapped.displayName(forKey: .languageCode, value: languageCode) } /// Returns a localized string for a specified region code. /// /// For example, in the "en" locale, the result for `"fr"` is `"France"`. public func localizedString(forRegionCode regionCode: String) -> String? { return _wrapped.displayName(forKey: .countryCode, value: regionCode) } /// Returns a localized string for a specified script code. /// /// For example, in the "en" locale, the result for `"Hans"` is `"Simplified Han"`. public func localizedString(forScriptCode scriptCode: String) -> String? { return _wrapped.displayName(forKey: .scriptCode, value: scriptCode) } /// Returns a localized string for a specified variant code. /// /// For example, in the "en" locale, the result for `"POSIX"` is `"Computer"`. public func localizedString(forVariantCode variantCode: String) -> String? { return _wrapped.displayName(forKey: .variantCode, value: variantCode) } /// Returns a localized string for a specified `Calendar.Identifier`. /// /// For example, in the "en" locale, the result for `.buddhist` is `"Buddhist Calendar"`. public func localizedString(for calendarIdentifier: Calendar.Identifier) -> String? { // NSLocale doesn't export a constant for this let result = CFLocaleCopyDisplayNameForPropertyValue(unsafeBitCast(_wrapped, to: CFLocale.self), .calendarIdentifier, Calendar._toNSCalendarIdentifier(calendarIdentifier).rawValue as CFString) as String? return result } /// Returns a localized string for a specified ISO 4217 currency code. /// /// For example, in the "en" locale, the result for `"USD"` is `"US Dollar"`. /// - seealso: `Locale.isoCurrencyCodes` public func localizedString(forCurrencyCode currencyCode: String) -> String? { return _wrapped.displayName(forKey: .currencyCode, value: currencyCode) } /// Returns a localized string for a specified ICU collation identifier. /// /// For example, in the "en" locale, the result for `"phonebook"` is `"Phonebook Sort Order"`. public func localizedString(forCollationIdentifier collationIdentifier: String) -> String? { return _wrapped.displayName(forKey: .collationIdentifier, value: collationIdentifier) } /// Returns a localized string for a specified ICU collator identifier. public func localizedString(forCollatorIdentifier collatorIdentifier: String) -> String? { return _wrapped.displayName(forKey: .collatorIdentifier, value: collatorIdentifier) } // MARK: - // /// Returns the identifier of the locale. public var identifier: String { return _wrapped.localeIdentifier } /// Returns the language code of the locale, or nil if has none. /// /// For example, for the locale "zh-Hant-HK", returns "zh". public var languageCode: String? { return _wrapped.object(forKey: .languageCode) as? String } /// Returns the region code of the locale, or nil if it has none. /// /// For example, for the locale "zh-Hant-HK", returns "HK". public var regionCode: String? { // n.b. this is called countryCode in ObjC if let result = _wrapped.object(forKey: .countryCode) as? String { if result.isEmpty { return nil } else { return result } } else { return nil } } /// Returns the script code of the locale, or nil if has none. /// /// For example, for the locale "zh-Hant-HK", returns "Hant". public var scriptCode: String? { return _wrapped.object(forKey: .scriptCode) as? String } /// Returns the variant code for the locale, or nil if it has none. /// /// For example, for the locale "en_POSIX", returns "POSIX". public var variantCode: String? { if let result = _wrapped.object(forKey: .variantCode) as? String { if result.isEmpty { return nil } else { return result } } else { return nil } } /// Returns the exemplar character set for the locale, or nil if has none. public var exemplarCharacterSet: CharacterSet? { return _wrapped.object(forKey: .exemplarCharacterSet) as? CharacterSet } /// Returns the calendar for the locale, or the Gregorian calendar as a fallback. public var calendar: Calendar { // NSLocale should not return nil here if let result = _wrapped.object(forKey: .calendar) as? Calendar { return result } else { return Calendar(identifier: .gregorian) } } /// Returns the collation identifier for the locale, or nil if it has none. /// /// For example, for the locale "en_US@collation=phonebook", returns "phonebook". public var collationIdentifier: String? { return _wrapped.object(forKey: .collationIdentifier) as? String } /// Returns true if the locale uses the metric system. /// /// -seealso: MeasurementFormatter public var usesMetricSystem: Bool { // NSLocale should not return nil here, but just in case if let result = (_wrapped.object(forKey: .usesMetricSystem) as? NSNumber)?.boolValue { return result } else { return false } } /// Returns the decimal separator of the locale. /// /// For example, for "en_US", returns ".". public var decimalSeparator: String? { return _wrapped.object(forKey: .decimalSeparator) as? String } /// Returns the grouping separator of the locale. /// /// For example, for "en_US", returns ",". public var groupingSeparator: String? { return _wrapped.object(forKey: .groupingSeparator) as? String } /// Returns the currency symbol of the locale. /// /// For example, for "zh-Hant-HK", returns "HK$". public var currencySymbol: String? { return _wrapped.object(forKey: .currencySymbol) as? String } /// Returns the currency code of the locale. /// /// For example, for "zh-Hant-HK", returns "HKD". public var currencyCode: String? { return _wrapped.object(forKey: .currencyCode) as? String } /// Returns the collator identifier of the locale. public var collatorIdentifier: String? { return _wrapped.object(forKey: .collatorIdentifier) as? String } /// Returns the quotation begin delimiter of the locale. /// /// For example, returns `“` for "en_US", and `「` for "zh-Hant-HK". public var quotationBeginDelimiter: String? { return _wrapped.object(forKey: .quotationBeginDelimiterKey) as? String } /// Returns the quotation end delimiter of the locale. /// /// For example, returns `”` for "en_US", and `」` for "zh-Hant-HK". public var quotationEndDelimiter: String? { return _wrapped.object(forKey: .quotationEndDelimiterKey) as? String } /// Returns the alternate quotation begin delimiter of the locale. /// /// For example, returns `‘` for "en_US", and `『` for "zh-Hant-HK". public var alternateQuotationBeginDelimiter: String? { return _wrapped.object(forKey: .alternateQuotationBeginDelimiterKey) as? String } /// Returns the alternate quotation end delimiter of the locale. /// /// For example, returns `’` for "en_US", and `』` for "zh-Hant-HK". public var alternateQuotationEndDelimiter: String? { return _wrapped.object(forKey: .alternateQuotationEndDelimiterKey) as? String } // MARK: - // /// Returns a list of available `Locale` identifiers. public static var availableIdentifiers: [String] { return NSLocale.availableLocaleIdentifiers } /// Returns a list of available `Locale` language codes. public static var isoLanguageCodes: [String] { return NSLocale.isoLanguageCodes } /// Returns a list of available `Locale` region codes. public static var isoRegionCodes: [String] { // This was renamed from Obj-C return NSLocale.isoCountryCodes } /// Returns a list of available `Locale` currency codes. public static var isoCurrencyCodes: [String] { return NSLocale.isoCurrencyCodes } /// Returns a list of common `Locale` currency codes. public static var commonISOCurrencyCodes: [String] { return NSLocale.commonISOCurrencyCodes } /// Returns a list of the user's preferred languages. /// /// - note: `Bundle` is responsible for determining the language that your application will run in, based on the result of this API and combined with the languages your application supports. /// - seealso: `Bundle.preferredLocalizations(from:)` /// - seealso: `Bundle.preferredLocalizations(from:forPreferences:)` public static var preferredLanguages: [String] { return NSLocale.preferredLanguages } /// Returns a dictionary that splits an identifier into its component pieces. public static func components(fromIdentifier string: String) -> [String : String] { return NSLocale.components(fromLocaleIdentifier: string) } /// Constructs an identifier from a dictionary of components. public static func identifier(fromComponents components: [String : String]) -> String { return NSLocale.localeIdentifier(fromComponents: components) } /// Returns a canonical identifier from the given string. public static func canonicalIdentifier(from string: String) -> String { return NSLocale.canonicalLocaleIdentifier(from: string) } /// Returns a canonical language identifier from the given string. public static func canonicalLanguageIdentifier(from string: String) -> String { return NSLocale.canonicalLanguageIdentifier(from: string) } /// Returns the `Locale` identifier from a given Windows locale code, or nil if it could not be converted. public static func identifier(fromWindowsLocaleCode code: Int) -> String? { return NSLocale.localeIdentifier(fromWindowsLocaleCode: UInt32(code)) } /// Returns the Windows locale code from a given identifier, or nil if it could not be converted. public static func windowsLocaleCode(fromIdentifier identifier: String) -> Int? { let result = NSLocale.windowsLocaleCode(fromLocaleIdentifier: identifier) if result == 0 { return nil } else { return Int(result) } } /// Returns the character direction for a specified language code. public static func characterDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection { return NSLocale.characterDirection(forLanguage: isoLangCode) } /// Returns the line direction for a specified language code. public static func lineDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection { return NSLocale.lineDirection(forLanguage: isoLangCode) } // MARK: - @available(*, unavailable, renamed: "init(identifier:)") public init(localeIdentifier: String) { fatalError() } @available(*, unavailable, renamed: "identifier") public var localeIdentifier: String { fatalError() } @available(*, unavailable, renamed: "localizedString(forIdentifier:)") public func localizedString(forLocaleIdentifier localeIdentifier: String) -> String { fatalError() } @available(*, unavailable, renamed: "availableIdentifiers") public static var availableLocaleIdentifiers: [String] { fatalError() } @available(*, unavailable, renamed: "components(fromIdentifier:)") public static func components(fromLocaleIdentifier string: String) -> [String : String] { fatalError() } @available(*, unavailable, renamed: "identifier(fromComponents:)") public static func localeIdentifier(fromComponents dict: [String : String]) -> String { fatalError() } @available(*, unavailable, renamed: "canonicalIdentifier(from:)") public static func canonicalLocaleIdentifier(from string: String) -> String { fatalError() } @available(*, unavailable, renamed: "identifier(fromWindowsLocaleCode:)") public static func localeIdentifier(fromWindowsLocaleCode lcid: UInt32) -> String? { fatalError() } @available(*, unavailable, renamed: "windowsLocaleCode(fromIdentifier:)") public static func windowsLocaleCode(fromLocaleIdentifier localeIdentifier: String) -> UInt32 { fatalError() } @available(*, unavailable, message: "use regionCode instead") public var countryCode: String { fatalError() } @available(*, unavailable, message: "use localizedString(forRegionCode:) instead") public func localizedString(forCountryCode countryCode: String) -> String { fatalError() } @available(*, unavailable, renamed: "isoRegionCodes") public static var isoCountryCodes: [String] { fatalError() } // MARK: - // public func hash(into hasher: inout Hasher) { if _autoupdating { hasher.combine(false) } else { hasher.combine(true) hasher.combine(_wrapped) } } public static func ==(lhs: Locale, rhs: Locale) -> Bool { if lhs._autoupdating || rhs._autoupdating { return lhs._autoupdating == rhs._autoupdating } else { return lhs._wrapped.isEqual(rhs._wrapped) } } } extension Locale : CustomDebugStringConvertible, CustomStringConvertible, CustomReflectable { private var _kindDescription : String { if self == Locale.autoupdatingCurrent { return "autoupdatingCurrent" } else if self == Locale.current { return "current" } else { return "fixed" } } public var customMirror : Mirror { var c: [(label: String?, value: Any)] = [] c.append((label: "identifier", value: identifier)) c.append((label: "kind", value: _kindDescription)) return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct) } public var description: String { return "\(identifier) (\(_kindDescription))" } public var debugDescription : String { return "\(identifier) (\(_kindDescription))" } } extension Locale : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSLocale { return _wrapped } public static func _forceBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) { if !_conditionallyBridgeFromObjectiveC(input, result: &result) { fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) -> Bool { result = Locale(reference: input) return true } @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC(_ source: NSLocale?) -> Locale { var result: Locale? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } extension NSLocale : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(self as Locale) } } extension Locale : Codable { private enum CodingKeys : Int, CodingKey { case identifier } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let identifier = try container.decode(String.self, forKey: .identifier) self.init(identifier: identifier) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.identifier, forKey: .identifier) } }
apache-2.0
f6369944fc3c2d2cc058cf8bf98f0f0d
38.309381
282
0.655733
5.056226
false
false
false
false
yujiaao/HanekeSwift
HanekeTests/UIImage+Test.swift
1
2782
// // UIImageExtension.swift // Haneke // // Created by Oriol Blanc Gimeno on 01/08/14. // Copyright (c) 2014 Haneke. All rights reserved. // import UIKit extension UIImage { func isEqualPixelByPixel(theOtherImage: UIImage) -> Bool { let imageData = self.normalizedData() let theOtherImageData = theOtherImage.normalizedData() return imageData.isEqualToData(theOtherImageData) } func normalizedData() -> NSData { let pixelSize = CGSize(width : self.size.width * self.scale, height : self.size.height * self.scale) NSLog(NSStringFromCGSize(pixelSize)) UIGraphicsBeginImageContext(pixelSize) self.drawInRect(CGRect(x: 0, y: 0, width: pixelSize.width, height: pixelSize.height)) let drawnImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let provider = CGImageGetDataProvider(drawnImage.CGImage) let data = CGDataProviderCopyData(provider) return data! } class func imageWithColor(color: UIColor, _ size: CGSize = CGSize(width: 1, height: 1), _ opaque: Bool = true) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, opaque, 0) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } class func imageGradientFromColor(fromColor : UIColor = UIColor.redColor(), toColor : UIColor = UIColor.greenColor(), size : CGSize = CGSizeMake(10, 20)) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false /* opaque */, 0 /* scale */) let context = UIGraphicsGetCurrentContext() let colorspace = CGColorSpaceCreateDeviceRGB() let gradientNumberOfLocations : size_t = 2 let gradientLocations : [CGFloat] = [ 0.0, 1.0 ] var r1 : CGFloat = 0, g1 : CGFloat = 0, b1 : CGFloat = 0, a1 : CGFloat = 0 fromColor.getRed(&r1, green: &g1, blue: &b1, alpha: &a1) var r2 : CGFloat = 0, g2 : CGFloat = 0 , b2 : CGFloat = 0, a2 : CGFloat = 0 toColor.getRed(&r2, green: &g2, blue: &b2, alpha: &a2) let gradientComponents = [r1, g1, b1, a1, r2, g2, b2, a2] let gradient = CGGradientCreateWithColorComponents (colorspace, gradientComponents, gradientLocations, gradientNumberOfLocations) CGContextDrawLinearGradient(context, gradient, CGPointMake(0, 0), CGPointMake(0, size.height), CGGradientDrawingOptions(rawValue: 0)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
apache-2.0
c1fc97d17d08784f4044ade04ad33fd4
45.366667
170
0.679367
4.598347
false
false
false
false
xcodeswift/xcproj
Sources/XcodeProj/Workspace/XCWorkspaceDataElementLocationType.swift
1
2853
import Foundation public enum XCWorkspaceDataElementLocationType { public enum Error: Swift.Error { case missingSchema } case absolute(String) // "Absolute path" case container(String) // "Relative to container" case developer(String) // "Relative to Developer Directory" case group(String) // "Relative to group" case `self`(String) // Single project workspace in xcodeproj directory case other(String, String) public var schema: String { switch self { case .absolute: return "absolute" case .container: return "container" case .developer: return "developer" case .group: return "group" case .self: return "self" case let .other(schema, _): return schema } } public var path: String { switch self { case let .absolute(path): return path case let .container(path): return path case let .developer(path): return path case let .group(path): return path case let .self(path): return path case let .other(_, path): return path } } public init(string: String) throws { let elements = string.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false) guard let schema = elements.first.map(String.init) else { throw Error.missingSchema } let path = String(elements.last ?? "") switch schema { case "absolute": self = .absolute(path) case "container": self = .container(path) case "developer": self = .developer(path) case "group": self = .group(path) case "self": self = .self(path) default: self = .other(schema, path) } } } extension XCWorkspaceDataElementLocationType: CustomStringConvertible { public var description: String { "\(schema):\(path)" } } extension XCWorkspaceDataElementLocationType: Equatable { public static func == (lhs: XCWorkspaceDataElementLocationType, rhs: XCWorkspaceDataElementLocationType) -> Bool { switch (lhs, rhs) { case let (.absolute(lhs), .absolute(rhs)): return lhs == rhs case let (.container(lhs), .container(rhs)): return lhs == rhs case let (.developer(lhs), .developer(rhs)): return lhs == rhs case let (.group(lhs), .group(rhs)): return lhs == rhs case let (.self(lhs), .self(rhs)): return lhs == rhs case let (.other(lhs0, lhs1), .other(rhs0, rhs1)): return lhs0 == rhs0 && lhs1 == rhs1 default: return false } } }
mit
58535af534a963a7c9adc60c90b1bd96
28.71875
118
0.556257
4.707921
false
false
false
false
AfricanSwift/TUIKit
TUIKit/Source/Ansi/Ansi+Set.swift
1
23756
// // File: Ansi+Set.swift // Created by: African Swift import Darwin public extension Ansi { /// DEC Private Mode Set (DECSET) & Reset (DECRST). /// - CSI ? Pm h ... CSI ? Pm l /// /// Set Mode (SM) / Reset Mode (RM) /// - CSI Pm l ... CSI Pm h public enum Set { private static let setH = { (function: Int) -> Ansi in return Ansi("\(Ansi.C1.CSI)\(function)h") } private static let setL = { (function: Int) -> Ansi in return Ansi("\(Ansi.C1.CSI)\(function)l") } private static let setHQ = { (function: Int) -> Ansi in return Ansi("\(Ansi.C1.CSI)?\(function)h") } private static let setLQ = { (function: Int) -> Ansi in return Ansi("\(Ansi.C1.CSI)?\(function)l") } // /// Ps = 2 -> Keyboard Action Mode (AM). // public static func keyboardActionModeOn() -> Ansi // { // return setH(2) // } // // /// Ps = 2 -> Keyboard Action Mode (AM). // public static func keyboardActionModeOff() -> Ansi { // return setL(2) // } /// Ps = 4 -> Insert Mode (IRM) /// /// - returns: Ansi public static func modeInsert() -> Ansi { return setH(4) } /// Ps = 4 -> Replace Mode (IRM) /// /// - returns: Ansi public static func modeReplace() -> Ansi { return setL(4) } // /// Ps = 1 2 -> Send/receive (SRM). // public static func sendReceiveOn() -> Ansi // { // return setH(12) // } // // /// Ps = 1 2 -> Send/receive (SRM). // public static func sendReceiveOff() -> Ansi // { // return setL(12) // } /// Ps = 2 0 -> Automatic Newline (LNM) /// /// - returns: Ansi public static func linefeedAutomaticNewline() -> Ansi { return setH(20) } /// Ps = 2 0 -> Normal Linefeed (LNM) /// /// - returns: Ansi public static func linefeedNormal() -> Ansi { return setL(20) } /// Application Cursor Keys (DECCKM) /// /// Causes the cursor keys to send application control functions. public static func cursorKeysApplication() -> Ansi { return setHQ(1) } /// Normal Cursor Keys (DECCKM) /// /// Causes the cursor keys to generate ANSI cursor control sequences. public static func cursorKeysNormal() -> Ansi { return setLQ(1) } // /// Ps = 2 -> Designate USASCII for character sets // /// G0-G3 (DECANM), and set VT100 mode. // public static func designateUSASCII() -> Ansi // { // return setHQ(2) // } // // /// Ps = 2 -> Designate VT52 mode (DECANM). // public static func designateVT52() -> Ansi // { // return setLQ(2) // } /// Ps = 3 -> 132 Column Mode (DECCOLM) /// /// - returns: Ansi public static func column132() -> Ansi { return setHQ(3) } /// Ps = 3 -> 80 Column Mode (DECCOLM) /// /// - returns: Ansi public static func column80() -> Ansi { return setLQ(3) } /// Ps = 4 -> Smooth (Slow) Scroll (DECSCLM) /// /// - returns: Ansi public static func scrollSmooth() -> Ansi { return setHQ(4) } /// Ps = 4 -> Jump (Fast) Scroll (DECSCLM) /// /// - returns: Ansi public static func scrollJump() -> Ansi { return setLQ(4) } /// Ps = 5 -> Reverse Video (DECSCNM) /// /// - returns: Ansi public static func videoReverse() -> Ansi { return setHQ(5) } /// Ps = 5 -> Normal Video (DECSCNM) /// /// - returns: Ansi public static func videoNormal() -> Ansi { return setLQ(5) } /// Ps = 6 -> Origin Mode (DECOM) /// /// - returns: Ansi public static func modeOrigin() -> Ansi { return setHQ(6) } /// Ps = 6 -> Normal Cursor Mode (DECOM) /// /// - returns: Ansi public static func modeNormalCursor() -> Ansi { return setLQ(6) } /// Ps = 7 -> Wraparound Mode (DECAWM) /// /// - returns: Ansi public static func wraparoundModeOn() -> Ansi { return setHQ(7) } /// Ps = 7 -> No Wraparound Mode (DECAWM) /// /// - returns: Ansi public static func wraparoundModeOff() -> Ansi { return setLQ(7) } /// Ps = 8 -> Auto-repeat Keys (DECARM) /// /// - returns: Ansi public static func autorepeatKeysOn() -> Ansi { return setHQ(8) } /// Ps = 8 -> No Auto-repeat Keys (DECARM) /// /// - returns: Ansi public static func autorepeatKeysOff() -> Ansi { return setLQ(8) } /// Ps = 9 -> Send Mouse X & Y on button press /// /// - returns: Ansi public static func sendMouseXYOnButtonPressOn() -> Ansi { return setHQ(9) } /// Ps = 9 -> Don't Send Mouse X & Y on button press. /// /// - returns: Ansi public static func sendMouseXYOnButtonPressOff() -> Ansi { return setLQ(9) } // /// Ps = 1 0 -> Show toolbar (rxvt). // public static func toolbarOn() -> Ansi // { // return setHQ(10) // } // // /// Ps = 1 0 -> Hide toolbar (rxvt). // public static func toolbarOff() -> Ansi // { // return setLQ(10) // } /// Ps = 1 2 -> Start Blinking Cursor (att610) /// /// - returns: Ansi public static func blinkingCursorStart() -> Ansi { return setHQ(12) } /// Ps = 1 2 -> Stop Blinking Cursor (att610) /// /// - returns: Ansi public static func blinkingCursorStop() -> Ansi { return setLQ(12) } // /// Ps = 1 8 -> Print form feed (DECPFF). // public static func printFormFeedOn() -> Ansi // { // return setHQ(18) // } // // /// Ps = 1 8 -> Don't Print form feed (DECPFF). // public static func printFormFeedOff() -> Ansi // { // return setLQ(18) // } // /// Ps = 1 9 -> Set print extent to full screen (DECPEX). // public static func printExtentToFullscreen() -> Ansi // { // return setHQ(19) // } // // /// Ps = 1 9 -> Limit print to scrolling region (DECPEX). // public static func printExtentToScrollRegion() -> Ansi // { // return setLQ(19) // } /// Show Cursor (DECTCEM) /// /// Makes the cursor visible /// - returns: Ansi public static func cursorOn() -> Ansi { return setHQ(25) } /// Hide Cursor (DECTCEM) /// /// Makes the cursor not visible /// - returns: Ansi public static func cursorOff() -> Ansi { return setLQ(25) } /// Ps = 3 0 -> Show scrollbar (rxvt) /// /// - returns: Ansi public static func scrollbarOn() -> Ansi { return setHQ(30) } /// Ps = 3 0 -> Hide scrollbar (rxvt) /// /// - returns: Ansi public static func scrollbarOff() -> Ansi { return setLQ(30) } // /// Ps = 3 5 -> Enable font-shifting functions (rxvt). // public static func fontShiftingFunctionsOn() -> Ansi // { // return setHQ(35) // } // // /// Ps = 3 5 -> Disable font-shifting functions (rxvt). // public static func fontShiftingFunctionsOff() -> Ansi // { // return setLQ(35) // } // /// Ps = 3 8 -> Enter Tektronix Mode (DECTEK). // public static func tektronixOn() -> Ansi // { // return setHQ(38) // } // // /// Ps = 3 8 -> Disable Tektronix Mode (DECTEK). // public static func tektronixOff() -> Ansi // { // return setLQ(38) // } /// Ps = 4 0 -> Allow 80 -> 132 Mode /// /// - returns: Ansi public static func mode80To132On() -> Ansi { return setHQ(40) } /// Ps = 4 0 -> Disallow 80 -> 132 Mode /// /// - returns: Ansi public static func mode80To132Off() -> Ansi { return setLQ(40) } // /// Ps = 4 1 -> more(1) fix (see curses resource). // public static func moreFixOn() -> Ansi // { // return setHQ(41) // } // // /// Ps = 4 1 -> No more(1) fix (see curses resource). // public static func moreFixOff() -> Ansi // { // return setLQ(41) // } // /// Ps = 4 2 -> Enable National Replacement Character sets (DECNRCM). // public static func nationalReplacementCharactersetOn() -> Ansi // { // return setHQ(42) // } // // /// Ps = 4 2 -> Disable National Replacement Character sets (DECNRCM). // public static func nationalReplacementCharactersetOff() -> Ansi // { // return setLQ(42) // } // /// Ps = 4 4 -> Turn On Margin Bell. // public static func marginBellOn() -> Ansi // { // return setHQ(44) // } // // /// Ps = 4 4 -> Turn Off Margin Bell. // public static func marginBellOff() -> Ansi // { // return setLQ(44) // } // /// Ps = 4 5 -> Reverse-wraparound Mode. // public static func reverseWraparoundOn() -> Ansi // { // return setHQ(45) // } // // /// Ps = 4 5 -> NoReverse-wraparound Mode. // public static func reverseWraparoundOff() -> Ansi // { // return setLQ(45) // } // /// Ps = 4 6 -> Start Logging. This is normally disabled by a // /// compile-time option. // public static func loggingOn() -> Ansi // { // return setHQ(46) // } // // /// Ps = 4 6 -> Stop Logging. This is normally disabled by a // /// compile-time option. // public static func loggingOff() -> Ansi // { // return setLQ(46) // } /// Ps = 4 7 -> Use Normal Screen Buffer /// /// - returns: Ansi public static func screenBufferNormal() -> Ansi { return setHQ(47) } /// Ps = 4 7 -> Use Alternate Screen Buffer /// /// - returns: Ansi public static func screenBufferAlternate() -> Ansi { return setLQ(47) } // /// Ps = 6 6 -> Numeric keypad (DECNKM). // public static func keypadNumeric() -> Ansi // { // return setHQ(66) // } // // /// Ps = 6 6 -> Application keypad (DECNKM). // public static func keypadApplication() -> Ansi // { // return setLQ(66) // } /// Ps = 6 7 -> Backarrow key sends delete (DECBKM) /// /// - returns: Ansi public static func backarrowKeySendsDelete() -> Ansi { return setHQ(67) } /// Ps = 6 7 -> Backarrow key sends backspace (DECBKM) /// /// - returns: Ansi public static func backarrowKeySendsBackspace() -> Ansi { return setLQ(67) } // /// Ps = 6 9 -> Disable left and right margin mode (DECLRMM), // /// VT420 and up. // public static func leftRightMarginModeOff() -> Ansi // { // return setHQ(69) // } // // /// Ps = 6 9 -> Enable left and right margin mode (DECLRMM), // /// VT420 and up. // public static func leftRightMarginModeOn() -> Ansi // { // return setLQ(69) // } /// Ps = 9 5 -> Clear screen when DECCOLM is set/reset (DECNCSM) /// /// - returns: Ansi public static func clearWhenSetResetOn() -> Ansi { return setHQ(95) } /// Ps = 9 5 -> Do not clear screen when DECCOLM is set/reset (DECNCSM) /// /// - returns: Ansi public static func clearWhenSetResetOff() -> Ansi { return setLQ(95) } /// Ps = 1 0 0 0 -> Don't Send Mouse X & Y on button press and release /// /// - returns: Ansi public static func sendMouseXYOnButtonPressX11Off() -> Ansi { return setLQ(1000) } /// Ps = 1 0 0 0 -> Send Mouse X & Y on button press and release /// /// - returns: Ansi public static func sendMouseXYOnButtonPressX11On() -> Ansi { // return Ansi("\(Ansi.C1.CSI)?1000h") return setHQ(1000) } /// Ps = 1 0 0 1 -> Don't Use Hilite Mouse Tracking /// /// - returns: Ansi public static func hiliteMouseTrackingOff() -> Ansi { return setHQ(1001) } /// Ps = 1 0 0 1 -> Use Hilite Mouse Tracking /// /// - returns: Ansi public static func hiliteMouseTrackingOn() -> Ansi { return setLQ(1001) } /// Ps = 1 0 0 2 -> Don't Use Cell Motion Mouse Tracking /// /// - returns: Ansi public static func cellMouseTrackingOff() -> Ansi { return setHQ(1002) } /// Ps = 1 0 0 2 -> Use Cell Motion Mouse Tracking /// /// - returns: Ansi public static func cellMouseTrackingOn() -> Ansi { return setLQ(1002) } /// Ps = 1 0 0 3 -> Don't Use All Motion Mouse Tracking /// /// - returns: Ansi public static func allMouseTrackingOff() -> Ansi { return setHQ(1003) } /// Ps = 1 0 0 3 -> Use All Motion Mouse Tracking /// /// - returns: Ansi public static func allMouseTrackingOn() -> Ansi { return setLQ(1003) } // /// Ps = 1 0 0 4 -> Send FocusIn/FocusOut events. // public static func focusInOutEventsOn() -> Ansi // { // return setHQ(1004) // } // // /// Ps = 1 0 0 4 -> Don't Send FocusIn/FocusOut events. // public static func focusInOutEventsOff() -> Ansi // { // return setLQ(1004) // } /// Ps = 1 0 0 5 -> Enable UTF-8 Mouse Mode /// /// - returns: Ansi public static func utf8MouseModeOn() -> Ansi { return setHQ(1005) } /// Ps = 1 0 0 5 -> Disable UTF-8 Mouse Mode /// /// - returns: Ansi public static func utf8MouseModeOff() -> Ansi { return setLQ(1005) } /// Ps = 1 0 0 6 -> Enable SGR Mouse Mode /// /// - returns: Ansi public static func sgrMouseModeOn() -> Ansi { return setHQ(1006) } /// Ps = 1 0 0 6 -> Disable SGR Mouse Mode /// /// - returns: Ansi public static func sgrMouseModeOff() -> Ansi { return setLQ(1006) } /// Ps = 1 0 0 7 -> Enable Alternate Scroll Mode /// /// - returns: Ansi public static func alternateScrollOn() -> Ansi { return setHQ(1007) } /// Ps = 1 0 0 7 -> Disable Alternate Scroll Mode /// /// - returns: Ansi public static func alternateScrollOff() -> Ansi { return setLQ(1007) } /// Ps = 1 0 1 0 -> Scroll to bottom on tty output (rxvt) /// /// - returns: Ansi public static func scrollToBottomOnOutputOn() -> Ansi { return setHQ(1010) } /// Ps = 1 0 1 0 -> Don't Scroll to bottom on tty output (rxvt) /// /// - returns: Ansi public static func scrollToBottomOnOutputOff() -> Ansi { return setLQ(1010) } /// Ps = 1 0 1 1 -> Scroll to bottom on key press (rxvt) /// /// - returns: Ansi public static func scrollToBottomOnKeypressOn() -> Ansi { return setHQ(1011) } /// Ps = 1 0 1 1 -> Don't Scroll to bottom on key press (rxvt) /// /// - returns: Ansi public static func scrollToBottomOnKeypressOff() -> Ansi { return setLQ(1011) } /// Ps = 1 0 1 5 -> Enable urxvt Mouse Mode /// /// - returns: Ansi public static func urxvtMouseOn() -> Ansi { return setHQ(1015) } /// Ps = 1 0 1 5 -> Disable urxvt Mouse Mode /// /// - returns: Ansi public static func urxvtMouseOff() -> Ansi { return setLQ(1015) } // /// Ps = 1 0 3 4 -> Interpret "meta" key, sets eighth bit. // /// (enables the eightBitInput resource). // public static func interpretMetaKeyOn() -> Ansi // { // return setHQ(1034) // } // // /// Ps = 1 0 3 4 -> Don't interpret "meta" key, sets eighth bit. // /// (enables the eightBitInput resource). // public static func interpretMetaKeyOff() -> Ansi // { // return setLQ(1034) // } // /// Ps = 1 0 3 5 -> Enable special modifiers for Alt and Num- // /// Lock keys. (This enables the numLock resource). // public static func specialModifiersAltNumlockKeysOn() -> Ansi // { // return setHQ(1035) // } // // /// Ps = 1 0 3 5 -> Disable special modifiers for Alt and Num- // /// Lock keys. (This enables the numLock resource). // public static func specialModifiersAltNumlockKeysOff() -> Ansi // { // return setLQ(1035) // } // /// Ps = 1 0 3 6 -> Send ESC when Meta modifies a key. (This // /// enables the metaSendsEscape resource). // public static func sendESCWhenMetaModifiesKeysOn() -> Ansi // { // return setHQ(1036) // } // // /// Ps = 1 0 3 6 -> Don't Send ESC when Meta modifies a key. (This // /// enables the metaSendsEscape resource). // public static func sendESCWhenMetaModifiesKeysOff() -> Ansi // { // return setLQ(1036) // } // /// Ps = 1 0 3 7 -> Send DEL from the editing-keypad Delete key. // public static func keypadDeleteKeySendDEL4() -> Ansi // { // return setHQ(1037) // } // // /// Ps = 1 0 3 7 -> Send VT220 Remove from editing-keypad Delete key. // public static func keypadDeleteKeySendV220Remove() -> Ansi // { // return setLQ(1037) // } // /// Ps = 1 0 3 9 -> Send ESC when Alt modifies a key. (This // /// enables the altSendsEscape resource). // public static func sendESCWhenAltModifiesKeysOn() -> Ansi // { // return setHQ(1039) // } // // /// Ps = 1 0 3 9 -> Don't Send ESC when Alt modifies a key. (This // /// enables the altSendsEscape resource). // public static func sendESCWhenAltModifiesKeysOff() -> Ansi // { // return setLQ(1039) // } // /// Ps = 1 0 4 0 -> Keep selection even if not highlighted. // /// (This enables the keepSelection resource). // public static func keepSelectionOn() -> Ansi // { // return setHQ(1040) // } // // /// Ps = 1 0 4 0 -> Don't keep selection even if not highlighted. // /// (This enables the keepSelection resource). // public static func keepSelectionOff() -> Ansi // { // return setLQ(1040) // } // /// Ps = 1 0 4 1 -> Use the CLIPBOARD selection. (This enables // /// the selectToClipboard resource). // public static func useClipboardSelectionOn() -> Ansi // { // return setHQ(1041) // } // // /// Ps = 1 0 4 1 -> Use the PRIMARY selection. (This disables // /// the selectToClipboard resource). // public static func useClipboardSelectionOff() -> Ansi // { // return setLQ(1041) // } // /// Ps = 1 0 4 2 -> Enable Urgency window manager hint when // /// Control-G is received. (This enables the bellIsUrgent resource). // public static func urgencyWindowManagerHintOn() -> Ansi // { // return setHQ(1042) // } // // /// Ps = 1 0 4 2 -> Disable Urgency window manager hint when // /// Control-G is received. (This disables the bellIsUrgent resource). // public static func urgencyWindowManagerHintOff() -> Ansi // { // return setLQ(1042) // } // /// Ps = 1 0 4 3 -> Enable raising of the window when Control-G // /// is received. (enables the popOnBell resource). // public static func raisingOfWindowOn() -> Ansi // { // return setHQ(1043) // } // // /// Ps = 1 0 4 3 -> Disable raising of the window when Control-G // /// is received. (Disable the popOnBell resource). // public static func raisingOfWindowOff() -> Ansi // { // return setLQ(1043) // } // /// Use Alternate Screen Buffer 2, // /// clearing screen first if in the Alternate Screen. // /// (This may be disabled by the titeInhibit resource). // public static func screenBufferAlternate2() -> Ansi // { // return setHQ(1047) // } // // /// Use Normal Screen Buffer 2, // /// clearing screen first if in the Alternate Screen. // /// (This may be disabled by the titeInhibit resource). // public static func screenBufferNormal2() -> Ansi // { // return setLQ(1047) // } /// Ps = 1 0 4 8 -> Save cursor as in DECSC /// /// - returns: Ansi public static func cursorSave() -> Ansi { return setHQ(1048) } /// Ps = 1 0 4 8 -> Restore cursor as in DECSC /// /// - returns: Ansi public static func cursorRestore() -> Ansi { return setLQ(1048) } /// Ps = 1 0 4 9 -> Save cursor as in DECSC and use Alternate /// Screen Buffer, clearing it first. (This may be disabled by /// the titeInhibit resource). /// This combines the effects of the 1 0 4 7 and 1 0 4 8 modes. /// Use this with terminfo-based applications rather than the 4 7 mode /// /// - returns: Ansi public static func screenBufferAlternateCursorSave() -> Ansi { return setHQ(1049) } /// Ps = 1 0 4 9 -> Use Normal Screen Buffer and restore cursor /// as in DECRC. (This may be disabled by the titeInhibit /// resource). This combines the effects of the 1 0 4 7 and 1 0 4 8 /// modes. Use this with terminfo-based applications rather /// than the 4 7 mode /// /// - returns: Ansi public static func screenBufferNormalCursorRestore() -> Ansi { return setLQ(1049) } // /// Ps = 1 0 5 0 -> Set terminfo/termcap function-key mode. // public static func terminfoTermcapFunctionkeyOn() -> Ansi // { // return setHQ(1050) // } // // /// Ps = 1 0 5 0 -> Reset terminfo/termcap function-key mode. // public static func terminfoTermcapFunctionkeyOff() -> Ansi // { // return setLQ(1050) // } // /// Ps = 1 0 5 1 -> Set Sun function-key mode. // public static func sunFunctionkeyOn() -> Ansi // { // return setHQ(1051) // } // // /// Ps = 1 0 5 1 -> Reset Sun function-key mode. // public static func sunFunctionkeyOff() -> Ansi // { // return setLQ(1051) // } // /// Ps = 1 0 5 2 -> Set HP function-key mode. // public static func hpFunctionkeyOn() -> Ansi // { // return setHQ(1052) // } // // /// Ps = 1 0 5 2 -> Reset HP function-key mode. // public static func hpFunctionkeyOff() -> Ansi // { // return setLQ(1052) // } // /// Ps = 1 0 5 3 -> Set SCO function-key mode. // public static func scoFunctionkeyOn() -> Ansi // { // return setHQ(1053) // } // // /// Ps = 1 0 5 3 -> Reset SCO function-key mode. // public static func scoFunctionkeyOff() -> Ansi // { // return setLQ(1053) // } // /// Ps = 1 0 6 0 -> Set legacy keyboard emulation (X11R6). // public static func legacyKeyboardEmulationOn() -> Ansi // { // return setHQ(1060) // } // // /// Ps = 1 0 6 0 -> Reset legacy keyboard emulation (X11R6). // public static func legacyKeyboardEmulationOff() -> Ansi // { // return setLQ(1060) // } // /// Ps = 1 0 6 1 -> Set VT220 keyboard emulation. // public static func keyboardEmulationVT200() -> Ansi // { // return setHQ(1061) // } // // /// Ps = 1 0 6 1 -> Reset keyboard emulation to Sun/PC style.. // public static func keyboardEmulationPCStyle() -> Ansi // { // return setLQ(1061) // } // /// Ps = 2 0 0 4 -> Set bracketed paste mode. // public static func bracketedPasteOn() -> Ansi // { // return setHQ(2004) // } // // /// Ps = 2 0 0 4 -> Reset bracketed paste mode. // public static func bracketedPasteOff() -> Ansi // { // return setLQ(2004) // } } }
mit
4cc1cd65e368843d043684f7891ac26e
24.461951
77
0.532581
3.594492
false
false
false
false
nyin005/Forecast-App
Forecast/Forecast/HttpRequest/Model/Report/SummaryModel.swift
1
1435
// // SummaryModel.swift // Forecast // // Created by Perry Z Chen on 11/3/16. // Copyright © 2016 Perry Z Chen. All rights reserved. // import Foundation import ObjectMapper class SummaryListModel: Mappable { var msg: String var data: [SummaryDepartModel] required init?(map: Map) { self.msg = "" self.data = [SummaryDepartModel]() } func mapping(map: Map) { self.msg <- map["msg"] self.data <- map["data"] } } class SummaryDepartModel: Mappable { var department: String var reports: [SummaryTimeModel] required init?(map: Map) { self.department = "" self.reports = [SummaryTimeModel]() } func mapping(map: Map) { self.department <- map["department"] self.reports <- map["reports"] } } class SummaryTimeModel: Mappable { var date: String var values: [SummaryValueModel] required init?(map: Map) { self.date = "" self.values = [SummaryValueModel]() } func mapping(map: Map) { self.date <- map["date"] self.values <- map["values"] } } class SummaryValueModel: Mappable { var title: String var value: String required init?(map: Map) { self.title = "" self.value = "" } func mapping(map: Map) { self.title <- map["title"] self.value <- map["value"] } }
gpl-3.0
c582140321d8fabc75c8aa84b45694b0
18.643836
55
0.560669
3.875676
false
false
false
false
brentsimmons/Evergreen
iOS/Account/LocalAccountViewController.swift
1
1922
// // LocalAccountViewController.swift // NetNewsWire-iOS // // Created by Maurice Parker on 5/19/19. // Copyright © 2019 Ranchero Software. All rights reserved. // import UIKit import Account class LocalAccountViewController: UITableViewController { @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var footerLabel: UILabel! weak var delegate: AddAccountDismissDelegate? override func viewDidLoad() { super.viewDidLoad() setupFooter() navigationItem.title = Account.defaultLocalAccountName nameTextField.delegate = self tableView.register(ImageHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader") } private func setupFooter() { footerLabel.text = NSLocalizedString("Local accounts do not sync your feeds across devices.", comment: "Local") } @IBAction func cancel(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBAction func add(_ sender: Any) { let account = AccountManager.shared.createAccount(type: .onMyMac) account.name = nameTextField.text dismiss(animated: true, completion: nil) delegate?.dismiss() } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 0 ? ImageHeaderView.rowHeight : super.tableView(tableView, heightForHeaderInSection: section) } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as! ImageHeaderView headerView.imageView.image = AppAssets.image(for: .onMyMac) return headerView } else { return super.tableView(tableView, viewForHeaderInSection: section) } } } extension LocalAccountViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
mit
ea378c04dcf0add10ebb3614733dad87
28.553846
114
0.762624
4.336343
false
false
false
false
allevato/SwiftCGI
Tests/SwiftCGI/FCGIRequestHandlerTest.swift
1
4603
// Copyright 2015 Tony Allevato // // 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 SwiftCGI import XCTest /// Unit tests for the `FCGIRequestHandler` class. class FCGIRequestHandlerTest: XCTestCase { private var recordStream: TestOutputStream! private var inputStream: TestInputStream! private var outputStream: TestOutputStream! override func setUp() { recordStream = TestOutputStream() inputStream = TestInputStream() outputStream = TestOutputStream() } func testStart_withRequestRecords_shouldWriteResponseRecords() { let headers = [ "HTTP_METHOD": "POST" ] addTestRecord(1, body: .BeginRequest(role: .Responder, flags: [ .KeepConnection ])) addTestRecord(1, body: .Params(bytes: FCGIBytesFromNameValueDictionary(headers))) addTestRecord(1, body: .Params(bytes: [])) addTestRecord(1, body: .Stdin(bytes: Array("request body".utf8))) addTestRecord(1, body: .Stdin(bytes: [])) inputStream.testData = recordStream.testData let requestHandler = FCGIRequestHandler(inputStream: inputStream, outputStream: outputStream) { (request: HTTPRequest, var response: HTTPResponse) in XCTAssertNoThrow { // Verify some request properties. XCTAssertEqual(request.method, HTTPMethod.GET) let requestBody = try request.contentStream.readString() XCTAssertEqual(requestBody, "request body") // Write some response data. response.contentType = "text/plain" try response.contentStream.write("response body") } } XCTAssertNoThrow { try requestHandler.start() } // Create records that mimic the expected output so we can test the outcome. recordStream = TestOutputStream() addTestRecord(1, body: .Stdout(bytes: Array("Status: 200\ncontent-type: text/plain\n\nresponse body".utf8))) addTestRecord(1, body: .Stdout(bytes: [])) addTestRecord(1, body: .EndRequest(appStatus: 0, protocolStatus: .RequestComplete)) XCTAssertEqual(outputStream.testData, recordStream.testData) } func testStart_withUnexpectedRecordType_shouldThrowUnexpectedRecordType() { addTestRecord(1, body: .BeginRequest(role: .Responder, flags: [ .KeepConnection ])) addTestRecord(1, body: .GetValuesResult(bytes: [])) inputStream.testData = recordStream.testData let requestHandler = FCGIRequestHandler(inputStream: inputStream, outputStream: outputStream) { request, response in return } XCTAssertThrow(FCGIError.UnexpectedRecordType) { try requestHandler.start() } } func testStart_withMultipleBeginRequestRecords_shouldThrowUnexpectedRequestID() { addTestRecord(1, body: .BeginRequest(role: .Responder, flags: [ .KeepConnection ])) addTestRecord(1, body: .BeginRequest(role: .Responder, flags: [ .KeepConnection ])) inputStream.testData = recordStream.testData let requestHandler = FCGIRequestHandler(inputStream: inputStream, outputStream: outputStream) { request, response in return } XCTAssertThrow(FCGIError.UnexpectedRequestID) { try requestHandler.start() } } func testStart_withRecordsWithDifferentRequestIDs_shouldThrowUnexpectedRequestID() { addTestRecord(1, body: .BeginRequest(role: .Responder, flags: [ .KeepConnection ])) addTestRecord(2, body: .Params(bytes: [])) inputStream.testData = recordStream.testData let requestHandler = FCGIRequestHandler(inputStream: inputStream, outputStream: outputStream) { request, response in return } XCTAssertThrow(FCGIError.UnexpectedRequestID) { try requestHandler.start() } } /// Writes a record with the given body to the test stream. /// /// - Parameter requestID: The request ID to include in the record. /// - Parameter body: The body of the record. /// - Throws: `IOError` if there was an error writing the record to the test stream. private func addTestRecord(requestID: Int, body: FCGIRecordBody) { let record = FCGIRecord(requestID: requestID, body: body) XCTAssertNoThrow { try record.write(recordStream) } } }
apache-2.0
f5152260f242a2fb30a1e6bd84cd0209
36.422764
99
0.723224
4.658907
false
true
false
false
MA806P/SwiftDemo
SwiftTips/SwiftTips/SwiftAppTest/DispatchWorkItem.swift
1
1300
// // DispatchWorkItem.swift // SwiftAppTest // // Created by MA806P on 2018/12/22. // Copyright © 2018 myz. All rights reserved. // import Foundation typealias Task = (_ cancel: Bool) -> Void //“对于 block 的调用是同步行为。如果我们改变一下代码,将 block 放到一个 Dispatch 中去, //让它在 doWork 返回后被调用的话,我们就需要在 block 的类型前加上 @escaping 标记来表明这个闭包是会“逃逸”出该方法的: func delayBling(_ time: TimeInterval, task: @escaping()->()) -> Task? { func dispatch_later(block: @escaping ()->()) { let t = DispatchTime.now() + time DispatchQueue.main.asyncAfter(deadline: t, execute: block) } var closure :(()->Void)? = task var result: Task? let delayedClosure: Task = { cancel in if let internalClosure = closure { if (cancel == false) { DispatchQueue.main.async(execute: internalClosure) } } closure = nil result = nil } result = delayedClosure dispatch_later { if let delayedClosure = result { delayedClosure(false) } } return result } func canelBling(_ task: Task?) { task?(true) }
apache-2.0
7a919f4640938fbfdca001907b4c8fe4
20.641509
73
0.582389
3.888136
false
false
false
false
fireunit/login
Pods/Material/Sources/iOS/Material+UIImage+Crop.swift
2
2172
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Material nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit public extension UIImage { /** :name: crop */ public func crop(toWidth tw: CGFloat, toHeight th: CGFloat) -> UIImage? { let g: UIImage? let b: Bool = width > height let s: CGFloat = b ? th / height : tw / width let t: CGSize = CGSizeMake(tw, th) let w = width * s let h = height * s UIGraphicsBeginImageContext(t) drawInRect(b ? CGRectMake(-1 * (w - t.width) / 2, 0, w, h) : CGRectMake(0, -1 * (h - t.height) / 2, w, h), blendMode: .Normal, alpha: 1) g = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return g! } }
mit
4cdfd668f13c3390f8a6808ee4bed2a5
40
138
0.741713
4.044693
false
false
false
false
playbasis/native-sdk-ios
PlaybasisSDK/Classes/PBModel/PBPlayer.swift
1
1763
// // PBPlayer.swift // Playbook // // Created by Médéric Petit on 6/14/2559 BE. // Copyright © 2559 smartsoftasia. All rights reserved. // import ObjectMapper public class PBPlayer:PBModel { public var playerId:String! public var email:String? public var firstName:String? public var lastName:String? public var username:String? public var profilePictureUrl:String? public var profilePicture:UIImage? public var phoneNumber:String? public var customFields:[String:String]? public var goods:[PBReward] = [] public var badges:[PBBadge] = [] public var points:[PBPoint] = [] init(apiResponse:PBApiResponse) { super.init() Mapper<PBPlayer>().map(apiResponse.parsedJson!["player"], toObject: self) } public override init() { super.init() } required public init?(_ map: Map) { super.init(map) } override public func mapping(map: Map) { super.mapping(map) uid <- map["cl_player_id"] email <- map["email"] username <- map["username"] firstName <- map["first_name"] lastName <- map["last_name"] profilePictureUrl <- map["image"] customFields <- map["custom"] playerId <- map["cl_player_id"] goods <- map["goods"] badges <- map["badges"] points <- map["points"] phoneNumber <- map["phone_number"] } init(registerForm:PBRegisterForm) { super.init() self.email = registerForm.email self.username = registerForm.username self.playerId = registerForm.playerId self.profilePictureUrl = registerForm.profilePictureUrl self.customFields = registerForm.customFields } }
mit
6647fde1ba51084dcf6e3d267084ea3a
26.5
81
0.615909
4.303178
false
false
false
false
Pocketbrain/nativeadslib-ios
PocketMediaNativeAds/Core/NativeAdsConstants.swift
1
1622
// // Constants.swift // NativeAdsSwift // // Created by Carolina Barreiro Cancela on 15/06/15. // Copyright (c) 2015 Pocket Media. All rights reserved. // /** Information about the current platform/running device */ import UIKit import Foundation struct Platform { /** Utility method for deciding if using a real device or simulator - Returns: Bool indicating if using a real device or simulator true = Simulator false = Device */ static let isSimulator: Bool = { var isSim = false #if arch(i386) || arch(x86_64) isSim = true #endif return isSim }() } /** Contains constants for the NativeAds */ public struct NativeAdsConstants { /// Holds device information, about the device running this app. public struct Device { static let iosVersion = NSString(string: UIDevice.current.systemVersion).doubleValue static let model = UIDevice.current.model.characters.split { $0 == " " }.map { String($0) }[0] } /// Some config. public struct NativeAds { /// URL called to inform us about ads with bad end urls. Ones that make the user end up nowhere. public static let notifyBadAdsUrl = "https://nativeadsapi.pocketmedia.mobi/api.php" #if BETA /// The URL used to fetch the ads from. public static let baseURL = "https://getnativebeta.pocketmedia.mobi/ow.php?output=json" #else /// The URL used to fetch the ads from. public static let baseURL = "https://getnative.pocketmedia.mobi/ow.php?output=json" #endif } }
mit
b3c125d19723eea05ee4a6c97ea67de4
29.037037
104
0.644266
4.158974
false
false
false
false
cafielo/iOS_BigNerdRanch_5th
Chap13_Homepwner_bronze_silver_gold/Homepwner/ChangeDateViewController.swift
1
771
// // ChangeDateViewController.swift // Homepwner // // Created by Joonwon Lee on 8/7/16. // Copyright © 2016 Joonwon Lee. All rights reserved. // import UIKit class ChangeDateViewController: UIViewController { var item: Item! @IBOutlet weak var datePicker: UIDatePicker! let dateFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateStyle = .MediumStyle formatter.timeStyle = .NoStyle return formatter }() override func viewDidLoad() { super.viewDidLoad() datePicker.date = item.dateCreated } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) item.dateCreated = datePicker.date } }
mit
75d4b755015d8c33de4f6adbf23d2a7f
22.333333
54
0.651948
4.935897
false
false
false
false
wireapp/wire-ios
Wire-iOS Tests/CallQualityControllerTests.swift
1
8473
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import XCTest @testable import Wire final class CallQualityControllerTests: ZMSnapshotTestCase, CoreDataFixtureTestHelper { var sut: MockCallQualityController! var coreDataFixture: CoreDataFixture! var router: CallQualityRouterProtocolMock! var conversation: ZMConversation! var callConversationProvider: MockCallConversationProvider! var callQualityViewController: CallQualityViewController! override func setUp() { router = CallQualityRouterProtocolMock() coreDataFixture = CoreDataFixture() conversation = ZMConversation.createOtherUserConversation(moc: coreDataFixture.uiMOC, otherUser: otherUser) callConversationProvider = MockCallConversationProvider() sut = MockCallQualityController() sut.router = router let questionLabelText = NSLocalizedString("calling.quality_survey.question", comment: "") callQualityViewController = CallQualityViewController(questionLabelText: questionLabelText, callDuration: 10) callQualityViewController?.delegate = sut super.setUp() } override func tearDown() { coreDataFixture = nil sut = nil router = nil conversation = nil callConversationProvider = nil callQualityViewController = nil super.tearDown() } // MARK: - SurveyRequestValidation Tests func testSurveyRequestValidation() { sut.usesCallSurveyBudget = true // When the survey was never presented, it is possible to request it let initialDate = Date() CallQualityController.resetSurveyMuteFilter() XCTAssertTrue(sut.canRequestSurvey(at: initialDate)) CallQualityController.updateLastSurveyDate(initialDate) // During the mute time interval, it is not possible to request it let mutedRequestDate = Date() XCTAssertFalse(sut.canRequestSurvey(at: mutedRequestDate)) // After the mute time interval, it is not possible to request it let postMuteDate = mutedRequestDate.addingTimeInterval(2) XCTAssertTrue(sut.canRequestSurvey(at: postMuteDate, muteInterval: 1)) } // MARK: - SnapshotTests func testSurveyInterface() { CallQualityController.resetSurveyMuteFilter() verifyInAllDeviceSizes(view: callQualityViewController.view, configuration: configure) } // MARK: - CallQualitySurvey Presentation Tests func testThatCallQualitySurveyIsPresented_WhenCallStateIsTerminating_AndReasonIsNormal() { // GIVEN let establishedCallState: CallState = .established let terminatingCallState: CallState = .terminating(reason: .normal) conversation.remoteIdentifier = UUID() callConversationProvider.priorityCallConversation = conversation callQualityController_callCenterDidChange(callState: establishedCallState, conversation: conversation) // WHEN callQualityController_callCenterDidChange(callState: terminatingCallState, conversation: conversation) // THEN XCTAssertTrue(router.presentCallQualitySurveyIsCalled) } func testThatCallQualitySurveyIsPresented_WhenCallStateIsTerminating_AndReasonIsStillOngoing() { // GIVEN let establishedCallState: CallState = .established let terminatingCallState: CallState = .terminating(reason: .stillOngoing) conversation.remoteIdentifier = UUID() callConversationProvider.priorityCallConversation = conversation callQualityController_callCenterDidChange(callState: establishedCallState, conversation: conversation) // WHEN callQualityController_callCenterDidChange(callState: terminatingCallState, conversation: conversation) // THEN XCTAssertTrue(router.presentCallQualitySurveyIsCalled) } func testThatCallQualitySurveyIsNotPresented_WhenCallStateIsTerminating_AndReasonIsNotNormanlOrStillOngoing() { // GIVEN let establishedCallState: CallState = .established let terminatingCallState: CallState = .terminating(reason: .timeout) conversation.remoteIdentifier = UUID() callConversationProvider.priorityCallConversation = conversation callQualityController_callCenterDidChange(callState: establishedCallState, conversation: conversation) // WHEN callQualityController_callCenterDidChange(callState: terminatingCallState, conversation: conversation) // THEN XCTAssertFalse(router.presentCallQualitySurveyIsCalled) } func testThatCallQualitySurveyIsDismissed() { // WHEN callQualityViewController.delegate?.callQualityControllerDidFinishWithoutScore(callQualityViewController) // THEN XCTAssertTrue(router.dismissCallQualitySurveyIsCalled) } // MARK: - CallFailureDebugAlert Presentation Tests func testThatCallFailureDebugAlertIsPresented_WhenCallIsTerminated() { // GIVEN let establishedCallState: CallState = .established let terminatingCallState: CallState = .terminating(reason: .internalError) conversation.remoteIdentifier = UUID() callConversationProvider.priorityCallConversation = conversation callQualityController_callCenterDidChange(callState: establishedCallState, conversation: conversation) // WHEN callQualityController_callCenterDidChange(callState: terminatingCallState, conversation: conversation) // THEN XCTAssertTrue(router.presentCallFailureDebugAlertIsCalled) } func testThatCallFailureDebugAlertIsNotPresented_WhenCallIsTerminated() { // GIVEN let establishedCallState: CallState = .established let terminatingCallState: CallState = .terminating(reason: .anweredElsewhere) conversation.remoteIdentifier = UUID() callConversationProvider.priorityCallConversation = conversation callQualityController_callCenterDidChange(callState: establishedCallState, conversation: conversation) // WHEN callQualityController_callCenterDidChange(callState: terminatingCallState, conversation: conversation) // THEN XCTAssertFalse(router.presentCallFailureDebugAlertIsCalled) } } // MARK: - Helpers extension CallQualityControllerTests { private func configure(view: UIView, isTablet: Bool) { callQualityViewController?.dimmingView.alpha = 1 callQualityViewController?.updateLayout(isRegular: isTablet) } private func callQualityController_callCenterDidChange(callState: CallState, conversation: ZMConversation) { sut.callCenterDidChange(callState: callState, conversation: conversation, caller: otherUser, timestamp: nil, previousCallState: nil) } } // MARK: - ActiveCallRouterMock class CallQualityRouterProtocolMock: CallQualityRouterProtocol { var presentCallQualitySurveyIsCalled: Bool = false func presentCallQualitySurvey(with callDuration: TimeInterval) { presentCallQualitySurveyIsCalled = true } var dismissCallQualitySurveyIsCalled: Bool = false func dismissCallQualitySurvey(completion: Completion?) { dismissCallQualitySurveyIsCalled = true } var presentCallFailureDebugAlertIsCalled: Bool = false func presentCallFailureDebugAlert() { presentCallFailureDebugAlertIsCalled = true } func presentCallQualityRejection() { } } // MARK: - ActiveCallRouterMock class MockCallQualityController: CallQualityController { override var canPresentCallQualitySurvey: Bool { return true } }
gpl-3.0
31fe762542f4fd2473e303b4544b4b16
37.866972
117
0.727723
6.267012
false
true
false
false
mltbnz/pixelsynth
pixelsynth/UIImage+MetalImage.swift
1
2090
// // UIImage+Sugar.swift // pixelsynth // // Created by Malte Bünz on 05.05.17. // Copyright © 2017 Malte Bünz. All rights reserved. // import Foundation public extension UIImage { public func toMTLTexture() -> MTLTexture { let imageRef: CGImage = self.cgImage! let width: Int = imageRef.width let height: Int = imageRef.height let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceRGB() let rawData = malloc(height * width * 4)//byte let bytesPerPixel: Int = 4 let bytesPerRow: Int = bytesPerPixel * width let bitsPerComponent: Int = 8 let bitmapContext: CGContext = CGContext(data: rawData, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: (CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue))! bitmapContext.translateBy(x: 0, y: CGFloat(height)) bitmapContext.scaleBy(x: 1, y: -1) bitmapContext.draw(imageRef, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) let textureDescriptor: MTLTextureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm, width: width, height: height, mipmapped: false) let texture: MTLTexture = MTLCreateSystemDefaultDevice()!.makeTexture(descriptor: textureDescriptor)! let region: MTLRegion = MTLRegionMake2D(0, 0, width, height) texture.replace(region: region, mipmapLevel: 0, withBytes: rawData!, bytesPerRow: bytesPerRow) free(rawData) return texture } }
mit
00eae779345056687ca80ab96475f48a
45.377778
168
0.540968
5.81337
false
false
false
false
Rehsco/SnappingStepper
Sources/AutoRepeatHelper.swift
1
2606
/* * SnappingStepper * * Copyright 2015-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import Foundation final class AutoRepeatHelper { fileprivate var timer: Timer? fileprivate var autorepeatCount = 0 fileprivate var tickBlock: (() -> Void)? deinit { stop() } // MARK: - Managing Autorepeat func stop() { timer?.invalidate() } func start(autorepeatCount count: Int = 0, tickBlock block: @escaping () -> Void) { if let _timer = timer , _timer.isValid { return } autorepeatCount = count tickBlock = block repeatTick(nil) let newTimer = Timer(timeInterval: 0.1, target: self, selector: #selector(AutoRepeatHelper.repeatTick), userInfo: nil, repeats: true) timer = newTimer RunLoop.current.add(newTimer, forMode: RunLoopMode.commonModes) } @objc func repeatTick(_ sender: AnyObject?) { let needsIncrement: Bool if autorepeatCount < 35 { if autorepeatCount < 10 { needsIncrement = autorepeatCount % 5 == 0 } else if autorepeatCount < 20 { needsIncrement = autorepeatCount % 4 == 0 } else if autorepeatCount < 25 { needsIncrement = autorepeatCount % 3 == 0 } else if autorepeatCount < 30 { needsIncrement = autorepeatCount % 2 == 0 } else { needsIncrement = autorepeatCount % 1 == 0 } autorepeatCount += 1 } else { needsIncrement = true } if needsIncrement { tickBlock?() } } }
mit
aec35afdd3736d4e9a1b58e921ce2288
27.955556
137
0.677283
4.563923
false
false
false
false
volodg/LotterySRV
Sources/App/Models/PowerBallResult.swift
1
3459
import FluentProvider import CSwiftV import Foundation private extension Date { //example: 06/10/2017 private static var dateFormat: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.dateFormat = "MM/dd/yyyy" dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) return dateFormatter }() static func fromString(_ str: String) -> Date? { let result = dateFormat.date(from: str) return result } var toString: String { let result = Date.dateFormat.string(from: self) return result } } final class PowerBallResult: WithDrawDateModel, LotteryWithSpecialBall { let storage = Storage() /// The content of the post var winningNumbers: String//space separated result var drawDate: Date var megaBall: String var multiplier: String? /// Creates a new Post init(winningNumbers: String, drawDate: Date, megaBall: String, multiplier: String?) { self.winningNumbers = winningNumbers self.drawDate = drawDate self.megaBall = megaBall self.multiplier = multiplier } } // MARK: Fluent Preparation extension PowerBallResult: Preparation { /// Prepares a table/collection in the database /// for storing Posts static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.buildLotteryWithSpecialBall() } try setupInitialValues(database) } static func models(withData data: Data) throws -> [PowerBallResult] { struct SetupError: Error { let description: String } guard let content = String(data: Data(data), encoding: .utf8) else { throw SetupError(description: "invalid csv content") } let csv = CSwiftV(with: content, separator: " ", headers: nil) return csv.rows.map { rawWithEmpties -> PowerBallResult in let raw = rawWithEmpties.filter { !$0.isEmpty } let winningNumbers = raw[1...5].joined(separator: " ") let drawDate = Date.fromString(raw[0])! let megaBall = raw[6] let multiplier = raw.count > 7 ? raw[7] : nil let result = PowerBallResult(winningNumbers: winningNumbers, drawDate: drawDate, megaBall: megaBall, multiplier: multiplier) return result } } private static func setupInitialValues(_ database: Database) throws { let config = try Config() //https://data.ny.gov/Government-Finance/Lottery-Mega-Millions-Winning-Numbers-Beginning-20/5xaw-6ayf //all data: https://data.ny.gov/api/views/5xaw-6ayf/rows.json?accessType=DOWNLOAD let path = config.resourcesDir + "/PowerBall/" + "winnums-text.txt" let data = try DataFile.read(at: path) let models_ = try models(withData: Data(data)) try models_.reversed().forEach { entity in try entity.save() } } /// Undoes what was done in `prepare` static func revert(_ database: Database) throws { try database.delete(self) } } // MARK: JSON // How the model converts from / to JSON. // For example when: // - Creating a new Post (POST /posts) // - Fetching a post (GET /posts, GET /posts/:id) // extension PowerBallResult: JSONRepresentable { } // MARK: HTTP // This allows Post models to be returned // directly in route closures extension PowerBallResult: ResponseRepresentable { }
mit
8f443fdd4ccf21040cc13912cec1e7dc
28.067227
105
0.663487
4.307597
false
false
false
false
xeo-it/poggy
Poggy/Helpers/SlackHelper.swift
1
6829
// // SlackHelper.swift // Poggy // // Created by Francesco Pretelli on 10/05/16. // Copyright © 2016 Francesco Pretelli. All rights reserved. // import Foundation import Alamofire import ObjectMapper import AlamofireObjectMapper #if os (iOS) import OAuthSwift #endif class SlackHelper { enum channelType:String { case PUBLIC = "channels" case PRIVATE = "groups" } let OAUTH_ENDPOINT = "https://slack.com/oauth/authorize" let OUTH_TOKEN_ENDPOINT = "https://slack.com/api/oauth.access" let POGGY_OAUTH_CALLBACK_URL = "poggy://oauth-callback/slack" let PUBLIC_CHANNELS_ENDPOINT = "https://slack.com/api/channels.list?token=" let PRIVATE_CHANNELS_ENDPOINT = "https://slack.com/api/groups.list?token=" let USER_LIST_ENDPOINT = "https://slack.com/api/users.list?token=" let POST_MESSAGE_ENDPOINT = "https://slack.com/api/chat.postMessage?token=" let TEAM_INFO_ENDPOINT = "https://slack.com/api/team.info?token=" static let instance = SlackHelper() // singleton private init() { } // This prevents others from using the default '()' initializer for this class. #if os (iOS) //no need to authenticate from watch func authenticate(viewController:UIViewController, callback: (slackDetails: SlackAuthResponse?) -> Void) { let oauthswift = OAuth2Swift( consumerKey: getSlackConsumerKey(), consumerSecret: getSlackConsumerSecret(), authorizeUrl: OAUTH_ENDPOINT, accessTokenUrl: OUTH_TOKEN_ENDPOINT, responseType: "code" ) oauthswift.authorize_url_handler = SafariURLHandler(viewController: viewController, oauthSwift:oauthswift ) let state: String = generateStateWithLength(20) as String oauthswift.authorizeWithCallbackURL( NSURL(string: POGGY_OAUTH_CALLBACK_URL)!, scope: "channels:read groups:read users:read chat:write:user team:read", state: state, success: { credential, response, parameters in if let teamName = parameters["team_name"] as? String{ if let token = parameters["access_token"] as? String { self.saveAuthCredentials(teamName, token: token) callback(slackDetails: SlackAuthResponse(teamName: teamName, token: token)) } } }, failure: { error in NSLog(error.localizedDescription) }) } #endif private func saveAuthCredentials(teamName:String, token:String) { var newCredentials = [String: String]() if let savedCredentials = getAuthCredentials() { newCredentials = savedCredentials } newCredentials[teamName] = token NSUserDefaults.standardUserDefaults().setValue(newCredentials, forKey: PoggyConstants.SLACK_TEAMS_STORE_KEY) } func getAuthCredentials() -> [String: String]? { return NSUserDefaults.standardUserDefaults().valueForKey(PoggyConstants.SLACK_TEAMS_STORE_KEY) as? [String: String] } func setSlackConsumerKey(key:String) { NSUserDefaults.standardUserDefaults().setValue(key, forKey: PoggyConstants.SLACK_CONSUMER_KEY) } func getSlackConsumerKey() -> String { let key = NSUserDefaults.standardUserDefaults().valueForKey(PoggyConstants.SLACK_CONSUMER_KEY) return key != nil ? key as! String : "" } func setSlackConsumerSecret(key:String) { NSUserDefaults.standardUserDefaults().setValue(key, forKey: PoggyConstants.SLACK_CONSUMER_SECRET) } func getSlackConsumerSecret() -> String { let key = NSUserDefaults.standardUserDefaults().valueForKey(PoggyConstants.SLACK_CONSUMER_SECRET) return key != nil ? key as! String : "" } //MARK: - API Calls func getChannels(teamToken: String, type:channelType, callback: (data: [SlackChannel]?) -> Void) { let endpoint = type == .PUBLIC ? PUBLIC_CHANNELS_ENDPOINT + teamToken : PRIVATE_CHANNELS_ENDPOINT + teamToken sendRequestArray(endpoint, method: Method.GET, keyPath: type.rawValue) { (result: [SlackChannel]?) in callback(data: result) } } func getUsers(teamToken: String, callback: (data: [SlackUser]?) -> Void) { let endpoint = USER_LIST_ENDPOINT + teamToken sendRequestArray(endpoint, method: Method.GET, keyPath: "members") { (result: [SlackUser]?) in callback(data: result) } } func getTeamInfo(teamToken: String, callback: (data: SlackTeam?) -> Void) { let endpoint = TEAM_INFO_ENDPOINT + teamToken sendRequestObject(endpoint, method: Method.GET) { (result: SlackTeamResponse?) in callback(data: result?.teamInfo) } } func postMessage(teamToken: String, channelName: String, message: String, callback: (data: SlackMessageResponse?) -> Void) { let endpoint = "\(POST_MESSAGE_ENDPOINT)\(teamToken)&channel=\(channelName)&text=\(message)&pretty=1" sendRequestObject(endpoint, method: Method.POST) { (result: SlackMessageResponse?) in callback(data: result) } } private func sendRequestObject<T: Mappable>(endpoint: String, method: Alamofire.Method, headers: [String: String]? = nil, parameters: [String: AnyObject]? = nil, keyPath: String = "", encoding: ParameterEncoding? = .JSON, callback: (result: T?) -> Void) { // NSLog("API Calling sendRequestObject: " + endpoint) Alamofire.request(method, endpoint, headers: headers, parameters: parameters, encoding: encoding!).responseObject(keyPath: keyPath) { (response: Response<T, NSError>) in guard response.result.error == nil else { NSLog("error in API object request" + " -> " + String(response.result.error!)) callback(result: nil) return } callback(result: response.result.value!) } } private func sendRequestArray<T: Mappable>(endpoint: String, method: Alamofire.Method, headers: [String: String]? = nil, parameters: [String: AnyObject]? = nil, keyPath: String = "", encoding: ParameterEncoding? = .JSON, callback: (result: [T]?) -> Void) { Alamofire.request(method, endpoint, headers: headers).responseArray(keyPath: keyPath) { (response: Response < [T], NSError >) in guard response.result.error == nil else { NSLog("error in API array request" + " -> " + String(response.result.error!)) callback(result: nil) return } callback(result: response.result.value!) } } }
apache-2.0
bb20a852544340afb813610543c7fe0e
42.490446
261
0.633275
4.561122
false
false
false
false
FandyLiu/Cabin
Cabin/Extension/UIViewAdd.swift
1
869
// // UIViewAdd.swift // Cabin // // Created by QianTuFD on 2017/5/9. // Copyright © 2017年 fandy. All rights reserved. // import UIKit extension UIView { func screenViewYValue() -> CGFloat { var y: CGFloat = 0.0 var supView: UIView = self while let view = supView.superview { y += view.frame.origin.y if let scrollView = view as? UIScrollView { y -= scrollView.contentOffset.y } supView = view } return y } // 得出父 cell var superCell: UITableViewCell? { var superView: UIView? = self while (superView as? UITableViewCell) == nil { superView = superView?.superview if superView == nil { return nil } } return superView as? UITableViewCell } }
mit
401154d0cc3d5a8024ac19be419778e5
22.888889
55
0.533721
4.502618
false
false
false
false
ktatroe/MPA-Horatio
Horatio/Horatio/Classes/Operations/AlertOperation.swift
2
3461
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file shows how to present an alert as part of an operation. */ import UIKit public class AlertOperation: Operation { // MARK: Properties fileprivate let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .alert) fileprivate let presentationContext: UIViewController? public var title: String? { get { return alertController.title } set { alertController.title = newValue name = newValue } } public var message: String? { get { return alertController.message } set { alertController.message = newValue } } // MARK: Initialization public init(presentationContext: UIViewController? = nil) { self.presentationContext = presentationContext super.init() addCondition(AlertPresentation()) /* This operation modifies the view controller hierarchy. Doing this while other such operations are executing can lead to inconsistencies in UIKit. So, let's make them mutally exclusive. */ addCondition(MutuallyExclusive<UIViewController>()) } public func addAction(_ title: String, style: UIAlertAction.Style = .default, handler: @escaping (AlertOperation) -> Void = { _ in }) { let action = UIAlertAction(title: title, style: style) { [weak self] _ in if let strongSelf = self { handler(strongSelf) } self?.finish() } alertController.addAction(action) } override public func execute() { // it's probably not safe to even walk the view hierarchy from a background thread, so do this all on main DispatchQueue.main.async { var presentationContext = self.presentationContext if presentationContext == nil { // if no context is provided, use the root VC presentationContext = UIApplication.shared.keyWindow?.rootViewController // but if something is already presented there, walk down the hierarchy to find the leaf to present on while let presentedVC = presentationContext?.presentedViewController { presentationContext = presentedVC } } guard let presenter = presentationContext else { // this shouldn't be possible, but just in case self.finishWithError(NSError(code: .executionFailed, userInfo: [NSLocalizedDescriptionKey : "Alert operation failed because no presenter was found"])) return } if self.alertController.actions.isEmpty { self.addAction("OK") } if presenter.presentedViewController != nil { // presentation will fail if another VC is already presented, so error out the operation self.finishWithError(NSError(code: .executionFailed, userInfo: [NSLocalizedDescriptionKey : "Alert operation failed because presenter was already presenting another VC"])) } else { presenter.present(self.alertController, animated: true, completion: nil) } } } }
mit
a675811a9c417b783be6176f834c73fa
32.911765
139
0.612605
5.803691
false
false
false
false
NagiYan/NGKit
NGKit/Extension/UI/UIColor+NG.swift
1
3795
// // UIColor+NG.swift // NGKit // // Created by nagi on 16/8/9. // Copyright © 2016年 aria. All rights reserved. // import Foundation import UIKit public extension UIColor { /** 变化当前颜色的透明度,目前支持 WA 和 RGBA 两种模式 - parameter alpha: 目标透明度 - returns: 变化后的颜色 */ // func ng_makeAlpha(alpha:CGFloat) -> UIColor // { // let numberComponents = CGColorGetNumberOfComponents(self.CGColor) // let components = CGColorGetComponents(self.CGColor) // // switch numberComponents { // case 2: // return UIColor.init(white: components[0], alpha: alpha) // case 4: // return UIColor.init(red: components[0], green: components[1], blue: components[2], alpha: alpha) // default: // return self // } // } // use colorWithAlphaComponent /** 16进制RGB ARGB字符串转UIColor - parameter hexString: #ffffff ffffff 00ffffff - returns: UIColor */ static func ng_colorWith(_ hexString:String) -> UIColor { func colorComponentFrom(_ string:String, start:Int, length:Int) -> CGFloat { let substring = (string as NSString).substring(with: NSRange(location: start, length: length)) let fullHex = length == 2 ? substring : "\(substring)\(substring)" var hexComponent:UInt32 = 0 Scanner.init(string: fullHex).scanHexInt32(&hexComponent) return CGFloat(hexComponent) } var colorString = (hexString as NSString).replacingOccurrences(of: "#", with: "").uppercased() colorString = (colorString as NSString).replacingOccurrences(of: "0X", with: "").uppercased() var a:CGFloat = 1, r:CGFloat, g:CGFloat, b:CGFloat switch colorString.characters.count { case 3: r = colorComponentFrom(colorString, start: 0, length: 1) g = colorComponentFrom(colorString, start: 1, length: 1) b = colorComponentFrom(colorString, start: 2, length: 1) case 4: a = colorComponentFrom(colorString, start: 0, length: 1) r = colorComponentFrom(colorString, start: 1, length: 1) g = colorComponentFrom(colorString, start: 2, length: 1) b = colorComponentFrom(colorString, start: 3, length: 1) case 6: r = colorComponentFrom(colorString, start: 0, length: 2) g = colorComponentFrom(colorString, start: 2, length: 2) b = colorComponentFrom(colorString, start: 4, length: 2) case 8: a = colorComponentFrom(colorString, start: 0, length: 2) r = colorComponentFrom(colorString, start: 0, length: 2) g = colorComponentFrom(colorString, start: 2, length: 2) b = colorComponentFrom(colorString, start: 4, length: 2) default: return black } return RGBA(r, g: g, b: b, a: a) } //MARK:预设颜色 static func ngColorTextGrey() -> UIColor { struct sparam { static let color = RGBA(162, g: 162, b: 162, a: 1.0) } return sparam.color } static func ngColorTextGreyDark() -> UIColor { struct sparam { static let color = RGBA(132, g: 132, b: 132, a: 1.0) } return sparam.color } static func ngColorNaviBackground() -> UIColor { struct sparam { static let color = RGBA(248, g: 248, b: 248, a: 1.0) } return sparam.color } static func ngColorNaviLine() -> UIColor { struct sparam { static let color = RGBA(215, g: 215, b: 215, a: 1.0) } return sparam.color } }
mit
2c41412b3dec6b395fe8973cea33fd88
31.54386
110
0.578437
4.201586
false
false
false
false
serieuxchat/SwiftySRP
SwiftySRP/SRPProtocol.swift
1
9516
// // SRPProtocol.swift // SwiftySRP // // Created by Sergey A. Novitsky on 22/02/2017. // Copyright © 2017 Flock of Files. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation // SPR Design spec: http://srp.stanford.edu/design.html // SRP RFC: https://tools.ietf.org/html/rfc5054 // N A large safe prime (N = 2q+1, where q is prime) // All arithmetic is done modulo N. // // g A generator modulo N // k Multiplier parameter (k = H(N, g) in SRP-6a, k = 3 for legacy SRP-6) // s User's salt // I Username // p Cleartext Password // H() One-way hash function // ^ (Modular) Exponentiation // u Random scrambling parameter // a,b Secret ephemeral values // A,B Public ephemeral values // x Private key (derived from p and s) // v Password verifier // The host stores passwords using the following formula: // x = H(s, p) (s is chosen randomly) // v = g^x (computes password verifier) // The host then keeps {I, s, v} in its password database. The authentication protocol itself goes as follows: // User -> Host: I, A = g^a (identifies self, a = random number) // Host -> User: s, B = kv + g^b (sends salt, b = random number) // // Both: u = H(A, B) // // User: x = H(s, p) (user enters password) // NOTE: BouncyCastle does it differently because of the user name involved: // x = H(s | H(I | ":" | p)) (| means concatenation) // // User: S = (B - kg^x) ^ (a + ux) (computes session key) // User: K = H(S) // // Host: S = (Av^u) ^ b (computes session key) // Host: K = H(S) // Now the two parties have a shared, strong session key K. To complete authentication, they need to prove to each other that their keys match. One possible way: // User -> Host: M = H(H(N) xor H(g), H(I), s, A, B, K) // Host -> User: H(A, M, K) // The two parties also employ the following safeguards: // The user will abort if he receives B == 0 (mod N) or u == 0. // The host will abort if it detects that A == 0 (mod N). // The user must show his proof of K first. If the server detects that the user's proof is incorrect, it must abort without showing its own proof of K. public protocol SRPProtocol { /// Configuration for this protocol instance. var configuration: SRPConfiguration { get } /// Compute the verifier and client credentials. /// /// - Parameters: /// - s: SRP salt /// - I: User name /// - p: Password /// - Returns: SRPData with parameters v, x, a, and A populated. /// - Throws: SRPError if input parameters or configuration are not valid. func verifier(s: Data, I: Data, p: Data) throws -> SRPData /// Generate client credentials (parameters x, a, and A) from the SRP salt, user name (I), and password (p) /// /// - Parameters: /// - s: SRP salt /// - I: User name /// - p: Password /// - Returns: SRP data with parameters x, a, and A populated. /// - Throws: SRPError if input parameters or configuration are not valid. func generateClientCredentials(s: Data, I: Data, p: Data) throws -> SRPData /// Calculate the shared secret on the client side: S = (B - kg^x) ^ (a + ux) /// /// - Parameter srpData: SRP data to use in the calculation. /// Must have the following parameters populated and valid: B (received from the server), A (computed previously), a, x /// - Returns: SRPData with parameter S populated /// - Throws: SRPError if some of the input parameters is not set or invalid. func calculateClientSecret(srpData: SRPData) throws -> SRPData /// Compute the client evidence message. /// NOTE: This is different from the spec. above and is done the BouncyCastle way: /// M = H( pA | pB | pS), where pA, pB, and pS - padded values of A, B, and S /// - Parameter srpData: SRP data to use in the calculation. /// Must have the following fields populated: /// - a: Private ephemeral value a (per spec. above) /// - A: Public ephemeral value A (per spec. above) /// - x: Identity hash (computed the BouncyCastle way) /// - B: Server public ephemeral value B (per spec. above) /// - Returns: SRPData with the client evidence message populated. /// - Throws: SRPError if some of the required parameters are invalid. func clientEvidenceMessage(srpData: SRPData) throws -> SRPData /// Verify the client evidence message (received from the client) /// /// - Parameter srpData: SRPData with the following fields populated: A, B, clientM, serverS /// - Throws: SRPError in case verification fails or when some of the required parameters are invalid. func verifyClientEvidenceMessage(srpData: SRPData) throws /// Calculate the shared key (client side) in the standard way: sharedKey = H(clientS) /// /// - Parameter srpData: SRPData with clientS populated. /// - Returns: Shared key /// - Throws: SRPError if some of the required parameters is invalid. func calculateClientSharedKey(srpData: SRPData) throws -> Data /// Calculate the shared key (client side) by using HMAC: sharedKey = HMAC(salt, clientS) /// This version can be used to derive multiple shared keys from the same shared secret (by using different salts) /// - Parameter srpData: SRPData with clientS populated. /// - Returns: Shared key /// - Throws: SRPError if some of the required parameters is invalid. func calculateClientSharedKey(srpData: SRPData, salt: Data) throws -> Data /// Generate the server side SRP parameters. This method normally will NOT be used by the client. /// It's included here for testing purposes. /// - Parameter verifier: SRP verifier received from the client. /// - Returns: SRP data with parameters v, k, b, and B populated. /// - Throws: SRPError if the verifier or configuration is invalid. func generateServerCredentials(verifier: Data) throws -> SRPData /// Calculate the shared secret on the server side: S = (Av^u) ^ b /// /// - Parameter srpData: SRPData with the following parameters populated: A, v, b, B /// - Returns: SRPData with the computed u and serverS /// - Throws: SRPError if some of the required parameters are invalid. func calculateServerSecret(srpData: SRPData) throws -> SRPData /// Compute the server evidence message. /// NOTE: This is different from the spec above and is done the BouncyCastle way: /// M = H( pA | pMc | pS), where pA is the padded A value; pMc is the padded client evidence message, and pS is the padded shared secret. /// - Parameter srpData: SRP Data with the following fields populated: /// - A: Client value A /// - v: Password verifier v (per spec above) /// - b: Private ephemeral value b /// - B: Public ephemeral value B /// - clientM: Client evidence message /// - Returns: SRPData with the computed server evidence message field populated. /// - Throws: SRPError if some of the required parameters are invalid. func serverEvidenceMessage(srpData: SRPData) throws -> SRPData /// Verify the server evidence message (received from the server) /// /// - Parameter srpData: SRPData with the following fields populated: serverM, clientM, A, clientS /// - Throws: SRPError if verification fails or if some of the input parameters is invalid. func verifyServerEvidenceMessage(srpData: SRPData) throws /// Calculate the shared key (server side) in the standard way: sharedKey = H(serverS) /// /// - Parameter srpData: SRPData with serverS populated. /// - Returns: Shared key /// - Throws: SRPError if some of the required parameters is invalid. func calculateServerSharedKey(srpData: SRPData) throws -> Data /// Calculate the shared key (server side) by using HMAC: sharedKey = HMAC(salt, clientS) /// This version can be used to derive multiple shared keys from the same shared secret (by using different salts) /// - Parameter srpData: SRPData with clientS populated. /// - Returns: Shared key /// - Throws: SRPError if some of the required parameters is invalid. func calculateServerSharedKey(srpData: SRPData, salt: Data) throws -> Data }
mit
1167a01167c6b48194720899f7afb703
49.078947
164
0.661377
4.155022
false
false
false
false
lavenderofme/MySina
Sina/Sina/Classes/Home/LQYPresentationController.swift
1
1432
// // LQYPresentationController.swift // Sina // // Created by shasha on 15/11/11. // Copyright © 2015年 shasha. All rights reserved. // import UIKit class LQYPresentationController: UIPresentationController { /** 记录菜单的尺寸 */ var presentedFrame = CGRectZero /** 布局被弹出的控制器 */ override func containerViewWillLayoutSubviews() { super.containerViewWillLayoutSubviews() // containerView 容器视图 (所有被展现的内容都再容器视图上) // presentedView() 被展现的视图(当前就是弹出菜单控制器的view) // 1.添加一个蒙版 containerView?.insertSubview(cover, atIndex: 0) cover.frame = containerView!.bounds // 2.修改被展现控件的尺寸 presentedView()?.frame = presentedFrame } // MARK: - 懒加载 private lazy var cover: UIView = { // 1.创建蒙版 let coverView = UIView() coverView.backgroundColor = UIColor(white: 0.8, alpha: 0.5) // 2.添加手势 coverView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("coverClick"))) return coverView }() // MARK: - 内部控制方法 @objc func coverClick() { presentedViewController.dismissViewControllerAnimated(true, completion: nil) } }
apache-2.0
d2b2b5275b2c275ad7a2566774a87b0a
23.647059
108
0.610979
4.779468
false
false
false
false
codepgq/WeiBoDemo
PQWeiboDemo/PQWeiboDemo/classes/Tools 工具/TBDataSource.swift
1
3009
// // TBDataSource.swift // CustomPullToRefresh // // Created by ios on 16/9/26. // Copyright © 2016年 ios. All rights reserved. // import UIKit /** 设置Section样式,默认 Single */ public enum TBSectionStyle : Int { ///Default 默认没有多个Section case Section_Single /// 有多个Section case Section_Has } class TBDataSource: NSObject,UITableViewDataSource { private var sectionStyle : TBSectionStyle = .Section_Single private var data : NSArray? private var identifier : String = "null" private var cellBlock : ((_ cell : AnyObject, _ item : AnyObject) -> ())? /** 快速创建一个数据源,需要提前注册,数组和style要对应 - parameter identifier: 标识 - parameter data: 数据 - parameter style: 类型 - parameter cell: 回调 - returns: 数据源对象(dataSource) */ class func cellIdentifierWith(identifier : String , data : NSArray , style : TBSectionStyle , cell : @escaping ((_ cell : AnyObject, _ item : AnyObject) -> Void)) -> TBDataSource { let source = TBDataSource() source.sectionStyle = style source.data = data source.identifier = identifier source.cellBlock = cell return source } /** 返回数据 - parameter indexPath: indexPath - returns: 数据 */ private func itemWithIndexPath(indexPath : NSIndexPath) -> AnyObject{ if sectionStyle == .Section_Single { return data![indexPath.row] as AnyObject } else{ return (data![indexPath.section] as! Array)[indexPath.row] } } /** 返回有多少个Section - parameter tableView: tableView - returns: section */ private func numberOfSectionsInTableView(tableView: UITableView) -> Int { if sectionStyle == .Section_Single { return 1 } return (data?.count)! } /** 返回对应Section的rows - parameter tableView: tableView - parameter section: section - returns: rows */ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ if sectionStyle == .Section_Single { return (data?.count)! }else{ return ((data?[section] as AnyObject).count)! } } /** 返回cell,并用闭包把cell封装到外面,提供样式设置 - parameter tableView: tableView - parameter indexPath: indexPath - returns: cell */ func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) if let block = cellBlock { block(cell, itemWithIndexPath(indexPath: indexPath as NSIndexPath)) } return cell } }
mit
c150c10ec1791d9be5381ebf7172f6f8
24.709091
184
0.591938
4.850772
false
false
false
false
gokush/GKAddressKit
GKAddressKitExample/ViewController.swift
1
7159
// // ViewController.swift // GKAddressKit // // Created by 童小波 on 15/1/19. // Copyright (c) 2015年 tongxiaobo. All rights reserved. // import UIKit class ViewController: UIViewController, FetchedResultsControllerDataSourceDelegate { @IBOutlet weak var tableView: UITableView! var fetchedResultControllerDataSource: FetchedResultsControllerDataSource? var provinces:NSArray?; let service:GKAddressService = GKAddressContainerImpl().addressService() let addressRepository = AddressRepository.sharedInstance override func viewDidLoad() { super.viewDidLoad() let controller:AddressEditController = AddressEditController() controller.service = GKAddressContainerMock().addressService() self.navigationController?.pushViewController(controller, animated: true) // let province = addressRepository.findProvinceWithId(2) // println(province?.name) // // let city = addressRepository.findCityWithId(21, province: province!) // println(city?.name) // // let district = addressRepository.findDistrict(212, city: city!) // println(district?.name) refreshDate() let address = GKAddress() let province = GKProvince() province.provinceID = 2 let city = GKCity() city.cityID = 21 let county = GKCounty() county.countyID = 212 address.userID = 1 address.addressID = 1 address.localID = 101 address.name = "tong" address.cellPhone = "1312099999999" address.postcode = "321300" address.address = "昌平路700号" address.isDefault = true address.province = province address.city = city address.county = county address.synchronization = GKAddressSynchronizationSending() addressRepository.create(address).subscribeNext({ (success) -> Void in println(success) }, error: { (error) -> Void in println("error") }) let user = GKUser() user.userID = 1 addressRepository.findAddressesWithUser(user).subscribeNext({ (addresses) -> Void in let aAddresses = addresses as [GKAddress] for item in aAddresses{ print("\(item.localID) \(item.synchronization.description) ") println(item.address) } }, error: { (error) -> Void in }) let add = GKAddress() add.userID = 1 add.localID = 3 add.addressID = 1010 add.synchronization = GKAddressSynchronizationSuccess() addressRepository.updatePrimary(add).subscribeNext({ (address) -> Void in let aAddress = address as GKAddress println(aAddress.localID) }, error: { (errors) -> Void in let aErrors = errors as NSError println(aErrors.domain) }) // println("***************") // // addressRepository.findAddressesWithUser(user).subscribeNext({ (addresses) -> Void in // // let aAddresses = addresses as [GKAddress] // for item in aAddresses{ // print("\(item.localID) \(item.synchronization.description) ") // println(item.address) // } // // }, error: { (error) -> Void in // // }) // self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: UIBarButtonItemStyle.Plain, target: self, action: "addAddressButtonClick:") // self.tableView.tableFooterView = UIView() // // refreshDate() // setupFetchedResultsControllerDataSource() // // let provinces = AddressRepository.sharedInstance.fetchProvinces() // let province = AddressRepository.sharedInstance.findProvinceWithId(1) // println(province?.name) // for item in provinces{ // print("\(item.name) ") // println(item.addresses.count) // let cities = item.cities.allObjects as [CityEntity] // for item in cities{ // print(" ") // println(item.name) // let districts = item.districts.allObjects as [DistrictEntity] // for item in districts{ // print(" ") // println(item.name) // } // } // } // println("************************") // let districts = AddressRepository.sharedInstance.fetchDistricts() // if districts != nil{ // for item in districts!{ // println(item.name) // } // } // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func addAddressButtonClick(sender: UIBarButtonItem){ let addressEditViewController = AddressEditViewController() self.performSegueWithIdentifier("editAddress", sender: self) } func refreshDate(){ let jsonPath = NSBundle.mainBundle().pathForResource("province", ofType: "json") let jsonData = NSData(contentsOfFile: jsonPath!) let jsonArray = NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers, error: nil) as [AnyObject] //测试更新时间 // var tpstart = timeval(tv_sec: 0, tv_usec: 0) // var tpend = timeval(tv_sec: 0, tv_usec: 0) // gettimeofday(&tpstart, nil) AddressRepository.sharedInstance.updateProvince(jsonArray) // gettimeofday(&tpend, nil) // println(tpend.tv_usec - tpstart.tv_usec) } func setupFetchedResultsControllerDataSource(){ self.fetchedResultControllerDataSource = FetchedResultsControllerDataSource(tableView: self.tableView) self.fetchedResultControllerDataSource?.fetchedResultsController = AddressRepository.sharedInstance.fetchedResultsController() self.fetchedResultControllerDataSource?.delegate = self self.fetchedResultControllerDataSource?.reuseIdentifier = "AddressCellIdentity" } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { } func configureCell(cell: AnyObject, withObject: AnyObject) { let addressCell = cell as AddressCell let address = withObject as AddressEntity addressCell.textLabel?.numberOfLines = 3 addressCell.textLabel?.text = "\(address.name) \(address.cellphone)\n\(address.province.name)\(address.city.name)\(address.district.name)" } func deleteObject(object: AnyObject) { let address = object as AddressEntity // AddressRepository.sharedInstance.deleteAddress(address) } }
mit
180328f20c02aaf403c2a91ab4556f1a
34.834171
163
0.59613
5.046709
false
false
false
false
dreamsxin/swift
validation-test/compiler_crashers_fixed/02115-vtable.swift
11
613
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse protocol a { protocol a { } typealias R = A, Any) -> { }) func f<T -> (x(Range<U -> { case A? = [" typealias f == d struct D : b) -> T : c { extension NSData { } } typealias R = { _, V>() } func a: (x: Sequence, f() func
apache-2.0
79b3f092849103c8241dc71f09cd25ca
24.541667
78
0.670473
3.278075
false
false
false
false
Swift-Flow/CounterExample
Carthage/Checkouts/ReSwift/[email protected]
3
417
// swift-tools-version:5.0 import PackageDescription let pkg = Package(name: "ReSwift") pkg.platforms = [ .macOS(.v10_10), .iOS(.v8), .tvOS(.v9), .watchOS(.v2) ] pkg.products = [ .library(name: "ReSwift", targets: ["ReSwift"]) ] let pmk: Target = .target(name: "ReSwift") pmk.path = "ReSwift" pkg.targets = [ pmk, .testTarget(name: "ReSwiftTests", dependencies: ["ReSwift"], path: "ReSwiftTests") ]
mit
383e245f34db42ca78fca0fad306e099
23.529412
86
0.645084
2.957447
false
true
false
false
cenfoiOS/ImpesaiOSCourse
CleanSwiftExample/CleanSwiftExample/Scenes/ToDoTasksList/ToDoTasksListRouter.swift
1
2210
// // ToDoTasksListRouter.swift // CleanSwiftExample // // Created by Cesar Brenes on 6/6/17. // Copyright (c) 2017 César Brenes Solano. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit protocol ToDoTasksListRouterInput{ func navigateToSomewhere() } class ToDoTasksListRouter: ToDoTasksListRouterInput{ weak var viewController: ToDoTasksListViewController! // MARK: Navigation func navigateToSomewhere(){ // NOTE: Teach the router how to navigate to another scene. Some examples follow: // 1. Trigger a storyboard segue // viewController.performSegueWithIdentifier("ShowSomewhereScene", sender: nil) // 2. Present another view controller programmatically // viewController.presentViewController(someWhereViewController, animated: true, completion: nil) // 3. Ask the navigation controller to push another view controller onto the stack // viewController.navigationController?.pushViewController(someWhereViewController, animated: true) // 4. Present a view controller from a different storyboard // let storyboard = UIStoryboard(name: "OtherThanMain", bundle: nil) // let someWhereViewController = storyboard.instantiateInitialViewController() as! SomeWhereViewController // viewController.navigationController?.pushViewController(someWhereViewController, animated: true) } // MARK: Communication func passDataToNextScene(segue: UIStoryboardSegue){ // NOTE: Teach the router which scenes it can communicate with if segue.identifier == "ShowSomewhereScene" { passDataToSomewhereScene(segue: segue) } } func passDataToSomewhereScene(segue: UIStoryboardSegue){ // NOTE: Teach the router how to pass data to the next scene // let someWhereViewController = segue.destinationViewController as! SomeWhereViewController // someWhereViewController.output.name = viewController.output.name } }
mit
25cc084ae667cbdbc1716421d938212e
37.754386
114
0.707107
5.859416
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/00713-swift-declcontext-lookupqualified.swift
1
1072
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck // Distribu where D.C == E> {s func c() { } func f<g>() -> (g, g -> g) -> g { d j d.i = { } { g) { h } } protocol f { } protocol A { -func b<d>(a : d) -> c { {}ol !(a) } } func c<d { enum c { } } func a<T>() { enum b { } } func i(c: () -> ()) { } class a { var _ = i() { } } class a<f : b, g : b where f.d == g> { } protocol b { } struct c<h : b> : b { typealias e = a<c<h>0) { } protocol a : a { } class a { } struct A<T> { } func f<g>() -> (g, g -> g) -> g { d j d.i = { } { g) { } } ny, Any) -> Any) -> Any)) -> Any { return z({ }) } func prefix(with: String) -> <T>(() -> T return "\(with): \(g())" } } struct c<S: Sequence, T where Optional<T> == S.Iterator.Element>
apache-2.0
3821314612c0fa19e566e919614a2eac
16.015873
79
0.557836
2.516432
false
false
false
false
darknoon/CookieCutterCutter
CookieCutterCutter/CookieCutterCutter/Util.swift
1
4145
// // Util.swift // CookieCutterCutter // // Created by Elizabeth Salazar on 8/23/14. // // import Foundation import UIKit import SceneKit func - (firstVector: SCNVector3, secondVector: SCNVector3) -> SCNVector3 { let x = firstVector.x - secondVector.x let y = firstVector.y - secondVector.y let z = firstVector.z - secondVector.z return SCNVector3(x: x, y: y, z: z) } func + (firstVector: SCNVector3, secondVector: SCNVector3) -> SCNVector3 { let x = firstVector.x + secondVector.x let y = firstVector.y + secondVector.y let z = firstVector.z + secondVector.z return SCNVector3(x: x, y: y, z: z) } func * (quat1: SCNQuaternion, quat2: SCNQuaternion) -> SCNQuaternion { let nx = (quat1.x * quat2.x - quat1.y * quat2.y - quat1.z * quat2.z - quat1.w * quat2.w) let ny = (quat1.x * quat2.y - quat1.y * quat2.x - quat1.z * quat2.w - quat1.w * quat2.z) let nz = (quat1.x * quat2.z - quat1.y * quat2.w - quat1.z * quat2.x - quat1.w * quat2.y) let nw = (quat1.x * quat2.w - quat1.y * quat2.z - quat1.z * quat2.y - quat1.w * quat2.x) return SCNQuaternion(x: nx, y: ny, z: nz, w: nw) } func * (a: SCNVector3, k: Float) -> SCNVector3 { return SCNVector3(x: a.x * k, y: a.y * k, z: a.z * k) } func * (k: Float, a: SCNVector3) -> SCNVector3 { return SCNVector3(x: a.x * k, y: a.y * k, z: a.z * k) } func normalize(vector: SCNVector3) -> SCNVector3 { let len = length(vector) let x = vector.x/len let y = vector.y/len let z = vector.z/len return SCNVector3(x: x, y: y, z: z) } func normalize(quat: SCNQuaternion) -> SCNQuaternion { let len = length(quat) let x = quat.x/len let y = quat.y/len let z = quat.z/len let w = quat.w/len return SCNQuaternion(x: x, y: y, z: z, w: w) } extension SCNVector4 : Printable { public var description : String { return "vector.x: \(self.x) vector.y: \(self.y) vector.z: \(self.z))" } } func length(vector: SCNVector3) -> Float { return sqrt((vector.x * vector.x) + (vector.y * vector.y) + (vector.z * vector.z)) } func length(quat: SCNQuaternion) -> Float { return sqrt((quat.x * quat.x) + (quat.y * quat.y) + (quat.z * quat.z) + (quat.w * quat.w)) } //func normalize(vector: SCNVector3) -> SCNVector3 //{ // return normalizeVector(vector, length(vector)) //} func cross(firstVector: SCNVector3, secondVector: SCNVector3) -> SCNVector3 { let x = (firstVector.y * secondVector.z) - (firstVector.z * secondVector.y) let y = (firstVector.z * secondVector.x) - (firstVector.x * secondVector.z) let z = (firstVector.x * secondVector.y) - (firstVector.y * secondVector.x) return SCNVector3(x: x, y: y, z: z) } func dot(firstVector: SCNVector3, secondVector: SCNVector3) -> Float { return (firstVector.x * secondVector.x) + (firstVector.y * secondVector.y) + (firstVector.z * secondVector.z) } extension SCNQuaternion { init(axis: SCNVector3, angle: Float) { let sinAngle = sin(angle/2) let qx = axis.x * sinAngle let qy = axis.y * sinAngle let qz = axis.z * sinAngle let qw = cos(angle/2) self = SCNQuaternion(x: qx, y: qy, z: qz, w: qw) } } func + (ss: CGPoint, other: CGPoint) -> CGPoint { return CGPoint(x: ss.x + other.x, y: ss.y + other.y) } func - (ss: CGPoint, other: CGPoint) -> CGPoint { return CGPoint(x: ss.x - other.x, y: ss.y - other.y) } func * (a: CGPoint, k: CGFloat) -> CGPoint { return CGPoint(x: a.x * k, y: a.y * k) } func norm(v : CGPoint) -> CGPoint { let length = sqrt(v.x * v.x + v.y * v.y) if (length < 0.00001) { return CGPointZero } return CGPoint(x: v.x / length, y: v.y / length) } func inv (p: SCNVector3) -> SCNVector3 { return SCNVector3(x: p.y, y: -p.x, z:p.z) } extension SCNVector3 { init (_ p : CGPoint) { self = SCNVector3(x: Float(p.x), y: Float(p.y), z: 0) } init (_ p : CGPoint, z: CGFloat) { self = SCNVector3(x: Float(p.x), y: Float(p.y), z: Float(z)) } func length() -> Float { return sqrt(self.x * self.x + self.y * self.y + self.z * self.z) } } func modulo(a : Int, b : Int) -> Int { let r = a % b return r > 0 ? r : -r }
mit
95364bbbc3829fbd60c1a11d0b21b2a5
25.069182
113
0.612304
2.785618
false
false
false
false
darrinhenein/firefox-ios
Client/Frontend/Browser/BrowserLocationView.swift
1
8779
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit protocol BrowserLocationViewDelegate { func browserLocationViewDidTapLocation(browserLocationView: BrowserLocationView) func browserLocationViewDidTapReaderMode(browserLocationView: BrowserLocationView) func browserLocationViewDidTapStop(browserLocationView: BrowserLocationView) func browserLocationViewDidTapReload(browserLocationView: BrowserLocationView) } let ImageReload = UIImage(named: "toolbar_reload.png") let ImageStop = UIImage(named: "toolbar_stop.png") class BrowserLocationView : UIView, UIGestureRecognizerDelegate { var delegate: BrowserLocationViewDelegate? private var lockImageView: UIImageView! private var locationLabel: UILabel! private var stopReloadButton: UIButton! private var readerModeButton: ReaderModeButton! var readerModeButtonWidthConstraint: NSLayoutConstraint? override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.whiteColor() self.layer.cornerRadius = 3 lockImageView = UIImageView(image: UIImage(named: "lock_verified.png")) lockImageView.hidden = false lockImageView.isAccessibilityElement = true lockImageView.accessibilityLabel = NSLocalizedString("Secure connection", comment: "") addSubview(lockImageView) locationLabel = UILabel() locationLabel.font = UIFont(name: "HelveticaNeue-Light", size: 12) locationLabel.lineBreakMode = .ByClipping locationLabel.userInteractionEnabled = true // TODO: This label isn't useful for people. We probably want this to be the page title or URL (see Safari). locationLabel.accessibilityLabel = NSLocalizedString("URL", comment: "Accessibility label") addSubview(locationLabel) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "SELtapLocationLabel:") locationLabel.addGestureRecognizer(tapGestureRecognizer) stopReloadButton = UIButton() stopReloadButton.setImage(ImageReload, forState: .Normal) stopReloadButton.addTarget(self, action: "SELtapStopReload", forControlEvents: .TouchUpInside) addSubview(stopReloadButton) readerModeButton = ReaderModeButton(frame: CGRectZero) readerModeButton.hidden = true readerModeButton.addTarget(self, action: "SELtapReaderModeButton", forControlEvents: .TouchUpInside) addSubview(readerModeButton) makeConstraints() } private func makeConstraints() { let container = self lockImageView.snp_remakeConstraints { make in make.centerY.equalTo(container).centerY make.leading.equalTo(container).with.offset(8) make.width.equalTo(self.lockImageView.intrinsicContentSize().width) } locationLabel.snp_remakeConstraints { make in make.centerY.equalTo(container.snp_centerY) if self.url?.scheme == "https" { make.leading.equalTo(self.lockImageView.snp_trailing).with.offset(8) } else { make.leading.equalTo(container).with.offset(8) } if self.readerModeButton.readerModeState == ReaderModeState.Unavailable { make.trailing.equalTo(self.stopReloadButton.snp_leading).with.offset(-8) } else { make.trailing.equalTo(self.readerModeButton.snp_leading).with.offset(-8) } } stopReloadButton.snp_remakeConstraints { make in make.centerY.equalTo(container).centerY make.trailing.equalTo(container).with.offset(-4) make.size.equalTo(20) } readerModeButton.snp_remakeConstraints { make in make.centerY.equalTo(container).centerY make.trailing.equalTo(self.stopReloadButton.snp_leading).offset(-4) // We fix the width of the button (to the height of the view) to prevent content // compression when the locationLabel has more text contents than will fit. It // would be nice to do this with a content compression priority but that does // not seem to work. make.width.equalTo(container.snp_height) } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func intrinsicContentSize() -> CGSize { return CGSize(width: 200, height: 28) } func SELtapLocationLabel(recognizer: UITapGestureRecognizer) { delegate?.browserLocationViewDidTapLocation(self) } func SELtapReaderModeButton() { delegate?.browserLocationViewDidTapReaderMode(self) } func SELtapStopReload() { if loading { delegate?.browserLocationViewDidTapStop(self) } else { delegate?.browserLocationViewDidTapReload(self) } } var url: NSURL? { didSet { lockImageView.hidden = (url?.scheme != "https") let t = url?.absoluteString if t?.hasPrefix("http://") ?? false { locationLabel.text = t!.substringFromIndex(advance(t!.startIndex, 7)) } else if t?.hasPrefix("https://") ?? false { locationLabel.text = t!.substringFromIndex(advance(t!.startIndex, 8)) } else if t == "about:home" { let placeholderText = NSLocalizedString("Search or enter address", comment: "The text shown in the URL bar on about:home") locationLabel.attributedText = NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.grayColor()]) } else { locationLabel.text = t } makeConstraints() } } var loading: Bool = false { didSet { if loading { stopReloadButton.setImage(ImageStop, forState: .Normal) } else { stopReloadButton.setImage(ImageReload, forState: .Normal) } } } var readerModeState: ReaderModeState { get { return readerModeButton.readerModeState } set (newReaderModeState) { if newReaderModeState != self.readerModeButton.readerModeState { self.readerModeButton.readerModeState = newReaderModeState makeConstraints() readerModeButton.hidden = (newReaderModeState == ReaderModeState.Unavailable) UIView.animateWithDuration(0.1, animations: { () -> Void in if newReaderModeState == ReaderModeState.Unavailable { self.readerModeButton.alpha = 0.0 } else { self.readerModeButton.alpha = 1.0 } self.layoutIfNeeded() }) } } } override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { // We only care about the horizontal position of this touch. Find the first // subview that takes up that space and return it. for view in subviews { let x1 = view.frame.origin.x let x2 = x1 + view.frame.width if point.x >= x1 && point.x <= x2 { return view as? UIView } } return nil } } private class ReaderModeButton: UIButton { override init(frame: CGRect) { super.init(frame: frame) setImage(UIImage(named: "reader.png"), forState: UIControlState.Normal) setImage(UIImage(named: "reader_active.png"), forState: UIControlState.Selected) accessibilityLabel = NSLocalizedString("Reader", comment: "Browser function that presents simplified version of the page with bigger text.") } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var _readerModeState: ReaderModeState = ReaderModeState.Unavailable var readerModeState: ReaderModeState { get { return _readerModeState; } set (newReaderModeState) { _readerModeState = newReaderModeState switch _readerModeState { case .Available: self.enabled = true self.selected = false case .Unavailable: self.enabled = false self.selected = false case .Active: self.enabled = true self.selected = true } } } }
mpl-2.0
7232da9f90622fd78e5461f5b293d0b4
38.191964
157
0.636519
5.483448
false
false
false
false