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
Jamonek/School-For-Me
School For Me/Distance.swift
1
1248
// // Distance.swift // School For Me // // Created by Jamone Alexander Kelly on 1/11/16. // Copyright © 2016 Jamone Kelly. All rights reserved. // // Updated swift-er version of `computeDistance` from Erica Sadun: http://ericasadun.com/2016/01/11/make-this-swift-er-coordinate-distances/ import Foundation postfix operator ° postfix func °(degrees: Double) -> Double {return degrees * M_PI / 180.0} public struct Coordinate { public let latitude: Double, longitude: Double public enum EarthUnits: Double {case imperialRadius = 3961.0, metricRadius = 6373.0} public func distanceFrom(_ coordinate: Coordinate, radius: EarthUnits = .imperialRadius) -> Double { let (dLat, dLon) = (latitude - coordinate.latitude, longitude - coordinate.longitude) let (sqSinLat, sqSinLon) = (pow(sin(dLat° / 2.0), 2.0), pow(sin(dLon° / 2.0), 2.0)) let a = sqSinLat + sqSinLon * cos(latitude°) * cos(coordinate.latitude°) let c = 2.0 * atan2(sqrt(a), sqrt(1.0 - a)) return c * radius.rawValue } } // Example use // let whitehouse = Coordinate(latitude: 38.898556, longitude: -77.037852) // let fstreet = Coordinate(latitude: 38.897147, longitude: -77.043934) // whitehouse.distanceFrom(fstreet)
apache-2.0
458615e653cb0286fae35c06a8cbae96
40.366667
140
0.687349
3.291777
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
Pods/HXPHPicker/Sources/HXPHPicker/Core/Extension/Core+Bundle.swift
1
626
// // Core+Bundle.swift // HXPHPickerExample // // Created by Silence on 2020/11/15. // Copyright © 2020 Silence. All rights reserved. // import UIKit extension Bundle { static func localizedString(for key: String) -> String { return localizedString(for: key, value: nil) } static func localizedString(for key: String, value: String?) -> String { let bundle = PhotoManager.shared.languageBundle var newValue = bundle?.localizedString(forKey: key, value: value, table: nil) if newValue == nil { newValue = key } return newValue! } }
mit
25d6c1a5b921f13753faf14809195d7c
24
85
0.6256
4.251701
false
false
false
false
nfls/nflsers
app/v2/Controller/User/UserInfoController.swift
1
12071
// // UserInfoController.swift // NFLSers-iOS // // Created by Qingyang Hu on 2018/9/21. // Copyright © 2018 胡清阳. All rights reserved. // import Foundation import SwiftDate import SDWebImage import SCLAlertView import ReCaptcha import YPImagePicker class TypeCell: UITableViewCell { @IBOutlet weak var hint: UILabel! @IBOutlet weak var field: UITextField? @IBOutlet weak var submit: UIButton? } class AvatarCell: UITableViewCell { @IBOutlet weak var avatar: UIImageView? @IBOutlet weak var username: UILabel? } class PrivacyCell: UITableViewCell, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var picker: UIPickerView? @IBOutlet weak var submit: UIButton? @IBOutlet weak var antiSpider: UISwitch? let data = ["仅同校学生 (所有实名用户)", "仅同届同学", "仅自己"] func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return self.data.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return self.data[row] } } class UserInfoController: UITableViewController { let provider = UserProvider() let sections = ["个人信息", "安全设置", "隐私设置"] let numberOfRowsInSection = [4, 3, 1] var recaptcha = try? ReCaptcha(endpoint: .default) let completion: (String?) -> Void = { response in if let response = response { SCLAlertView().showError("错误", subTitle: response) } else { MessageNotifier().showInfo("修改成功") } load() } @objc func changePhone(_ sender: UIButton) { let indexPath = IndexPath(row: 0, section: 1) let cell = self.tableView.cellForRow(at: indexPath) as! TypeCell self.handleClick(cell, isPhone: true) } @objc func changeEmail(_ sender: UIButton) { let indexPath = IndexPath(row: 1, section: 1) let cell = self.tableView.cellForRow(at: indexPath) as! TypeCell self.handleClick(cell, isPhone: false) } @objc func changeUsername() { let prompt = SCLAlertView() let username = prompt.addTextField("新用户名") prompt.addButton("提交") { self.provider.changeUsername(username.text ?? "", completion: self.completion) } prompt.showInfo("修改用户名", subTitle: "用户名支持中文、英文、日文,长度在3-16之间。每次改名需要2小时的\"创意、活动、服务\"。", closeButtonTitle: "取消") } @objc func changePassword(_ sender: UIButton) { let indexPath = IndexPath(row: 2, section: 1) let cell = self.tableView.cellForRow(at: indexPath) as! TypeCell let prompt = SCLAlertView() let password = prompt.addTextField("原密码") prompt.addButton("提交") { self.provider.changeSecurity(password: password.text ?? "", newPassword: cell.field?.text ?? "", newEmail: nil, newPhone: nil, phoneCode: nil, emailCode: nil, clean: true, completion: self.completion) } prompt.showInfo("修改密码", subTitle: "请输入您原来的密码以修改。请注意,您所有登录的设备在修改密码后会自动退出。", closeButtonTitle: "取消") } @objc func changeAvatar(_ imageView: UIImageView) { var config = YPImagePickerConfiguration() config.library.mediaType = .photo config.startOnScreen = .library config.showsCrop = .rectangle(ratio: 1.0/1.0) let picker = YPImagePicker(configuration: config) picker.didFinishPicking { (items, _) in if let photo = items.singlePhoto { let loading = SCLAlertView(appearance: SCLAlertView.SCLAppearance(showCloseButton: false)).showWait("请稍后", subTitle: "图片上传中,大概需要半分钟") self.provider.changeAvatar(photo.image, completion: { loading.close() let cell = self.tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! AvatarCell cell.avatar?.sd_setImage(with: self.provider.current?.avatar, placeholderImage: nil, options: .refreshCached, progress: nil, completed: nil) }) } picker.dismiss(animated: true) } self.present(picker, animated: true) } func handleClick(_ cell: TypeCell, isPhone: Bool) { if cell.field!.isEnabled { cell.field!.isEnabled = false if isPhone { self.sendCode(toPhone: cell.field?.text ?? "", completion: { cell.field!.isEnabled = true }) } else { self.sendCode(toEmail: cell.field?.text ?? "", completion: { cell.field!.isEnabled = true }) } } else { cell.field!.isEnabled = true cell.field!.text = "" cell.field!.becomeFirstResponder() cell.submit?.setTitle("提交", for: []) } } func sendCode(toPhone phone: String, completion: @escaping ()->Void) { self.provider.postSendRequest(toPhone: phone) { (message) in completion() if let message = message { SCLAlertView().showError("错误", subTitle: message) } else { self.showPromptForCode(entry: phone, isPhone: true) } } } func sendCode(toEmail email: String, completion: @escaping ()->Void) { self.provider.postSendRequest(toEmail: email) { (message) in completion() if let message = message { SCLAlertView().showError("错误", subTitle: message) } else { self.showPromptForCode(entry: email, isPhone: false) } } } func showPromptForCode(entry: String, isPhone: Bool) { let prompt = SCLAlertView() let code = prompt.addTextField("动态码") code.autocorrectionType = .no code.autocapitalizationType = .none let password = prompt.addTextField("账户密码") password.isSecureTextEntry = true prompt.addButton("确认") { if isPhone { self.provider.changeSecurity(password: password.text ?? "", newPassword: nil, newEmail: nil, newPhone: entry, phoneCode: code.text ?? "", emailCode: nil, clean: nil, completion: self.completion) } else { self.provider.changeSecurity(password: password.text ?? "", newPassword: nil, newEmail: entry, newPhone: nil, phoneCode: nil, emailCode: code.text ?? "", clean: nil, completion: self.completion) } } prompt.showInfo("信息确认", subTitle: "请输入您收到的动态码,并输入您账户的密码以确认", closeButtonTitle: "取消") } func load() { provider.getUser() { self.tableView.reloadData() } } override func viewDidLoad() { self.tableView.allowsSelection = false self.tableView.rowHeight = UITableView.automaticDimension self.tableView.estimatedRowHeight = 100 recaptcha?.configureWebView { [weak self] webview in webview.frame = CGRect(x: 0, y: 40, width: self?.view.bounds.width ?? 0, height: self?.view.bounds.height ?? 0) } self.load() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numberOfRowsInSection[section] } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: let cell = tableView.dequeueReusableCell(withIdentifier: "infoCell", for: indexPath) as UITableViewCell switch indexPath.row { case 0: let avatar = tableView.dequeueReusableCell(withIdentifier: "avatarCell", for: indexPath) as! AvatarCell avatar.avatar?.sd_setImage(with: provider.current!.avatar, completed: nil) avatar.username?.text = provider.current!.username avatar.avatar?.isUserInteractionEnabled = true avatar.avatar?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(changeAvatar(_:)))) avatar.username?.isUserInteractionEnabled = true avatar.username?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(changeUsername))) return avatar case 1: cell.textLabel?.text = "ID" cell.detailTextLabel?.text = String(provider.current!.id) case 2: cell.textLabel?.text = "\"创意、行动、服务\" 小时数" cell.detailTextLabel?.text = String(provider.current!.point) case 3: cell.textLabel?.text = "加入时间" cell.detailTextLabel?.text = provider.current!.joinTime?.toFormat("yyyy'/'MM'/'dd HH:mm") default: break } return cell case 1: let cell = tableView.dequeueReusableCell(withIdentifier: "typeCell", for: indexPath) as! TypeCell switch indexPath.row { case 0: cell.hint?.text = "手机" cell.field?.text = provider.current!.phone ?? "未绑定" cell.submit?.addTarget(self, action: #selector(changePhone(_:)), for: .touchDown) cell.submit?.tag = 0 case 1: cell.hint?.text = "邮箱" if let email = provider.current?.email { cell.field?.text = email cell.submit?.isEnabled = false } else { cell.field?.text = "未绑定" cell.submit?.addTarget(self, action: #selector(changeEmail(_:)), for: .touchDown) cell.submit?.tag = 1 } case 2: cell.hint?.text = "密码" cell.submit?.toolbarPlaceholder = "新密码" cell.submit?.addTarget(self, action: #selector(changePassword(_:)), for: .touchDown) cell.field?.isEnabled = true default: break } return cell case 2: switch indexPath.row { case 0: let cell = self.tableView.dequeueReusableCell(withIdentifier: "privacyCell", for: indexPath) as! PrivacyCell cell.picker?.delegate = cell cell.picker?.dataSource = cell return cell default: break } default: break } return UITableViewCell() } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { if section == 1 { let name = Bundle.main.infoDictionary?["CFBundleDisplayName"] as! String let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String let code = Bundle.main.infoDictionary?["CFBundleVersion"] as! String let jp = Bundle.main.infoDictionary?["CodeNameJP"] as! String let en = Bundle.main.infoDictionary?["CodeNameEN"] as! String return "\(name) \(version)(\(code)), \(jp)(\(en)), © 2017-2019 胡清阳 " } else { return nil } } override func numberOfSections(in tableView: UITableView) -> Int { if provider.current == nil { return 0 } else { return 2 } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.sections[section] } }
apache-2.0
ce151d2d0e420311c70932f6ae9ed364
39.719298
212
0.588367
4.698381
false
false
false
false
mhv/Beholder
Beholder/Ownee.swift
1
1184
// // Ownee.swift // Signal // // Created by Mikhail Vroubel on 13/09/2014. // // import Foundation let OwneeOwner = "unsafeOwner" @objc public class Ownee : NSObject { @IBOutlet public var context:AnyObject? unowned var unsafeOwner:AnyObject @IBOutlet public weak var owner:NSObject? { willSet { willSet(owner, newValue: newValue) } } func willSet(owner:NSObject?, newValue:NSObject?) { if owner != newValue { if newValue != nil { objc_setAssociatedObject(newValue, unsafeAddressOf(self), self, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } if owner != nil { objc_setAssociatedObject(owner, unsafeAddressOf(self), nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } unsafeOwner = newValue ?? Ownee.self } public init(owner:NSObject, context:AnyObject? = nil) { self.unsafeOwner = owner super.init() (self.owner, self.context) = (owner, context) willSet(nil, newValue: owner) } public func cancel() { owner = nil; context = nil } deinit { cancel() } }
mit
03811892e10c1dbc774dd88d4262a52d
24.73913
115
0.583615
4.228571
false
false
false
false
Carthage/Commandant
Sources/Commandant/Command.swift
2
7522
// // Command.swift // Commandant // // Created by Justin Spahr-Summers on 2014-10-10. // Copyright (c) 2014 Carthage. All rights reserved. // import Foundation /// Represents a subcommand that can be executed with its own set of arguments. public protocol CommandProtocol { /// The command's options type. associatedtype Options: OptionsProtocol associatedtype ClientError where ClientError == Options.ClientError /// The action that users should specify to use this subcommand (e.g., /// `help`). var verb: String { get } /// A human-readable, high-level description of what this command is used /// for. var function: String { get } /// Runs this subcommand with the given options. func run(_ options: Options) -> Result<(), ClientError> } /// A type-erased command. public struct CommandWrapper<ClientError: Error> { public let verb: String public let function: String public let run: (ArgumentParser) -> Result<(), CommandantError<ClientError>> public let usage: () -> CommandantError<ClientError>? /// Creates a command that wraps another. fileprivate init<C: CommandProtocol>(_ command: C) where C.ClientError == ClientError { verb = command.verb function = command.function run = { (arguments: ArgumentParser) -> Result<(), CommandantError<ClientError>> in let options = C.Options.evaluate(.arguments(arguments)) if let remainingArguments = arguments.remainingArguments { return .failure(unrecognizedArgumentsError(remainingArguments)) } switch options { case let .success(options): return command .run(options) .mapError(CommandantError.commandError) case let .failure(error): return .failure(error) } } usage = { () -> CommandantError<ClientError>? in return C.Options.evaluate(.usage).error } } } /// Describes the "mode" in which a command should run. public enum CommandMode { /// Options should be parsed from the given command-line arguments. case arguments(ArgumentParser) /// Each option should record its usage information in an error, for /// presentation to the user. case usage } /// Maintains the list of commands available to run. public final class CommandRegistry<ClientError: Error> { private var commandsByVerb: [String: CommandWrapper<ClientError>] = [:] /// All available commands. public var commands: [CommandWrapper<ClientError>] { return commandsByVerb.values.sorted { return $0.verb < $1.verb } } public init() {} /// Registers the given commands, making those available to run. /// /// If another commands were already registered with the same `verb`s, those /// will be overwritten. @discardableResult public func register<C: CommandProtocol>(_ commands: C...) -> CommandRegistry where C.ClientError == ClientError { for command in commands { commandsByVerb[command.verb] = CommandWrapper(command) } return self } /// Runs the command corresponding to the given verb, passing it the given /// arguments. /// /// Returns the results of the execution, or nil if no such command exists. public func run(command verb: String, arguments: [String]) -> Result<(), CommandantError<ClientError>>? { return self[verb]?.run(ArgumentParser(arguments)) } /// Returns the command matching the given verb, or nil if no such command /// is registered. public subscript(verb: String) -> CommandWrapper<ClientError>? { return commandsByVerb[verb] } } extension CommandRegistry { /// Hands off execution to the CommandRegistry, by parsing CommandLine.arguments /// and then running whichever command has been identified in the argument /// list. /// /// If the chosen command executes successfully, the process will exit with /// a successful exit code. /// /// If the chosen command fails, the provided error handler will be invoked, /// then the process will exit with a failure exit code. /// /// If a matching command could not be found but there is any `executable-verb` /// style subcommand executable in the caller's `$PATH`, the subcommand will /// be executed. /// /// If a matching command could not be found or a usage error occurred, /// a helpful error message will be written to `stderr`, then the process /// will exit with a failure error code. public func main(defaultVerb: String, errorHandler: (ClientError) -> Void) -> Never { main(arguments: CommandLine.arguments, defaultVerb: defaultVerb, errorHandler: errorHandler) } /// Hands off execution to the CommandRegistry, by parsing `arguments` /// and then running whichever command has been identified in the argument /// list. /// /// If the chosen command executes successfully, the process will exit with /// a successful exit code. /// /// If the chosen command fails, the provided error handler will be invoked, /// then the process will exit with a failure exit code. /// /// If a matching command could not be found but there is any `executable-verb` /// style subcommand executable in the caller's `$PATH`, the subcommand will /// be executed. /// /// If a matching command could not be found or a usage error occurred, /// a helpful error message will be written to `stderr`, then the process /// will exit with a failure error code. public func main(arguments: [String], defaultVerb: String, errorHandler: (ClientError) -> Void) -> Never { assert(arguments.count >= 1) var arguments = arguments // Extract the executable name. let executableName = arguments.remove(at: 0) // use the default verb even if we have other arguments var verb = defaultVerb if let argument = arguments.first, !argument.hasPrefix("-") { verb = argument // Remove the command name. arguments.remove(at: 0) } switch run(command: verb, arguments: arguments) { case .success?: exit(EXIT_SUCCESS) case let .failure(error)?: switch error { case let .usageError(description): fputs(description + "\n", stderr) case let .commandError(error): errorHandler(error) } exit(EXIT_FAILURE) case nil: if let subcommandExecuted = executeSubcommandIfExists(executableName, verb: verb, arguments: arguments) { exit(subcommandExecuted) } fputs("Unrecognized command: '\(verb)'. See `\(executableName) help`.\n", stderr) exit(EXIT_FAILURE) } } /// Finds and executes a subcommand which exists in your $PATH. The executable /// name must be in the form of `executable-verb`. /// /// - Returns: The exit status of found subcommand or nil. private func executeSubcommandIfExists(_ executableName: String, verb: String, arguments: [String]) -> Int32? { let subcommand = "\(NSString(string: executableName).lastPathComponent)-\(verb)" func launchTask(_ path: String, arguments: [String]) -> Int32 { let task = Process() task.arguments = arguments do { #if canImport(Darwin) if #available(macOS 10.13, *) { task.executableURL = URL(fileURLWithPath: path) try task.run() } else { task.launchPath = path task.launch() } #elseif compiler(>=5) task.executableURL = URL(fileURLWithPath: path) try task.run() #else task.launchPath = path task.launch() #endif } catch let nserror as NSError { return Int32(truncatingIfNeeded: nserror.code) } catch { return -1 } task.waitUntilExit() return task.terminationStatus } guard launchTask("/usr/bin/which", arguments: [ "-s", subcommand ]) == 0 else { return nil } return launchTask("/usr/bin/env", arguments: [ subcommand ] + arguments) } }
mit
51b42fc966a69b74a0ffdf82183c4f89
30.211618
112
0.706594
3.946485
false
false
false
false
macteo/bezier
Bézier.playgroundbook/Contents/Chapters/Bezier.playgroundchapter/Sources/DrawController.swift
2
1447
import UIKit let orangeTralio = UIColor(red: 255 / 255, green: 87 / 255, blue: 34 / 255, alpha: 1) public class DrawController : UIViewController { let graphicsView = GraphicsView() public override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white graphicsView.frame = view.bounds graphicsView.backgroundColor = .clear view.addSubview(graphicsView) graphicsView.interpolationPoints = [] graphicsView.setNeedsDisplay() let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tap(gesture:))) tapGestureRecognizer.numberOfTapsRequired = 1 tapGestureRecognizer.numberOfTouchesRequired = 1 view.addGestureRecognizer(tapGestureRecognizer) let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gesture:))) longPressGestureRecognizer.numberOfTouchesRequired = 1 view.addGestureRecognizer(longPressGestureRecognizer) } func tap(gesture: UITapGestureRecognizer) { let point = gesture.location(in: graphicsView) graphicsView.interpolationPoints.append(point) graphicsView.setNeedsDisplay() } func longPress(gesture: UILongPressGestureRecognizer) { graphicsView.interpolationPoints.removeAll() graphicsView.setNeedsDisplay() } }
mit
9a27fe3a8b6eb5d70adc3708bf0c788b
36.102564
123
0.697305
6.004149
false
false
false
false
tardieu/swift
test/SourceKit/DocSupport/Inputs/cake.swift
4
1319
public protocol Prot { associatedtype Element var p : Int { get } func foo() func foo1() } public class C1 : Prot { public typealias Element = Int public var p : Int = 0 public func foo() {} public subscript(index: Int) -> Int { return 0 } public subscript(index i: Float) -> Int { return 0 } } public func genfoo<T1 : Prot, T2 : C1>(x ix: T1, y iy: T2) where T1.Element == Int, T2.Element == T1.Element {} public extension Prot where Self.Element == Int { final func extfoo() {} } public enum MyEnum : Int { case Blah } protocol Prot1 {} typealias C1Alias = C1 extension C1Alias : Prot1 {} public extension Prot { public func foo1() {} } public struct S1 { public enum SE { case a case b case c } } public extension S1 { public func foo1() {} public struct S2 { public let b = 1 } } @objc public protocol P2 { @objc optional func foo1() } public protocol P3 { associatedtype T } public struct S2 : P3 { public typealias T = S2 } public extension C1 { public enum C1Cases : Int { case case1 } } public class C2 : C1 { public func C2foo() {} } public extension Prot { subscript(index: Int) -> Int { return 0 } } public protocol P4 {} extension C1 : P4 { public func C1foo() {} public struct C1S1{ public func C1S1foo(a : P4) {} } }
apache-2.0
d230319d293f5dbea24d227e4f00ab03
14.517647
111
0.638362
3.067442
false
false
false
false
LamGiauKhongKhoTeam/LGKK
LGKKCoreLib/LGKKCoreLib/Modules/SPExtensions/Realm+SPExtension.swift
1
2108
// // Realm+SPExtension.swift // drivethrough // // Created by Nguyen Minh on 3/18/17. // Copyright © 2017 SP. All rights reserved. // import UIKit import Realm import RealmSwift // Write helper public extension Realm { public func safeAdd(object: Object) { self.add(object, update: true) } public class func updateData(_ block: ((Realm) throws -> Void)) { do { if let realm = try? Realm() { realm.beginWrite() try block(realm) try realm.commitWrite() } else { Realm.removeOldRealmDataFile() // Re-try again let realm = try Realm() realm.beginWrite() try block(realm) try realm.commitWrite() } } catch { print("Error on write realm: \(error.localizedDescription)") } } public class func removeOldRealmDataFile() { if let realmURL = Realm.Configuration.defaultConfiguration.fileURL { let realmURLs = [ realmURL, realmURL.appendingPathExtension("lock"), realmURL.appendingPathExtension("note"), realmURL.appendingPathExtension("management") ] for URL in realmURLs { do { try FileManager.default.removeItem(at: URL) } catch { print("Still failed when try to remove old realm data files.") } } } else { print("Still failed when find realm url.") } } public class func readData(_ block: ((Realm) throws -> Void)) { do { if let realm = try? Realm() { try block(realm) } else { Realm.removeOldRealmDataFile() // Re-try again let realm = try Realm() try block(realm) } } catch { print("Error on read realm: \(error.localizedDescription)") } } }
mit
eb822765bf30676aed53596b60d7b518
27.863014
82
0.495491
5.164216
false
false
false
false
fernandomarins/food-drivr-pt
hackathon-for-hunger/UserRouter.swift
1
2115
// // UserRouter.swift // hackathon-for-hunger // // Created by Ian Gristock on 4/2/16. // Copyright © 2016 Hacksmiths. All rights reserved. // import Foundation import Alamofire enum UserEndpoint { case Login(credentials: UserLogin) case Register(userData: UserRegistration) case GetUser(token: Token) case Update(token: Token, userData: UserUpdate) } class UserRouter : BaseRouter { typealias JsonDict = [String: AnyObject] var endpoint: UserEndpoint init(endpoint: UserEndpoint) { self.endpoint = endpoint } override var method: Alamofire.Method { switch endpoint { case .Login: return .POST case .Register: return .POST case .GetUser: return .GET case .Update: return .PATCH } } override var path: String { switch endpoint { case .Login: return "sessions" case .Register: return "users" case .GetUser(let token): return "users/\(token.token)" case .Update(let token): return "users/\(token.token)" } } override var parameters: APIParams { switch endpoint { case .Login(let credentials): do { let credentials = try credentials.toJSON() return ["session": credentials] } catch { return [:] } case .Register(let userData): do { let user = try userData.toJSON() return ["user": user] } catch { return [:] } case .GetUser: return nil case .Update(_, let userData): do { let user = try userData.toJSON() return ["user": user] } catch { return [:] } } } override var encoding: Alamofire.ParameterEncoding? { switch endpoint { case .Login: return .URL case .Register: return .URL case .GetUser: return .URL case .Update: return .URL } } }
mit
efb2070365a8b86c46797d8c88b96189
23.882353
63
0.53122
4.772009
false
false
false
false
jaydeboer/SwiftR
SwiftR/SwiftR.swift
1
14910
// // SwiftR.swift // SwiftR // // Created by Adam Hartford on 4/13/15. // Copyright (c) 2015 Adam Hartford. All rights reserved. // import Foundation import WebKit public enum ConnectionType { case Hub case Persistent } public enum State { case Connecting case Connected case Disconnected } public enum Transport { case Auto case WebSockets case ForeverFrame case ServerSentEvents case LongPolling var stringValue: String { switch self { case .WebSockets: return "webSockets" case .ForeverFrame: return "foreverFrame" case .ServerSentEvents: return "serverSentEvents" case .LongPolling: return "longPolling" default: return "auto" } } } public final class SwiftR: NSObject { static var connections = [SignalR]() public static var useWKWebView = false public static var transport: Transport = .Auto public class func connect(url: String, connectionType: ConnectionType = .Hub, readyHandler: SignalR -> ()) -> SignalR? { let signalR = SignalR(baseUrl: url, connectionType: connectionType, readyHandler: readyHandler) connections.append(signalR) return signalR } public class func startAll() { checkConnections() for connection in connections { connection.stop() } } public class func stopAll() { checkConnections() for connection in connections { connection.stop() } } class func checkConnections() { if connections.count == 0 { print("No active SignalR connections. Use SwiftR.connect(...) first.") } } } public class SignalR: NSObject, SwiftRWebDelegate { var webView: SwiftRWebView! var wkWebView: WKWebView! var baseUrl: String var connectionType: ConnectionType var readyHandler: SignalR -> () var hubs = [String: Hub]() public var state: State = .Disconnected public var connectionID: String? public var received: (AnyObject? -> ())? public var starting: (() -> ())? public var connected: (() -> ())? public var disconnected: (() -> ())? public var connectionSlow: (() -> ())? public var connectionFailed: (() -> ())? public var reconnecting: (() -> ())? public var reconnected: (() -> ())? public var error: (AnyObject? -> ())? public var queryString: AnyObject? { didSet { if let qs: AnyObject = queryString { if let jsonData = try? NSJSONSerialization.dataWithJSONObject(qs, options: NSJSONWritingOptions()) { let json = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String runJavaScript("swiftR.connection.qs = \(json)") } } else { runJavaScript("swiftR.connection.qs = {}") } } } public var headers: [String: String]? { didSet { if let h = headers { if let jsonData = try? NSJSONSerialization.dataWithJSONObject(h, options: NSJSONWritingOptions()) { let json = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String runJavaScript("swiftR.headers = \(json)") } } else { runJavaScript("swiftR.headers = {}") } } } init(baseUrl: String, connectionType: ConnectionType = .Hub, readyHandler: SignalR -> ()) { self.baseUrl = baseUrl self.readyHandler = readyHandler self.connectionType = connectionType super.init() #if COCOAPODS let bundle = NSBundle(identifier: "org.cocoapods.SwiftR")! #elseif SWIFTR_FRAMEWORK let bundle = NSBundle(identifier: "com.adamhartford.SwiftR")! #else let bundle = NSBundle.mainBundle() #endif let jqueryURL = bundle.URLForResource("jquery-2.1.3.min", withExtension: "js")! let signalRURL = bundle.URLForResource("jquery.signalR-2.2.0.min", withExtension: "js")! let jsURL = bundle.URLForResource("SwiftR", withExtension: "js")! if SwiftR.useWKWebView { // Loading file:// URLs from NSTemporaryDirectory() works on iOS, not OS X. // Workaround on OS X is to include the script directly. #if os(iOS) let temp = NSURL(fileURLWithPath: NSTemporaryDirectory()) let jqueryTempURL = temp.URLByAppendingPathComponent("jquery-2.1.3.min.js") let signalRTempURL = temp.URLByAppendingPathComponent("jquery.signalR-2.2.0.min") let jsTempURL = temp.URLByAppendingPathComponent("SwiftR.js") let fileManager = NSFileManager.defaultManager() try! fileManager.removeItemAtURL(jqueryTempURL) try! fileManager.removeItemAtURL(signalRTempURL) try! fileManager.removeItemAtURL(jsTempURL) try! fileManager.copyItemAtURL(jqueryURL, toURL: jqueryTempURL) try! fileManager.copyItemAtURL(signalRURL, toURL: signalRTempURL) try! fileManager.copyItemAtURL(jsURL, toURL: jsTempURL) let jqueryInclude = "<script src='\(jqueryTempURL.absoluteString)'></script>" let signalRInclude = "<script src='\(signalRTempURL.absoluteString)'></script>" let jsInclude = "<script src='\(jsTempURL.absoluteString)'></script>" #else let jqueryString = NSString(contentsOfURL: jqueryURL, encoding: NSUTF8StringEncoding, error: nil)! let signalRString = NSString(contentsOfURL: signalRURL, encoding: NSUTF8StringEncoding, error: nil)! let jsString = NSString(contentsOfURL: jsURL, encoding: NSUTF8StringEncoding, error: nil)! let jqueryInclude = "<script>\(jqueryString)</script>" let signalRInclude = "<script>\(signalRString)</script>" let jsInclude = "<script>\(jsString)</script>" #endif let config = WKWebViewConfiguration() config.userContentController.addScriptMessageHandler(self, name: "interOp") #if !os(iOS) //config.preferences.setValue(true, forKey: "developerExtrasEnabled") #endif wkWebView = WKWebView(frame: CGRectZero, configuration: config) wkWebView.navigationDelegate = self let html = "<!doctype html><html><head></head><body>" + "\(jqueryInclude)\(signalRInclude)\(jsInclude))" + "</body></html>" wkWebView.loadHTMLString(html, baseURL: bundle.bundleURL) return } else { let jqueryInclude = "<script src='\(jqueryURL.absoluteString)'></script>" let signalRInclude = "<script src='\(signalRURL.absoluteString)'></script>" let jsInclude = "<script src='\(jsURL.absoluteString)'></script>" let html = "<!doctype html><html><head></head><body>" + "\(jqueryInclude)\(signalRInclude)\(jsInclude))" + "</body></html>" webView = SwiftRWebView() #if os(iOS) webView.delegate = self webView.loadHTMLString(html, baseURL: bundle.bundleURL) #else webView.policyDelegate = self webView.mainFrame.loadHTMLString(html, baseURL: bundle.bundleURL) #endif } } deinit { if let view = wkWebView { view.removeFromSuperview() } } public func createHubProxy(name: String) -> Hub { let hub = Hub(name: name, connection: self) hubs[name.lowercaseString] = hub return hub } public func send(data: AnyObject?) { var json = "null" if let d: AnyObject = data { if d is String { json = "'\(d)'" } else if d is NSNumber { json = "\(d)" } else if let jsonData = try? NSJSONSerialization.dataWithJSONObject(d, options: NSJSONWritingOptions()) { json = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String } } runJavaScript("swiftR.connection.send(\(json))") } public func start() { runJavaScript("start()") } public func stop() { runJavaScript("swiftR.connection.stop()") } func shouldHandleRequest(request: NSURLRequest) -> Bool { if request.URL!.absoluteString.hasPrefix("swiftr://") { let id = (request.URL!.absoluteString as NSString).substringFromIndex(9) let msg = webView.stringByEvaluatingJavaScriptFromString("readMessage(\(id))")! let data = msg.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let json: AnyObject = try! NSJSONSerialization.JSONObjectWithData(data, options: []) processMessage(json) return false } return true } func processMessage(json: AnyObject) { if let message = json["message"] as? String { switch message { case "ready": let isHub = connectionType == .Hub ? "true" : "false" runJavaScript("swiftR.transport = '\(SwiftR.transport.stringValue)'") runJavaScript("initialize('\(baseUrl)', \(isHub))") readyHandler(self) runJavaScript("start()") case "starting": state = .Connecting starting?() case "connected": state = .Connected connectionID = json["connectionId"] as? String connected?() case "disconnected": state = .Disconnected disconnected?() case "connectionSlow": connectionSlow?() case "connectionFailed": connectionFailed?() case "reconnecting": state = .Connecting reconnecting?() case "reconnected": state = .Connected reconnected?() case "error": if let err: AnyObject = json["error"] { error?(err["context"]) } else { error?(nil) } default: break } } else if let data: AnyObject = json["data"] { received?(data) } else if let hubName = json["hub"] as? String { let method = json["method"] as! String let arguments: AnyObject? = json["arguments"] let hub = hubs[hubName] hub?.handlers[method]?(arguments) } } func runJavaScript(script: String, callback: (AnyObject! -> ())? = nil) { if SwiftR.useWKWebView { wkWebView.evaluateJavaScript(script, completionHandler: { (result, _) in callback?(result) }) } else { let result = webView.stringByEvaluatingJavaScriptFromString(script) callback?(result) } } // MARK: - WKNavigationDelegate // http://stackoverflow.com/questions/26514090/wkwebview-does-not-run-javascriptxml-http-request-with-out-adding-a-parent-vie#answer-26575892 public func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { #if os(iOS) UIApplication.sharedApplication().keyWindow?.addSubview(wkWebView) #endif } // MARK: - WKScriptMessageHandler public func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { let id = message.body as! String wkWebView.evaluateJavaScript("readMessage(\(id))", completionHandler: { [weak self] (msg, _) in let data = msg!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let json: AnyObject = try! NSJSONSerialization.JSONObjectWithData(data, options: []) self?.processMessage(json) }) } // MARK: - Web delegate methods #if os(iOS) public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { return shouldHandleRequest(request) } #else public override func webView(webView: WebView!, decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) { if shouldHandleRequest(request) { listener.use() } } #endif } // MARK: - Hub public class Hub { let name: String var handlers: [String: AnyObject? -> ()] = [:] public let connection: SignalR! init(name: String, connection: SignalR) { self.name = name self.connection = connection } public func on(method: String, parameters: [String]? = nil, callback: AnyObject? -> ()) { handlers[method] = callback var p = "null" if let params = parameters { p = "['" + params.joinWithSeparator("','") + "']" } connection.runJavaScript("addHandler('\(name)', '\(method)', \(p))") } public func invoke(method: String, arguments: [AnyObject]?) { var jsonArguments = [String]() if let args = arguments { for arg in args { if arg is String { jsonArguments.append("'\(arg)'") } else if arg is NSNumber { jsonArguments.append("\(arg)") } else if let data = try? NSJSONSerialization.dataWithJSONObject(arg, options: NSJSONWritingOptions()) { jsonArguments.append(NSString(data: data, encoding: NSUTF8StringEncoding) as! String) } } } let args = jsonArguments.joinWithSeparator(",") let js = "swiftR.hubs.\(name).invoke('\(method)', \(args))" connection.runJavaScript(js) } } #if os(iOS) typealias SwiftRWebView = UIWebView public protocol SwiftRWebDelegate: WKNavigationDelegate, WKScriptMessageHandler, UIWebViewDelegate {} #else typealias SwiftRWebView = WebView public protocol SwiftRWebDelegate: WKNavigationDelegate, WKScriptMessageHandler {} #endif
mit
7e2c2e43d7dfde7254a12f6066568017
35.101695
145
0.571764
5.334526
false
false
false
false
kinetic-fit/sensors-swift
Sources/SwiftySensors/CyclingSerializer.swift
1
3338
// // CyclingSerializer.swift // SwiftySensors // // https://github.com/kinetic-fit/sensors-swift // // Copyright © 2017 Kinetic. All rights reserved. // import Foundation /// :nodoc: public protocol CyclingMeasurementData { var timestamp: Double { get } var cumulativeWheelRevolutions: UInt32? { get } var lastWheelEventTime: UInt16? { get } var cumulativeCrankRevolutions: UInt16? { get } var lastCrankEventTime: UInt16? { get } } /// :nodoc: open class CyclingSerializer { public enum SensorLocation: UInt8 { case other = 0 case topOfShoe = 1 case inShoe = 2 case hip = 3 case frontWheel = 4 case leftCrank = 5 case rightCrank = 6 case leftPedal = 7 case rightPedal = 8 case frontHub = 9 case rearDropout = 10 case chainstay = 11 case rearWheel = 12 case rearHub = 13 case chest = 14 case spider = 15 case chainRing = 16 } public static func readSensorLocation(_ data: Data) -> SensorLocation? { let bytes = data.map { $0 } return SensorLocation(rawValue: bytes[0]) } public static func calculateWheelKPH(_ current: CyclingMeasurementData, previous: CyclingMeasurementData, wheelCircumferenceCM: Double, wheelTimeResolution: Int) -> Double? { guard let cwr1 = current.cumulativeWheelRevolutions else { return nil } guard let cwr2 = previous.cumulativeWheelRevolutions else { return nil } guard let lwet1 = current.lastWheelEventTime else { return nil } guard let lwet2 = previous.lastWheelEventTime else { return nil } let wheelRevsDelta: UInt32 = deltaWithRollover(cwr1, old: cwr2, max: UInt32.max) let wheelTimeDelta: UInt16 = deltaWithRollover(lwet1, old: lwet2, max: UInt16.max) let wheelTimeSeconds = Double(wheelTimeDelta) / Double(wheelTimeResolution) if wheelTimeSeconds > 0 { let wheelRPM = Double(wheelRevsDelta) / (wheelTimeSeconds / 60) let cmPerKm = 0.00001 let minsPerHour = 60.0 return wheelRPM * wheelCircumferenceCM * cmPerKm * minsPerHour } return 0 } public static func calculateCrankRPM(_ current: CyclingMeasurementData, previous: CyclingMeasurementData) -> Double? { guard let ccr1 = current.cumulativeCrankRevolutions else { return nil } guard let ccr2 = previous.cumulativeCrankRevolutions else { return nil } guard let lcet1 = current.lastCrankEventTime else { return nil } guard let lcet2 = previous.lastCrankEventTime else { return nil } let crankRevsDelta: UInt16 = deltaWithRollover(ccr1, old: ccr2, max: UInt16.max) let crankTimeDelta: UInt16 = deltaWithRollover(lcet1, old: lcet2, max: UInt16.max) let crankTimeSeconds = Double(crankTimeDelta) / 1024 if crankTimeSeconds > 0 { return Double(crankRevsDelta) / (crankTimeSeconds / 60) } return 0 } private static func deltaWithRollover<T: BinaryInteger>(_ new: T, old: T, max: T) -> T { return old > new ? max - old + new : new - old } }
mit
40d488a5a1e4b4d84252b537b465c280
36.494382
178
0.623314
4.234772
false
false
false
false
googleads/googleads-mobile-ios-examples
Swift/admanager/AdManagerInterstitialExample/AdManagerInterstitialExample/ViewController.swift
1
5255
// // Copyright (C) 2015 Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import GoogleMobileAds import UIKit class ViewController: UIViewController, GADFullScreenContentDelegate { enum GameState: NSInteger { case notStarted case playing case paused case ended } /// The game length. static let gameLength = 5 /// The interstitial ad. var interstitial: GAMInterstitialAd? /// The countdown timer. var timer: Timer? /// The amount of time left in the game. var timeLeft = gameLength /// The state of the game. var gameState = GameState.notStarted /// The date that the timer was paused. var pauseDate: Date? /// The last fire date before a pause. var previousFireDate: Date? /// The countdown timer label. @IBOutlet weak var gameText: UILabel! /// The play again button. @IBOutlet weak var playAgainButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Pause game when application enters background. NotificationCenter.default.addObserver( self, selector: #selector(ViewController.pauseGame), name: UIApplication.didEnterBackgroundNotification, object: nil) // Resume game when application becomes active. NotificationCenter.default.addObserver( self, selector: #selector(ViewController.resumeGame), name: UIApplication.didBecomeActiveNotification, object: nil) startNewGame() } // MARK: - Game Logic fileprivate func startNewGame() { loadInterstitial() gameState = .playing timeLeft = ViewController.gameLength playAgainButton.isHidden = true updateTimeLeft() timer = Timer.scheduledTimer( timeInterval: 1.0, target: self, selector: #selector(ViewController.decrementTimeLeft(_:)), userInfo: nil, repeats: true) } fileprivate func loadInterstitial() { GAMInterstitialAd.load( withAdManagerAdUnitID: "/6499/example/interstitial", request: GAMRequest() ) { (ad, error) in if let error = error { print("Failed to load interstitial ad with error: \(error.localizedDescription)") return } self.interstitial = ad self.interstitial?.fullScreenContentDelegate = self } } fileprivate func updateTimeLeft() { gameText.text = "\(timeLeft) seconds left!" } @objc func decrementTimeLeft(_ timer: Timer) { timeLeft -= 1 updateTimeLeft() if timeLeft == 0 { endGame() } } @objc func pauseGame() { if gameState != .playing { return } gameState = .paused // Record the relevant pause times. pauseDate = Date() previousFireDate = timer?.fireDate // Prevent the timer from firing while app is in background. timer?.fireDate = Date.distantFuture } @objc func resumeGame() { if gameState != .paused { return } gameState = .playing // Calculate amount of time the app was paused. let pauseTime = (pauseDate?.timeIntervalSinceNow)! * -1 // Set the timer to start firing again. timer?.fireDate = (previousFireDate?.addingTimeInterval(pauseTime))! } fileprivate func endGame() { gameState = .ended timer?.invalidate() timer = nil let alert = UIAlertController( title: "Game Over", message: "You lasted \(ViewController.gameLength) seconds", preferredStyle: .alert) let alertAction = UIAlertAction( title: "OK", style: .cancel, handler: { [weak self] action in if let ad = self?.interstitial { ad.present(fromRootViewController: self!) } else { print("Ad wasn't ready") } self?.playAgainButton.isHidden = false }) alert.addAction(alertAction) self.present(alert, animated: true, completion: nil) } // MARK: - Interstitial Button Actions @IBAction func playAgain(_ sender: AnyObject) { startNewGame() } // MARK: - GADFullScreenContentDelegate func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) { print("Ad will present full screen content.") } func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) { print("Ad failed to present full screen content with error \(error.localizedDescription).") } func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) { print("Ad did dismiss full screen content.") } // MARK: - deinit deinit { NotificationCenter.default.removeObserver( self, name: UIApplication.didEnterBackgroundNotification, object: nil) NotificationCenter.default.removeObserver( self, name: UIApplication.didBecomeActiveNotification, object: nil) } }
apache-2.0
31d673a92a9811da0ad40089fbcabccc
25.407035
99
0.680304
4.764279
false
false
false
false
rene-dohan/CS-IOS
Renetik/Renetik/Classes/Core/Protocols/CSHasProgress.swift
1
859
// // Created by Rene Dohan on 1/11/20. // import Foundation public protocol CSHasProgressProtocol { func show(progress title: String, _ cancel: CSDialogAction?, _ graceTime: TimeInterval?, _ minShowTime: TimeInterval?) -> CSHasDialogVisible } public extension CSHasProgressProtocol { func show(progress title: String, onCancel: Func? = nil, graceTime: TimeInterval = 0, minShowTime: TimeInterval = 2) -> CSHasDialogVisible { show(progress: title, onCancel.notNil ? CSDialogAction(title: .cs_dialog_cancel, action: onCancel!) : nil, graceTime, minShowTime) } func show(progress title: String, cancel: CSDialogAction?, graceTime: TimeInterval = 0, minShowTime: TimeInterval = 2) -> CSHasDialogVisible { show(progress: title, cancel, graceTime, minShowTime) } }
mit
2eddf5f0cb417085f06cb52ac2a89b2f
36.347826
106
0.677532
4.338384
false
false
false
false
larrabetzu/iBasque-Radio
SwiftRadio/Track.swift
4
509
// // trackswift // Swift Radio // // Created by Matthew Fecher on 7/2/15. // Copyright (c) 2015 MatthewFecher.com. All rights reserved. // import UIKit //***************************************************************** // Track struct //***************************************************************** struct Track { var title: String = "" var artist: String = "" var artworkURL: String = "" var artworkImage = UIImage(named: "albumArt") var artworkLoaded = false var isPlaying: Bool = false }
mit
ac07d45c47e7f092e71f94d24c70b98c
22.181818
67
0.497053
4.241667
false
false
false
false
ygorshenin/omim
iphone/Maps/Categories/NSAttributedString+HTML.swift
1
1662
extension NSAttributedString { public class func string(withHtml htmlString:String, defaultAttributes attributes:[NSAttributedStringKey : Any]) -> NSAttributedString? { guard let data = htmlString.data(using: .utf8) else { return nil } guard let text = try? NSMutableAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) else { return nil } text.addAttributes(attributes, range: NSMakeRange(0, text.length)) return text } } extension NSMutableAttributedString { @objc convenience init?(htmlString: String, baseFont: UIFont) { guard let data = htmlString.data(using: .utf8) else { return nil } do { try self.init(data: data, options: [.documentType : NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) } catch { return nil } enumerateAttribute(.font, in: NSMakeRange(0, length), options: []) { (value, range, _) in if let font = value as? UIFont, let descriptor = baseFont.fontDescriptor.withSymbolicTraits(font.fontDescriptor.symbolicTraits) { let newFont = UIFont(descriptor: descriptor, size: baseFont.pointSize) addAttribute(.font, value: newFont, range: range) } else { addAttribute(.font, value: baseFont, range: range) } } } }
apache-2.0
6fb656fd05348418e8c5d84ce3749526
43.918919
139
0.613718
5.242902
false
false
false
false
azadibogolubov/InterestDestroyer
iOS Version/Interest Destroyer/Charts/Classes/Renderers/ChartXAxisRendererHorizontalBarChart.swift
15
11982
// // ChartXAxisRendererHorizontalBarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class ChartXAxisRendererHorizontalBarChart: ChartXAxisRendererBarChart { public override init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!, chart: BarChartView) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer, chart: chart) } public override func computeAxis(xValAverageLength xValAverageLength: Double, xValues: [String?]) { _xAxis.values = xValues let longest = _xAxis.getLongestLabel() as NSString let longestSize = longest.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]) _xAxis.labelWidth = floor(longestSize.width + _xAxis.xOffset * 3.5) _xAxis.labelHeight = longestSize.height } public override func renderAxisLabels(context context: CGContext?) { if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled || _chart.data === nil) { return } let xoffset = _xAxis.xOffset if (_xAxis.labelPosition == .Top) { drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, align: .Left) } else if (_xAxis.labelPosition == .Bottom) { drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, align: .Right) } else if (_xAxis.labelPosition == .BottomInside) { drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, align: .Left) } else if (_xAxis.labelPosition == .TopInside) { drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, align: .Right) } else { // BOTH SIDED drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, align: .Right) drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, align: .Left) } } /// draws the x-labels on the specified y-position internal func drawLabels(context context: CGContext?, pos: CGFloat, align: NSTextAlignment) { let labelFont = _xAxis.labelFont let labelTextColor = _xAxis.labelTextColor // pre allocate to save performance (dont allocate in loop) var position = CGPoint(x: 0.0, y: 0.0) let bd = _chart.data as! BarChartData let step = bd.dataSetCount for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus) { let label = _xAxis.values[i] if (label == nil) { continue } position.x = 0.0 position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace + bd.groupSpace / 2.0 // consider groups (center label for each group) if (step > 1) { position.y += (CGFloat(step) - 1.0) / 2.0 } transformer.pointValueToPixel(&position) if (viewPortHandler.isInBoundsY(position.y)) { drawLabel(context: context, label: label!, xIndex: i, x: pos, y: position.y - _xAxis.labelHeight / 2.0, align: align, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]) } } } internal func drawLabel(context context: CGContext?, label: String, xIndex: Int, x: CGFloat, y: CGFloat, align: NSTextAlignment, attributes: [String: NSObject]) { let formattedLabel = _xAxis.valueFormatter?.stringForXValue(xIndex, original: label, viewPortHandler: viewPortHandler) ?? label ChartUtils.drawText(context: context, text: formattedLabel, point: CGPoint(x: x, y: y), align: align, attributes: attributes) } private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderGridLines(context context: CGContext?) { if (!_xAxis.isEnabled || !_xAxis.isDrawGridLinesEnabled || _chart.data === nil) { return } CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor) CGContextSetLineWidth(context, _xAxis.gridLineWidth) if (_xAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } var position = CGPoint(x: 0.0, y: 0.0) let bd = _chart.data as! BarChartData // take into consideration that multiple DataSets increase _deltaX let step = bd.dataSetCount for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus) { position.x = 0.0 position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace - 0.5 transformer.pointValueToPixel(&position) if (viewPortHandler.isInBoundsY(position.y)) { _gridLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _gridLineSegmentsBuffer[0].y = position.y _gridLineSegmentsBuffer[1].x = viewPortHandler.contentRight _gridLineSegmentsBuffer[1].y = position.y CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2) } } CGContextRestoreGState(context) } private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderAxisLine(context context: CGContext?) { if (!_xAxis.isEnabled || !_xAxis.isDrawAxisLineEnabled) { return } CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, _xAxis.axisLineColor.CGColor) CGContextSetLineWidth(context, _xAxis.axisLineWidth) if (_xAxis.axisLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.axisLineDashPhase, _xAxis.axisLineDashLengths, _xAxis.axisLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } if (_xAxis.labelPosition == .Top || _xAxis.labelPosition == .TopInside || _xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } if (_xAxis.labelPosition == .Bottom || _xAxis.labelPosition == .BottomInside || _xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop _axisLineSegmentsBuffer[1].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } CGContextRestoreGState(context) } private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderLimitLines(context context: CGContext?) { var limitLines = _xAxis.limitLines if (limitLines.count == 0) { return } CGContextSaveGState(context) let trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for (var i = 0; i < limitLines.count; i++) { let l = limitLines[i] position.x = 0.0 position.y = CGFloat(l.limit) position = CGPointApplyAffineTransform(position, trans) _limitLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _limitLineSegmentsBuffer[0].y = position.y _limitLineSegmentsBuffer[1].x = viewPortHandler.contentRight _limitLineSegmentsBuffer[1].y = position.y CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor) CGContextSetLineWidth(context, l.lineWidth) if (l.lineDashLengths != nil) { CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2) let label = l.label // if drawing the limit-value label is enabled if (label.characters.count > 0) { let labelLineHeight = l.valueFont.lineHeight let add = CGFloat(4.0) let xOffset: CGFloat = add let yOffset: CGFloat = l.lineWidth + labelLineHeight if (l.labelPosition == .RightTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y - yOffset), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .RightBottom) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y + yOffset - labelLineHeight), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .LeftTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y - yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y + yOffset - labelLineHeight), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } } } CGContextRestoreGState(context) } }
apache-2.0
ed56bee683480fe79eedaf40340ba06e
38.032573
227
0.567768
5.573023
false
false
false
false
klundberg/swift-corelibs-foundation
Foundation/NSCache.swift
1
5500
// 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 // public class Cache: NSObject { private class NSCacheEntry { var key: AnyObject var value: AnyObject var cost: Int var prevByCost: NSCacheEntry? var nextByCost: NSCacheEntry? init(key: AnyObject, value: AnyObject, cost: Int) { self.key = key self.value = value self.cost = cost } } private var _entries = Dictionary<UnsafePointer<Void>, NSCacheEntry>() private let _lock = Lock() private var _totalCost = 0 private var _byCost: NSCacheEntry? public var name: String = "" public var totalCostLimit: Int = -1 // limits are imprecise/not strict public var countLimit: Int = -1 // limits are imprecise/not strict public var evictsObjectsWithDiscardedContent: Bool = false public override init() { } public weak var delegate: NSCacheDelegate? public func object(forKey key: AnyObject) -> AnyObject? { var object: AnyObject? let keyRef = unsafeBitCast(key, to: UnsafePointer<Void>.self) _lock.lock() if let entry = _entries[keyRef] { object = entry.value } _lock.unlock() return object } public func setObject(_ obj: AnyObject, forKey key: AnyObject) { setObject(obj, forKey: key, cost: 0) } private func remove(_ entry: NSCacheEntry) { let oldPrev = entry.prevByCost let oldNext = entry.nextByCost oldPrev?.nextByCost = oldNext oldNext?.prevByCost = oldPrev if entry === _byCost { _byCost = entry.nextByCost } } private func insert(_ entry: NSCacheEntry) { if _byCost == nil { _byCost = entry } else { var element = _byCost while let e = element { if e.cost > entry.cost { let newPrev = e.prevByCost entry.prevByCost = newPrev entry.nextByCost = e break } element = e.nextByCost } } } public func setObject(_ obj: AnyObject, forKey key: AnyObject, cost g: Int) { let keyRef = unsafeBitCast(key, to: UnsafePointer<Void>.self) _lock.lock() _totalCost += g var purgeAmount = 0 if totalCostLimit > 0 { purgeAmount = (_totalCost + g) - totalCostLimit } var purgeCount = 0 if countLimit > 0 { purgeCount = (_entries.count + 1) - countLimit } if let entry = _entries[keyRef] { entry.value = obj if entry.cost != g { entry.cost = g remove(entry) insert(entry) } } else { _entries[keyRef] = NSCacheEntry(key: key, value: obj, cost: g) } _lock.unlock() var toRemove = [NSCacheEntry]() if purgeAmount > 0 { _lock.lock() while _totalCost - totalCostLimit > 0 { if let entry = _byCost { _totalCost -= entry.cost toRemove.append(entry) remove(entry) } else { break } } if countLimit > 0 { purgeCount = (_entries.count - toRemove.count) - countLimit } _lock.unlock() } if purgeCount > 0 { _lock.lock() while (_entries.count - toRemove.count) - countLimit > 0 { if let entry = _byCost { _totalCost -= entry.cost toRemove.append(entry) remove(entry) } else { break } } _lock.unlock() } if let del = delegate { for entry in toRemove { del.cache(self, willEvictObject: entry.value) } } _lock.lock() for entry in toRemove { _entries.removeValue(forKey: unsafeBitCast(entry.key, to: UnsafePointer<Void>.self)) // the cost list is already fixed up in the purge routines } _lock.unlock() } public func removeObject(forKey key: AnyObject) { let keyRef = unsafeBitCast(key, to: UnsafePointer<Void>.self) _lock.lock() if let entry = _entries.removeValue(forKey: keyRef) { _totalCost -= entry.cost remove(entry) } _lock.unlock() } public func removeAllObjects() { _lock.lock() _entries.removeAll() _byCost = nil _totalCost = 0 _lock.unlock() } } public protocol NSCacheDelegate : class { func cache(_ cache: Cache, willEvictObject obj: AnyObject) } extension NSCacheDelegate { func cache(_ cache: Cache, willEvictObject obj: AnyObject) { // Default implementation does nothing } }
apache-2.0
77bf04a93c325c49da2a9acb622fa406
28.255319
155
0.516364
4.867257
false
false
false
false
meanjoe45/JKBCrypt
lib/JKBCrypt.swift
1
54366
// // JKBCrypt.swift // JKBCrypt // // Created by Joe Kramer on 6/19/2015. // Copyright (c) 2015 Joe Kramer. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ---------------------------------------------------------------------- // // This Swift port is based on the Objective-C port by Jay Fuerstenberg. // https://github.com/jayfuerstenberg/JFCommon // // ---------------------------------------------------------------------- // // The Objective-C port is based on the original Java implementation by Damien Miller // found here: http://www.mindrot.org/projects/jBCrypt/ // In accordance with the Damien Miller's request, his original copyright covering // his Java implementation is included here: // // Copyright (c) 2006 Damien Miller <[email protected]> // // Permission to use, copy, modify, and distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // import Foundation // MARK: - Class Extensions extension String { subscript (i: Int) -> Character { return self[advance(self.startIndex, i)] } subscript (i: Int) -> String { return String(self[i] as Character) } subscript (r: Range<Int>) -> String { return substringWithRange(Range(start: advance(startIndex, r.startIndex), end: advance(startIndex, r.endIndex))) } } extension Character { func utf16Value() -> UInt16 { for s in String(self).utf16 { return s } return 0 } } // BCrypt parameters let GENSALT_DEFAULT_LOG2_ROUNDS : Int = 10 let BCRYPT_SALT_LEN : Int = 16 // Blowfish parameters let BLOWFISH_NUM_ROUNDS : Int = 16 // Initial contents of key schedule let P_orig : [Int32] = [ Int32(bitPattern: 0x243f6a88), Int32(bitPattern: 0x85a308d3), Int32(bitPattern: 0x13198a2e), Int32(bitPattern: 0x03707344), Int32(bitPattern: 0xa4093822), Int32(bitPattern: 0x299f31d0), Int32(bitPattern: 0x082efa98), Int32(bitPattern: 0xec4e6c89), Int32(bitPattern: 0x452821e6), Int32(bitPattern: 0x38d01377), Int32(bitPattern: 0xbe5466cf), Int32(bitPattern: 0x34e90c6c), Int32(bitPattern: 0xc0ac29b7), Int32(bitPattern: 0xc97c50dd), Int32(bitPattern: 0x3f84d5b5), Int32(bitPattern: 0xb5470917), Int32(bitPattern: 0x9216d5d9), Int32(bitPattern: 0x8979fb1b) ] let S_orig : [Int32] = [ Int32(bitPattern: 0xd1310ba6), Int32(bitPattern: 0x98dfb5ac), Int32(bitPattern: 0x2ffd72db), Int32(bitPattern: 0xd01adfb7), Int32(bitPattern: 0xb8e1afed), Int32(bitPattern: 0x6a267e96), Int32(bitPattern: 0xba7c9045), Int32(bitPattern: 0xf12c7f99), Int32(bitPattern: 0x24a19947), Int32(bitPattern: 0xb3916cf7), Int32(bitPattern: 0x0801f2e2), Int32(bitPattern: 0x858efc16), Int32(bitPattern: 0x636920d8), Int32(bitPattern: 0x71574e69), Int32(bitPattern: 0xa458fea3), Int32(bitPattern: 0xf4933d7e), Int32(bitPattern: 0x0d95748f), Int32(bitPattern: 0x728eb658), Int32(bitPattern: 0x718bcd58), Int32(bitPattern: 0x82154aee), Int32(bitPattern: 0x7b54a41d), Int32(bitPattern: 0xc25a59b5), Int32(bitPattern: 0x9c30d539), Int32(bitPattern: 0x2af26013), Int32(bitPattern: 0xc5d1b023), Int32(bitPattern: 0x286085f0), Int32(bitPattern: 0xca417918), Int32(bitPattern: 0xb8db38ef), Int32(bitPattern: 0x8e79dcb0), Int32(bitPattern: 0x603a180e), Int32(bitPattern: 0x6c9e0e8b), Int32(bitPattern: 0xb01e8a3e), Int32(bitPattern: 0xd71577c1), Int32(bitPattern: 0xbd314b27), Int32(bitPattern: 0x78af2fda), Int32(bitPattern: 0x55605c60), Int32(bitPattern: 0xe65525f3), Int32(bitPattern: 0xaa55ab94), Int32(bitPattern: 0x57489862), Int32(bitPattern: 0x63e81440), Int32(bitPattern: 0x55ca396a), Int32(bitPattern: 0x2aab10b6), Int32(bitPattern: 0xb4cc5c34), Int32(bitPattern: 0x1141e8ce), Int32(bitPattern: 0xa15486af), Int32(bitPattern: 0x7c72e993), Int32(bitPattern: 0xb3ee1411), Int32(bitPattern: 0x636fbc2a), Int32(bitPattern: 0x2ba9c55d), Int32(bitPattern: 0x741831f6), Int32(bitPattern: 0xce5c3e16), Int32(bitPattern: 0x9b87931e), Int32(bitPattern: 0xafd6ba33), Int32(bitPattern: 0x6c24cf5c), Int32(bitPattern: 0x7a325381), Int32(bitPattern: 0x28958677), Int32(bitPattern: 0x3b8f4898), Int32(bitPattern: 0x6b4bb9af), Int32(bitPattern: 0xc4bfe81b), Int32(bitPattern: 0x66282193), Int32(bitPattern: 0x61d809cc), Int32(bitPattern: 0xfb21a991), Int32(bitPattern: 0x487cac60), Int32(bitPattern: 0x5dec8032), Int32(bitPattern: 0xef845d5d), Int32(bitPattern: 0xe98575b1), Int32(bitPattern: 0xdc262302), Int32(bitPattern: 0xeb651b88), Int32(bitPattern: 0x23893e81), Int32(bitPattern: 0xd396acc5), Int32(bitPattern: 0x0f6d6ff3), Int32(bitPattern: 0x83f44239), Int32(bitPattern: 0x2e0b4482), Int32(bitPattern: 0xa4842004), Int32(bitPattern: 0x69c8f04a), Int32(bitPattern: 0x9e1f9b5e), Int32(bitPattern: 0x21c66842), Int32(bitPattern: 0xf6e96c9a), Int32(bitPattern: 0x670c9c61), Int32(bitPattern: 0xabd388f0), Int32(bitPattern: 0x6a51a0d2), Int32(bitPattern: 0xd8542f68), Int32(bitPattern: 0x960fa728), Int32(bitPattern: 0xab5133a3), Int32(bitPattern: 0x6eef0b6c), Int32(bitPattern: 0x137a3be4), Int32(bitPattern: 0xba3bf050), Int32(bitPattern: 0x7efb2a98), Int32(bitPattern: 0xa1f1651d), Int32(bitPattern: 0x39af0176), Int32(bitPattern: 0x66ca593e), Int32(bitPattern: 0x82430e88), Int32(bitPattern: 0x8cee8619), Int32(bitPattern: 0x456f9fb4), Int32(bitPattern: 0x7d84a5c3), Int32(bitPattern: 0x3b8b5ebe), Int32(bitPattern: 0xe06f75d8), Int32(bitPattern: 0x85c12073), Int32(bitPattern: 0x401a449f), Int32(bitPattern: 0x56c16aa6), Int32(bitPattern: 0x4ed3aa62), Int32(bitPattern: 0x363f7706), Int32(bitPattern: 0x1bfedf72), Int32(bitPattern: 0x429b023d), Int32(bitPattern: 0x37d0d724), Int32(bitPattern: 0xd00a1248), Int32(bitPattern: 0xdb0fead3), Int32(bitPattern: 0x49f1c09b), Int32(bitPattern: 0x075372c9), Int32(bitPattern: 0x80991b7b), Int32(bitPattern: 0x25d479d8), Int32(bitPattern: 0xf6e8def7), Int32(bitPattern: 0xe3fe501a), Int32(bitPattern: 0xb6794c3b), Int32(bitPattern: 0x976ce0bd), Int32(bitPattern: 0x04c006ba), Int32(bitPattern: 0xc1a94fb6), Int32(bitPattern: 0x409f60c4), Int32(bitPattern: 0x5e5c9ec2), Int32(bitPattern: 0x196a2463), Int32(bitPattern: 0x68fb6faf), Int32(bitPattern: 0x3e6c53b5), Int32(bitPattern: 0x1339b2eb), Int32(bitPattern: 0x3b52ec6f), Int32(bitPattern: 0x6dfc511f), Int32(bitPattern: 0x9b30952c), Int32(bitPattern: 0xcc814544), Int32(bitPattern: 0xaf5ebd09), Int32(bitPattern: 0xbee3d004), Int32(bitPattern: 0xde334afd), Int32(bitPattern: 0x660f2807), Int32(bitPattern: 0x192e4bb3), Int32(bitPattern: 0xc0cba857), Int32(bitPattern: 0x45c8740f), Int32(bitPattern: 0xd20b5f39), Int32(bitPattern: 0xb9d3fbdb), Int32(bitPattern: 0x5579c0bd), Int32(bitPattern: 0x1a60320a), Int32(bitPattern: 0xd6a100c6), Int32(bitPattern: 0x402c7279), Int32(bitPattern: 0x679f25fe), Int32(bitPattern: 0xfb1fa3cc), Int32(bitPattern: 0x8ea5e9f8), Int32(bitPattern: 0xdb3222f8), Int32(bitPattern: 0x3c7516df), Int32(bitPattern: 0xfd616b15), Int32(bitPattern: 0x2f501ec8), Int32(bitPattern: 0xad0552ab), Int32(bitPattern: 0x323db5fa), Int32(bitPattern: 0xfd238760), Int32(bitPattern: 0x53317b48), Int32(bitPattern: 0x3e00df82), Int32(bitPattern: 0x9e5c57bb), Int32(bitPattern: 0xca6f8ca0), Int32(bitPattern: 0x1a87562e), Int32(bitPattern: 0xdf1769db), Int32(bitPattern: 0xd542a8f6), Int32(bitPattern: 0x287effc3), Int32(bitPattern: 0xac6732c6), Int32(bitPattern: 0x8c4f5573), Int32(bitPattern: 0x695b27b0), Int32(bitPattern: 0xbbca58c8), Int32(bitPattern: 0xe1ffa35d), Int32(bitPattern: 0xb8f011a0), Int32(bitPattern: 0x10fa3d98), Int32(bitPattern: 0xfd2183b8), Int32(bitPattern: 0x4afcb56c), Int32(bitPattern: 0x2dd1d35b), Int32(bitPattern: 0x9a53e479), Int32(bitPattern: 0xb6f84565), Int32(bitPattern: 0xd28e49bc), Int32(bitPattern: 0x4bfb9790), Int32(bitPattern: 0xe1ddf2da), Int32(bitPattern: 0xa4cb7e33), Int32(bitPattern: 0x62fb1341), Int32(bitPattern: 0xcee4c6e8), Int32(bitPattern: 0xef20cada), Int32(bitPattern: 0x36774c01), Int32(bitPattern: 0xd07e9efe), Int32(bitPattern: 0x2bf11fb4), Int32(bitPattern: 0x95dbda4d), Int32(bitPattern: 0xae909198), Int32(bitPattern: 0xeaad8e71), Int32(bitPattern: 0x6b93d5a0), Int32(bitPattern: 0xd08ed1d0), Int32(bitPattern: 0xafc725e0), Int32(bitPattern: 0x8e3c5b2f), Int32(bitPattern: 0x8e7594b7), Int32(bitPattern: 0x8ff6e2fb), Int32(bitPattern: 0xf2122b64), Int32(bitPattern: 0x8888b812), Int32(bitPattern: 0x900df01c), Int32(bitPattern: 0x4fad5ea0), Int32(bitPattern: 0x688fc31c), Int32(bitPattern: 0xd1cff191), Int32(bitPattern: 0xb3a8c1ad), Int32(bitPattern: 0x2f2f2218), Int32(bitPattern: 0xbe0e1777), Int32(bitPattern: 0xea752dfe), Int32(bitPattern: 0x8b021fa1), Int32(bitPattern: 0xe5a0cc0f), Int32(bitPattern: 0xb56f74e8), Int32(bitPattern: 0x18acf3d6), Int32(bitPattern: 0xce89e299), Int32(bitPattern: 0xb4a84fe0), Int32(bitPattern: 0xfd13e0b7), Int32(bitPattern: 0x7cc43b81), Int32(bitPattern: 0xd2ada8d9), Int32(bitPattern: 0x165fa266), Int32(bitPattern: 0x80957705), Int32(bitPattern: 0x93cc7314), Int32(bitPattern: 0x211a1477), Int32(bitPattern: 0xe6ad2065), Int32(bitPattern: 0x77b5fa86), Int32(bitPattern: 0xc75442f5), Int32(bitPattern: 0xfb9d35cf), Int32(bitPattern: 0xebcdaf0c), Int32(bitPattern: 0x7b3e89a0), Int32(bitPattern: 0xd6411bd3), Int32(bitPattern: 0xae1e7e49), Int32(bitPattern: 0x00250e2d), Int32(bitPattern: 0x2071b35e), Int32(bitPattern: 0x226800bb), Int32(bitPattern: 0x57b8e0af), Int32(bitPattern: 0x2464369b), Int32(bitPattern: 0xf009b91e), Int32(bitPattern: 0x5563911d), Int32(bitPattern: 0x59dfa6aa), Int32(bitPattern: 0x78c14389), Int32(bitPattern: 0xd95a537f), Int32(bitPattern: 0x207d5ba2), Int32(bitPattern: 0x02e5b9c5), Int32(bitPattern: 0x83260376), Int32(bitPattern: 0x6295cfa9), Int32(bitPattern: 0x11c81968), Int32(bitPattern: 0x4e734a41), Int32(bitPattern: 0xb3472dca), Int32(bitPattern: 0x7b14a94a), Int32(bitPattern: 0x1b510052), Int32(bitPattern: 0x9a532915), Int32(bitPattern: 0xd60f573f), Int32(bitPattern: 0xbc9bc6e4), Int32(bitPattern: 0x2b60a476), Int32(bitPattern: 0x81e67400), Int32(bitPattern: 0x08ba6fb5), Int32(bitPattern: 0x571be91f), Int32(bitPattern: 0xf296ec6b), Int32(bitPattern: 0x2a0dd915), Int32(bitPattern: 0xb6636521), Int32(bitPattern: 0xe7b9f9b6), Int32(bitPattern: 0xff34052e), Int32(bitPattern: 0xc5855664), Int32(bitPattern: 0x53b02d5d), Int32(bitPattern: 0xa99f8fa1), Int32(bitPattern: 0x08ba4799), Int32(bitPattern: 0x6e85076a), Int32(bitPattern: 0x4b7a70e9), Int32(bitPattern: 0xb5b32944), Int32(bitPattern: 0xdb75092e), Int32(bitPattern: 0xc4192623), Int32(bitPattern: 0xad6ea6b0), Int32(bitPattern: 0x49a7df7d), Int32(bitPattern: 0x9cee60b8), Int32(bitPattern: 0x8fedb266), Int32(bitPattern: 0xecaa8c71), Int32(bitPattern: 0x699a17ff), Int32(bitPattern: 0x5664526c), Int32(bitPattern: 0xc2b19ee1), Int32(bitPattern: 0x193602a5), Int32(bitPattern: 0x75094c29), Int32(bitPattern: 0xa0591340), Int32(bitPattern: 0xe4183a3e), Int32(bitPattern: 0x3f54989a), Int32(bitPattern: 0x5b429d65), Int32(bitPattern: 0x6b8fe4d6), Int32(bitPattern: 0x99f73fd6), Int32(bitPattern: 0xa1d29c07), Int32(bitPattern: 0xefe830f5), Int32(bitPattern: 0x4d2d38e6), Int32(bitPattern: 0xf0255dc1), Int32(bitPattern: 0x4cdd2086), Int32(bitPattern: 0x8470eb26), Int32(bitPattern: 0x6382e9c6), Int32(bitPattern: 0x021ecc5e), Int32(bitPattern: 0x09686b3f), Int32(bitPattern: 0x3ebaefc9), Int32(bitPattern: 0x3c971814), Int32(bitPattern: 0x6b6a70a1), Int32(bitPattern: 0x687f3584), Int32(bitPattern: 0x52a0e286), Int32(bitPattern: 0xb79c5305), Int32(bitPattern: 0xaa500737), Int32(bitPattern: 0x3e07841c), Int32(bitPattern: 0x7fdeae5c), Int32(bitPattern: 0x8e7d44ec), Int32(bitPattern: 0x5716f2b8), Int32(bitPattern: 0xb03ada37), Int32(bitPattern: 0xf0500c0d), Int32(bitPattern: 0xf01c1f04), Int32(bitPattern: 0x0200b3ff), Int32(bitPattern: 0xae0cf51a), Int32(bitPattern: 0x3cb574b2), Int32(bitPattern: 0x25837a58), Int32(bitPattern: 0xdc0921bd), Int32(bitPattern: 0xd19113f9), Int32(bitPattern: 0x7ca92ff6), Int32(bitPattern: 0x94324773), Int32(bitPattern: 0x22f54701), Int32(bitPattern: 0x3ae5e581), Int32(bitPattern: 0x37c2dadc), Int32(bitPattern: 0xc8b57634), Int32(bitPattern: 0x9af3dda7), Int32(bitPattern: 0xa9446146), Int32(bitPattern: 0x0fd0030e), Int32(bitPattern: 0xecc8c73e), Int32(bitPattern: 0xa4751e41), Int32(bitPattern: 0xe238cd99), Int32(bitPattern: 0x3bea0e2f), Int32(bitPattern: 0x3280bba1), Int32(bitPattern: 0x183eb331), Int32(bitPattern: 0x4e548b38), Int32(bitPattern: 0x4f6db908), Int32(bitPattern: 0x6f420d03), Int32(bitPattern: 0xf60a04bf), Int32(bitPattern: 0x2cb81290), Int32(bitPattern: 0x24977c79), Int32(bitPattern: 0x5679b072), Int32(bitPattern: 0xbcaf89af), Int32(bitPattern: 0xde9a771f), Int32(bitPattern: 0xd9930810), Int32(bitPattern: 0xb38bae12), Int32(bitPattern: 0xdccf3f2e), Int32(bitPattern: 0x5512721f), Int32(bitPattern: 0x2e6b7124), Int32(bitPattern: 0x501adde6), Int32(bitPattern: 0x9f84cd87), Int32(bitPattern: 0x7a584718), Int32(bitPattern: 0x7408da17), Int32(bitPattern: 0xbc9f9abc), Int32(bitPattern: 0xe94b7d8c), Int32(bitPattern: 0xec7aec3a), Int32(bitPattern: 0xdb851dfa), Int32(bitPattern: 0x63094366), Int32(bitPattern: 0xc464c3d2), Int32(bitPattern: 0xef1c1847), Int32(bitPattern: 0x3215d908), Int32(bitPattern: 0xdd433b37), Int32(bitPattern: 0x24c2ba16), Int32(bitPattern: 0x12a14d43), Int32(bitPattern: 0x2a65c451), Int32(bitPattern: 0x50940002), Int32(bitPattern: 0x133ae4dd), Int32(bitPattern: 0x71dff89e), Int32(bitPattern: 0x10314e55), Int32(bitPattern: 0x81ac77d6), Int32(bitPattern: 0x5f11199b), Int32(bitPattern: 0x043556f1), Int32(bitPattern: 0xd7a3c76b), Int32(bitPattern: 0x3c11183b), Int32(bitPattern: 0x5924a509), Int32(bitPattern: 0xf28fe6ed), Int32(bitPattern: 0x97f1fbfa), Int32(bitPattern: 0x9ebabf2c), Int32(bitPattern: 0x1e153c6e), Int32(bitPattern: 0x86e34570), Int32(bitPattern: 0xeae96fb1), Int32(bitPattern: 0x860e5e0a), Int32(bitPattern: 0x5a3e2ab3), Int32(bitPattern: 0x771fe71c), Int32(bitPattern: 0x4e3d06fa), Int32(bitPattern: 0x2965dcb9), Int32(bitPattern: 0x99e71d0f), Int32(bitPattern: 0x803e89d6), Int32(bitPattern: 0x5266c825), Int32(bitPattern: 0x2e4cc978), Int32(bitPattern: 0x9c10b36a), Int32(bitPattern: 0xc6150eba), Int32(bitPattern: 0x94e2ea78), Int32(bitPattern: 0xa5fc3c53), Int32(bitPattern: 0x1e0a2df4), Int32(bitPattern: 0xf2f74ea7), Int32(bitPattern: 0x361d2b3d), Int32(bitPattern: 0x1939260f), Int32(bitPattern: 0x19c27960), Int32(bitPattern: 0x5223a708), Int32(bitPattern: 0xf71312b6), Int32(bitPattern: 0xebadfe6e), Int32(bitPattern: 0xeac31f66), Int32(bitPattern: 0xe3bc4595), Int32(bitPattern: 0xa67bc883), Int32(bitPattern: 0xb17f37d1), Int32(bitPattern: 0x018cff28), Int32(bitPattern: 0xc332ddef), Int32(bitPattern: 0xbe6c5aa5), Int32(bitPattern: 0x65582185), Int32(bitPattern: 0x68ab9802), Int32(bitPattern: 0xeecea50f), Int32(bitPattern: 0xdb2f953b), Int32(bitPattern: 0x2aef7dad), Int32(bitPattern: 0x5b6e2f84), Int32(bitPattern: 0x1521b628), Int32(bitPattern: 0x29076170), Int32(bitPattern: 0xecdd4775), Int32(bitPattern: 0x619f1510), Int32(bitPattern: 0x13cca830), Int32(bitPattern: 0xeb61bd96), Int32(bitPattern: 0x0334fe1e), Int32(bitPattern: 0xaa0363cf), Int32(bitPattern: 0xb5735c90), Int32(bitPattern: 0x4c70a239), Int32(bitPattern: 0xd59e9e0b), Int32(bitPattern: 0xcbaade14), Int32(bitPattern: 0xeecc86bc), Int32(bitPattern: 0x60622ca7), Int32(bitPattern: 0x9cab5cab), Int32(bitPattern: 0xb2f3846e), Int32(bitPattern: 0x648b1eaf), Int32(bitPattern: 0x19bdf0ca), Int32(bitPattern: 0xa02369b9), Int32(bitPattern: 0x655abb50), Int32(bitPattern: 0x40685a32), Int32(bitPattern: 0x3c2ab4b3), Int32(bitPattern: 0x319ee9d5), Int32(bitPattern: 0xc021b8f7), Int32(bitPattern: 0x9b540b19), Int32(bitPattern: 0x875fa099), Int32(bitPattern: 0x95f7997e), Int32(bitPattern: 0x623d7da8), Int32(bitPattern: 0xf837889a), Int32(bitPattern: 0x97e32d77), Int32(bitPattern: 0x11ed935f), Int32(bitPattern: 0x16681281), Int32(bitPattern: 0x0e358829), Int32(bitPattern: 0xc7e61fd6), Int32(bitPattern: 0x96dedfa1), Int32(bitPattern: 0x7858ba99), Int32(bitPattern: 0x57f584a5), Int32(bitPattern: 0x1b227263), Int32(bitPattern: 0x9b83c3ff), Int32(bitPattern: 0x1ac24696), Int32(bitPattern: 0xcdb30aeb), Int32(bitPattern: 0x532e3054), Int32(bitPattern: 0x8fd948e4), Int32(bitPattern: 0x6dbc3128), Int32(bitPattern: 0x58ebf2ef), Int32(bitPattern: 0x34c6ffea), Int32(bitPattern: 0xfe28ed61), Int32(bitPattern: 0xee7c3c73), Int32(bitPattern: 0x5d4a14d9), Int32(bitPattern: 0xe864b7e3), Int32(bitPattern: 0x42105d14), Int32(bitPattern: 0x203e13e0), Int32(bitPattern: 0x45eee2b6), Int32(bitPattern: 0xa3aaabea), Int32(bitPattern: 0xdb6c4f15), Int32(bitPattern: 0xfacb4fd0), Int32(bitPattern: 0xc742f442), Int32(bitPattern: 0xef6abbb5), Int32(bitPattern: 0x654f3b1d), Int32(bitPattern: 0x41cd2105), Int32(bitPattern: 0xd81e799e), Int32(bitPattern: 0x86854dc7), Int32(bitPattern: 0xe44b476a), Int32(bitPattern: 0x3d816250), Int32(bitPattern: 0xcf62a1f2), Int32(bitPattern: 0x5b8d2646), Int32(bitPattern: 0xfc8883a0), Int32(bitPattern: 0xc1c7b6a3), Int32(bitPattern: 0x7f1524c3), Int32(bitPattern: 0x69cb7492), Int32(bitPattern: 0x47848a0b), Int32(bitPattern: 0x5692b285), Int32(bitPattern: 0x095bbf00), Int32(bitPattern: 0xad19489d), Int32(bitPattern: 0x1462b174), Int32(bitPattern: 0x23820e00), Int32(bitPattern: 0x58428d2a), Int32(bitPattern: 0x0c55f5ea), Int32(bitPattern: 0x1dadf43e), Int32(bitPattern: 0x233f7061), Int32(bitPattern: 0x3372f092), Int32(bitPattern: 0x8d937e41), Int32(bitPattern: 0xd65fecf1), Int32(bitPattern: 0x6c223bdb), Int32(bitPattern: 0x7cde3759), Int32(bitPattern: 0xcbee7460), Int32(bitPattern: 0x4085f2a7), Int32(bitPattern: 0xce77326e), Int32(bitPattern: 0xa6078084), Int32(bitPattern: 0x19f8509e), Int32(bitPattern: 0xe8efd855), Int32(bitPattern: 0x61d99735), Int32(bitPattern: 0xa969a7aa), Int32(bitPattern: 0xc50c06c2), Int32(bitPattern: 0x5a04abfc), Int32(bitPattern: 0x800bcadc), Int32(bitPattern: 0x9e447a2e), Int32(bitPattern: 0xc3453484), Int32(bitPattern: 0xfdd56705), Int32(bitPattern: 0x0e1e9ec9), Int32(bitPattern: 0xdb73dbd3), Int32(bitPattern: 0x105588cd), Int32(bitPattern: 0x675fda79), Int32(bitPattern: 0xe3674340), Int32(bitPattern: 0xc5c43465), Int32(bitPattern: 0x713e38d8), Int32(bitPattern: 0x3d28f89e), Int32(bitPattern: 0xf16dff20), Int32(bitPattern: 0x153e21e7), Int32(bitPattern: 0x8fb03d4a), Int32(bitPattern: 0xe6e39f2b), Int32(bitPattern: 0xdb83adf7), Int32(bitPattern: 0xe93d5a68), Int32(bitPattern: 0x948140f7), Int32(bitPattern: 0xf64c261c), Int32(bitPattern: 0x94692934), Int32(bitPattern: 0x411520f7), Int32(bitPattern: 0x7602d4f7), Int32(bitPattern: 0xbcf46b2e), Int32(bitPattern: 0xd4a20068), Int32(bitPattern: 0xd4082471), Int32(bitPattern: 0x3320f46a), Int32(bitPattern: 0x43b7d4b7), Int32(bitPattern: 0x500061af), Int32(bitPattern: 0x1e39f62e), Int32(bitPattern: 0x97244546), Int32(bitPattern: 0x14214f74), Int32(bitPattern: 0xbf8b8840), Int32(bitPattern: 0x4d95fc1d), Int32(bitPattern: 0x96b591af), Int32(bitPattern: 0x70f4ddd3), Int32(bitPattern: 0x66a02f45), Int32(bitPattern: 0xbfbc09ec), Int32(bitPattern: 0x03bd9785), Int32(bitPattern: 0x7fac6dd0), Int32(bitPattern: 0x31cb8504), Int32(bitPattern: 0x96eb27b3), Int32(bitPattern: 0x55fd3941), Int32(bitPattern: 0xda2547e6), Int32(bitPattern: 0xabca0a9a), Int32(bitPattern: 0x28507825), Int32(bitPattern: 0x530429f4), Int32(bitPattern: 0x0a2c86da), Int32(bitPattern: 0xe9b66dfb), Int32(bitPattern: 0x68dc1462), Int32(bitPattern: 0xd7486900), Int32(bitPattern: 0x680ec0a4), Int32(bitPattern: 0x27a18dee), Int32(bitPattern: 0x4f3ffea2), Int32(bitPattern: 0xe887ad8c), Int32(bitPattern: 0xb58ce006), Int32(bitPattern: 0x7af4d6b6), Int32(bitPattern: 0xaace1e7c), Int32(bitPattern: 0xd3375fec), Int32(bitPattern: 0xce78a399), Int32(bitPattern: 0x406b2a42), Int32(bitPattern: 0x20fe9e35), Int32(bitPattern: 0xd9f385b9), Int32(bitPattern: 0xee39d7ab), Int32(bitPattern: 0x3b124e8b), Int32(bitPattern: 0x1dc9faf7), Int32(bitPattern: 0x4b6d1856), Int32(bitPattern: 0x26a36631), Int32(bitPattern: 0xeae397b2), Int32(bitPattern: 0x3a6efa74), Int32(bitPattern: 0xdd5b4332), Int32(bitPattern: 0x6841e7f7), Int32(bitPattern: 0xca7820fb), Int32(bitPattern: 0xfb0af54e), Int32(bitPattern: 0xd8feb397), Int32(bitPattern: 0x454056ac), Int32(bitPattern: 0xba489527), Int32(bitPattern: 0x55533a3a), Int32(bitPattern: 0x20838d87), Int32(bitPattern: 0xfe6ba9b7), Int32(bitPattern: 0xd096954b), Int32(bitPattern: 0x55a867bc), Int32(bitPattern: 0xa1159a58), Int32(bitPattern: 0xcca92963), Int32(bitPattern: 0x99e1db33), Int32(bitPattern: 0xa62a4a56), Int32(bitPattern: 0x3f3125f9), Int32(bitPattern: 0x5ef47e1c), Int32(bitPattern: 0x9029317c), Int32(bitPattern: 0xfdf8e802), Int32(bitPattern: 0x04272f70), Int32(bitPattern: 0x80bb155c), Int32(bitPattern: 0x05282ce3), Int32(bitPattern: 0x95c11548), Int32(bitPattern: 0xe4c66d22), Int32(bitPattern: 0x48c1133f), Int32(bitPattern: 0xc70f86dc), Int32(bitPattern: 0x07f9c9ee), Int32(bitPattern: 0x41041f0f), Int32(bitPattern: 0x404779a4), Int32(bitPattern: 0x5d886e17), Int32(bitPattern: 0x325f51eb), Int32(bitPattern: 0xd59bc0d1), Int32(bitPattern: 0xf2bcc18f), Int32(bitPattern: 0x41113564), Int32(bitPattern: 0x257b7834), Int32(bitPattern: 0x602a9c60), Int32(bitPattern: 0xdff8e8a3), Int32(bitPattern: 0x1f636c1b), Int32(bitPattern: 0x0e12b4c2), Int32(bitPattern: 0x02e1329e), Int32(bitPattern: 0xaf664fd1), Int32(bitPattern: 0xcad18115), Int32(bitPattern: 0x6b2395e0), Int32(bitPattern: 0x333e92e1), Int32(bitPattern: 0x3b240b62), Int32(bitPattern: 0xeebeb922), Int32(bitPattern: 0x85b2a20e), Int32(bitPattern: 0xe6ba0d99), Int32(bitPattern: 0xde720c8c), Int32(bitPattern: 0x2da2f728), Int32(bitPattern: 0xd0127845), Int32(bitPattern: 0x95b794fd), Int32(bitPattern: 0x647d0862), Int32(bitPattern: 0xe7ccf5f0), Int32(bitPattern: 0x5449a36f), Int32(bitPattern: 0x877d48fa), Int32(bitPattern: 0xc39dfd27), Int32(bitPattern: 0xf33e8d1e), Int32(bitPattern: 0x0a476341), Int32(bitPattern: 0x992eff74), Int32(bitPattern: 0x3a6f6eab), Int32(bitPattern: 0xf4f8fd37), Int32(bitPattern: 0xa812dc60), Int32(bitPattern: 0xa1ebddf8), Int32(bitPattern: 0x991be14c), Int32(bitPattern: 0xdb6e6b0d), Int32(bitPattern: 0xc67b5510), Int32(bitPattern: 0x6d672c37), Int32(bitPattern: 0x2765d43b), Int32(bitPattern: 0xdcd0e804), Int32(bitPattern: 0xf1290dc7), Int32(bitPattern: 0xcc00ffa3), Int32(bitPattern: 0xb5390f92), Int32(bitPattern: 0x690fed0b), Int32(bitPattern: 0x667b9ffb), Int32(bitPattern: 0xcedb7d9c), Int32(bitPattern: 0xa091cf0b), Int32(bitPattern: 0xd9155ea3), Int32(bitPattern: 0xbb132f88), Int32(bitPattern: 0x515bad24), Int32(bitPattern: 0x7b9479bf), Int32(bitPattern: 0x763bd6eb), Int32(bitPattern: 0x37392eb3), Int32(bitPattern: 0xcc115979), Int32(bitPattern: 0x8026e297), Int32(bitPattern: 0xf42e312d), Int32(bitPattern: 0x6842ada7), Int32(bitPattern: 0xc66a2b3b), Int32(bitPattern: 0x12754ccc), Int32(bitPattern: 0x782ef11c), Int32(bitPattern: 0x6a124237), Int32(bitPattern: 0xb79251e7), Int32(bitPattern: 0x06a1bbe6), Int32(bitPattern: 0x4bfb6350), Int32(bitPattern: 0x1a6b1018), Int32(bitPattern: 0x11caedfa), Int32(bitPattern: 0x3d25bdd8), Int32(bitPattern: 0xe2e1c3c9), Int32(bitPattern: 0x44421659), Int32(bitPattern: 0x0a121386), Int32(bitPattern: 0xd90cec6e), Int32(bitPattern: 0xd5abea2a), Int32(bitPattern: 0x64af674e), Int32(bitPattern: 0xda86a85f), Int32(bitPattern: 0xbebfe988), Int32(bitPattern: 0x64e4c3fe), Int32(bitPattern: 0x9dbc8057), Int32(bitPattern: 0xf0f7c086), Int32(bitPattern: 0x60787bf8), Int32(bitPattern: 0x6003604d), Int32(bitPattern: 0xd1fd8346), Int32(bitPattern: 0xf6381fb0), Int32(bitPattern: 0x7745ae04), Int32(bitPattern: 0xd736fccc), Int32(bitPattern: 0x83426b33), Int32(bitPattern: 0xf01eab71), Int32(bitPattern: 0xb0804187), Int32(bitPattern: 0x3c005e5f), Int32(bitPattern: 0x77a057be), Int32(bitPattern: 0xbde8ae24), Int32(bitPattern: 0x55464299), Int32(bitPattern: 0xbf582e61), Int32(bitPattern: 0x4e58f48f), Int32(bitPattern: 0xf2ddfda2), Int32(bitPattern: 0xf474ef38), Int32(bitPattern: 0x8789bdc2), Int32(bitPattern: 0x5366f9c3), Int32(bitPattern: 0xc8b38e74), Int32(bitPattern: 0xb475f255), Int32(bitPattern: 0x46fcd9b9), Int32(bitPattern: 0x7aeb2661), Int32(bitPattern: 0x8b1ddf84), Int32(bitPattern: 0x846a0e79), Int32(bitPattern: 0x915f95e2), Int32(bitPattern: 0x466e598e), Int32(bitPattern: 0x20b45770), Int32(bitPattern: 0x8cd55591), Int32(bitPattern: 0xc902de4c), Int32(bitPattern: 0xb90bace1), Int32(bitPattern: 0xbb8205d0), Int32(bitPattern: 0x11a86248), Int32(bitPattern: 0x7574a99e), Int32(bitPattern: 0xb77f19b6), Int32(bitPattern: 0xe0a9dc09), Int32(bitPattern: 0x662d09a1), Int32(bitPattern: 0xc4324633), Int32(bitPattern: 0xe85a1f02), Int32(bitPattern: 0x09f0be8c), Int32(bitPattern: 0x4a99a025), Int32(bitPattern: 0x1d6efe10), Int32(bitPattern: 0x1ab93d1d), Int32(bitPattern: 0x0ba5a4df), Int32(bitPattern: 0xa186f20f), Int32(bitPattern: 0x2868f169), Int32(bitPattern: 0xdcb7da83), Int32(bitPattern: 0x573906fe), Int32(bitPattern: 0xa1e2ce9b), Int32(bitPattern: 0x4fcd7f52), Int32(bitPattern: 0x50115e01), Int32(bitPattern: 0xa70683fa), Int32(bitPattern: 0xa002b5c4), Int32(bitPattern: 0x0de6d027), Int32(bitPattern: 0x9af88c27), Int32(bitPattern: 0x773f8641), Int32(bitPattern: 0xc3604c06), Int32(bitPattern: 0x61a806b5), Int32(bitPattern: 0xf0177a28), Int32(bitPattern: 0xc0f586e0), Int32(bitPattern: 0x006058aa), Int32(bitPattern: 0x30dc7d62), Int32(bitPattern: 0x11e69ed7), Int32(bitPattern: 0x2338ea63), Int32(bitPattern: 0x53c2dd94), Int32(bitPattern: 0xc2c21634), Int32(bitPattern: 0xbbcbee56), Int32(bitPattern: 0x90bcb6de), Int32(bitPattern: 0xebfc7da1), Int32(bitPattern: 0xce591d76), Int32(bitPattern: 0x6f05e409), Int32(bitPattern: 0x4b7c0188), Int32(bitPattern: 0x39720a3d), Int32(bitPattern: 0x7c927c24), Int32(bitPattern: 0x86e3725f), Int32(bitPattern: 0x724d9db9), Int32(bitPattern: 0x1ac15bb4), Int32(bitPattern: 0xd39eb8fc), Int32(bitPattern: 0xed545578), Int32(bitPattern: 0x08fca5b5), Int32(bitPattern: 0xd83d7cd3), Int32(bitPattern: 0x4dad0fc4), Int32(bitPattern: 0x1e50ef5e), Int32(bitPattern: 0xb161e6f8), Int32(bitPattern: 0xa28514d9), Int32(bitPattern: 0x6c51133c), Int32(bitPattern: 0x6fd5c7e7), Int32(bitPattern: 0x56e14ec4), Int32(bitPattern: 0x362abfce), Int32(bitPattern: 0xddc6c837), Int32(bitPattern: 0xd79a3234), Int32(bitPattern: 0x92638212), Int32(bitPattern: 0x670efa8e), Int32(bitPattern: 0x406000e0), Int32(bitPattern: 0x3a39ce37), Int32(bitPattern: 0xd3faf5cf), Int32(bitPattern: 0xabc27737), Int32(bitPattern: 0x5ac52d1b), Int32(bitPattern: 0x5cb0679e), Int32(bitPattern: 0x4fa33742), Int32(bitPattern: 0xd3822740), Int32(bitPattern: 0x99bc9bbe), Int32(bitPattern: 0xd5118e9d), Int32(bitPattern: 0xbf0f7315), Int32(bitPattern: 0xd62d1c7e), Int32(bitPattern: 0xc700c47b), Int32(bitPattern: 0xb78c1b6b), Int32(bitPattern: 0x21a19045), Int32(bitPattern: 0xb26eb1be), Int32(bitPattern: 0x6a366eb4), Int32(bitPattern: 0x5748ab2f), Int32(bitPattern: 0xbc946e79), Int32(bitPattern: 0xc6a376d2), Int32(bitPattern: 0x6549c2c8), Int32(bitPattern: 0x530ff8ee), Int32(bitPattern: 0x468dde7d), Int32(bitPattern: 0xd5730a1d), Int32(bitPattern: 0x4cd04dc6), Int32(bitPattern: 0x2939bbdb), Int32(bitPattern: 0xa9ba4650), Int32(bitPattern: 0xac9526e8), Int32(bitPattern: 0xbe5ee304), Int32(bitPattern: 0xa1fad5f0), Int32(bitPattern: 0x6a2d519a), Int32(bitPattern: 0x63ef8ce2), Int32(bitPattern: 0x9a86ee22), Int32(bitPattern: 0xc089c2b8), Int32(bitPattern: 0x43242ef6), Int32(bitPattern: 0xa51e03aa), Int32(bitPattern: 0x9cf2d0a4), Int32(bitPattern: 0x83c061ba), Int32(bitPattern: 0x9be96a4d), Int32(bitPattern: 0x8fe51550), Int32(bitPattern: 0xba645bd6), Int32(bitPattern: 0x2826a2f9), Int32(bitPattern: 0xa73a3ae1), Int32(bitPattern: 0x4ba99586), Int32(bitPattern: 0xef5562e9), Int32(bitPattern: 0xc72fefd3), Int32(bitPattern: 0xf752f7da), Int32(bitPattern: 0x3f046f69), Int32(bitPattern: 0x77fa0a59), Int32(bitPattern: 0x80e4a915), Int32(bitPattern: 0x87b08601), Int32(bitPattern: 0x9b09e6ad), Int32(bitPattern: 0x3b3ee593), Int32(bitPattern: 0xe990fd5a), Int32(bitPattern: 0x9e34d797), Int32(bitPattern: 0x2cf0b7d9), Int32(bitPattern: 0x022b8b51), Int32(bitPattern: 0x96d5ac3a), Int32(bitPattern: 0x017da67d), Int32(bitPattern: 0xd1cf3ed6), Int32(bitPattern: 0x7c7d2d28), Int32(bitPattern: 0x1f9f25cf), Int32(bitPattern: 0xadf2b89b), Int32(bitPattern: 0x5ad6b472), Int32(bitPattern: 0x5a88f54c), Int32(bitPattern: 0xe029ac71), Int32(bitPattern: 0xe019a5e6), Int32(bitPattern: 0x47b0acfd), Int32(bitPattern: 0xed93fa9b), Int32(bitPattern: 0xe8d3c48d), Int32(bitPattern: 0x283b57cc), Int32(bitPattern: 0xf8d56629), Int32(bitPattern: 0x79132e28), Int32(bitPattern: 0x785f0191), Int32(bitPattern: 0xed756055), Int32(bitPattern: 0xf7960e44), Int32(bitPattern: 0xe3d35e8c), Int32(bitPattern: 0x15056dd4), Int32(bitPattern: 0x88f46dba), Int32(bitPattern: 0x03a16125), Int32(bitPattern: 0x0564f0bd), Int32(bitPattern: 0xc3eb9e15), Int32(bitPattern: 0x3c9057a2), Int32(bitPattern: 0x97271aec), Int32(bitPattern: 0xa93a072a), Int32(bitPattern: 0x1b3f6d9b), Int32(bitPattern: 0x1e6321f5), Int32(bitPattern: 0xf59c66fb), Int32(bitPattern: 0x26dcf319), Int32(bitPattern: 0x7533d928), Int32(bitPattern: 0xb155fdf5), Int32(bitPattern: 0x03563482), Int32(bitPattern: 0x8aba3cbb), Int32(bitPattern: 0x28517711), Int32(bitPattern: 0xc20ad9f8), Int32(bitPattern: 0xabcc5167), Int32(bitPattern: 0xccad925f), Int32(bitPattern: 0x4de81751), Int32(bitPattern: 0x3830dc8e), Int32(bitPattern: 0x379d5862), Int32(bitPattern: 0x9320f991), Int32(bitPattern: 0xea7a90c2), Int32(bitPattern: 0xfb3e7bce), Int32(bitPattern: 0x5121ce64), Int32(bitPattern: 0x774fbe32), Int32(bitPattern: 0xa8b6e37e), Int32(bitPattern: 0xc3293d46), Int32(bitPattern: 0x48de5369), Int32(bitPattern: 0x6413e680), Int32(bitPattern: 0xa2ae0810), Int32(bitPattern: 0xdd6db224), Int32(bitPattern: 0x69852dfd), Int32(bitPattern: 0x09072166), Int32(bitPattern: 0xb39a460a), Int32(bitPattern: 0x6445c0dd), Int32(bitPattern: 0x586cdecf), Int32(bitPattern: 0x1c20c8ae), Int32(bitPattern: 0x5bbef7dd), Int32(bitPattern: 0x1b588d40), Int32(bitPattern: 0xccd2017f), Int32(bitPattern: 0x6bb4e3bb), Int32(bitPattern: 0xdda26a7e), Int32(bitPattern: 0x3a59ff45), Int32(bitPattern: 0x3e350a44), Int32(bitPattern: 0xbcb4cdd5), Int32(bitPattern: 0x72eacea8), Int32(bitPattern: 0xfa6484bb), Int32(bitPattern: 0x8d6612ae), Int32(bitPattern: 0xbf3c6f47), Int32(bitPattern: 0xd29be463), Int32(bitPattern: 0x542f5d9e), Int32(bitPattern: 0xaec2771b), Int32(bitPattern: 0xf64e6370), Int32(bitPattern: 0x740e0d8d), Int32(bitPattern: 0xe75b1357), Int32(bitPattern: 0xf8721671), Int32(bitPattern: 0xaf537d5d), Int32(bitPattern: 0x4040cb08), Int32(bitPattern: 0x4eb4e2cc), Int32(bitPattern: 0x34d2466a), Int32(bitPattern: 0x0115af84), Int32(bitPattern: 0xe1b00428), Int32(bitPattern: 0x95983a1d), Int32(bitPattern: 0x06b89fb4), Int32(bitPattern: 0xce6ea048), Int32(bitPattern: 0x6f3f3b82), Int32(bitPattern: 0x3520ab82), Int32(bitPattern: 0x011a1d4b), Int32(bitPattern: 0x277227f8), Int32(bitPattern: 0x611560b1), Int32(bitPattern: 0xe7933fdc), Int32(bitPattern: 0xbb3a792b), Int32(bitPattern: 0x344525bd), Int32(bitPattern: 0xa08839e1), Int32(bitPattern: 0x51ce794b), Int32(bitPattern: 0x2f32c9b7), Int32(bitPattern: 0xa01fbac9), Int32(bitPattern: 0xe01cc87e), Int32(bitPattern: 0xbcc7d1f6), Int32(bitPattern: 0xcf0111c3), Int32(bitPattern: 0xa1e8aac7), Int32(bitPattern: 0x1a908749), Int32(bitPattern: 0xd44fbd9a), Int32(bitPattern: 0xd0dadecb), Int32(bitPattern: 0xd50ada38), Int32(bitPattern: 0x0339c32a), Int32(bitPattern: 0xc6913667), Int32(bitPattern: 0x8df9317c), Int32(bitPattern: 0xe0b12b4f), Int32(bitPattern: 0xf79e59b7), Int32(bitPattern: 0x43f5bb3a), Int32(bitPattern: 0xf2d519ff), Int32(bitPattern: 0x27d9459c), Int32(bitPattern: 0xbf97222c), Int32(bitPattern: 0x15e6fc2a), Int32(bitPattern: 0x0f91fc71), Int32(bitPattern: 0x9b941525), Int32(bitPattern: 0xfae59361), Int32(bitPattern: 0xceb69ceb), Int32(bitPattern: 0xc2a86459), Int32(bitPattern: 0x12baa8d1), Int32(bitPattern: 0xb6c1075e), Int32(bitPattern: 0xe3056a0c), Int32(bitPattern: 0x10d25065), Int32(bitPattern: 0xcb03a442), Int32(bitPattern: 0xe0ec6e0e), Int32(bitPattern: 0x1698db3b), Int32(bitPattern: 0x4c98a0be), Int32(bitPattern: 0x3278e964), Int32(bitPattern: 0x9f1f9532), Int32(bitPattern: 0xe0d392df), Int32(bitPattern: 0xd3a0342b), Int32(bitPattern: 0x8971f21e), Int32(bitPattern: 0x1b0a7441), Int32(bitPattern: 0x4ba3348c), Int32(bitPattern: 0xc5be7120), Int32(bitPattern: 0xc37632d8), Int32(bitPattern: 0xdf359f8d), Int32(bitPattern: 0x9b992f2e), Int32(bitPattern: 0xe60b6f47), Int32(bitPattern: 0x0fe3f11d), Int32(bitPattern: 0xe54cda54), Int32(bitPattern: 0x1edad891), Int32(bitPattern: 0xce6279cf), Int32(bitPattern: 0xcd3e7e6f), Int32(bitPattern: 0x1618b166), Int32(bitPattern: 0xfd2c1d05), Int32(bitPattern: 0x848fd2c5), Int32(bitPattern: 0xf6fb2299), Int32(bitPattern: 0xf523f357), Int32(bitPattern: 0xa6327623), Int32(bitPattern: 0x93a83531), Int32(bitPattern: 0x56cccd02), Int32(bitPattern: 0xacf08162), Int32(bitPattern: 0x5a75ebb5), Int32(bitPattern: 0x6e163697), Int32(bitPattern: 0x88d273cc), Int32(bitPattern: 0xde966292), Int32(bitPattern: 0x81b949d0), Int32(bitPattern: 0x4c50901b), Int32(bitPattern: 0x71c65614), Int32(bitPattern: 0xe6c6c7bd), Int32(bitPattern: 0x327a140a), Int32(bitPattern: 0x45e1d006), Int32(bitPattern: 0xc3f27b9a), Int32(bitPattern: 0xc9aa53fd), Int32(bitPattern: 0x62a80f00), Int32(bitPattern: 0xbb25bfe2), Int32(bitPattern: 0x35bdd2f6), Int32(bitPattern: 0x71126905), Int32(bitPattern: 0xb2040222), Int32(bitPattern: 0xb6cbcf7c), Int32(bitPattern: 0xcd769c2b), Int32(bitPattern: 0x53113ec0), Int32(bitPattern: 0x1640e3d3), Int32(bitPattern: 0x38abbd60), Int32(bitPattern: 0x2547adf0), Int32(bitPattern: 0xba38209c), Int32(bitPattern: 0xf746ce76), Int32(bitPattern: 0x77afa1c5), Int32(bitPattern: 0x20756060), Int32(bitPattern: 0x85cbfe4e), Int32(bitPattern: 0x8ae88dd8), Int32(bitPattern: 0x7aaaf9b0), Int32(bitPattern: 0x4cf9aa7e), Int32(bitPattern: 0x1948c25c), Int32(bitPattern: 0x02fb8a8c), Int32(bitPattern: 0x01c36ae4), Int32(bitPattern: 0xd6ebe1f9), Int32(bitPattern: 0x90d4f869), Int32(bitPattern: 0xa65cdea0), Int32(bitPattern: 0x3f09252d), Int32(bitPattern: 0xc208e69f), Int32(bitPattern: 0xb74e6132), Int32(bitPattern: 0xce77e25b), Int32(bitPattern: 0x578fdfe3), Int32(bitPattern: 0x3ac372e6) ] // bcrypt IV: "OrpheanBeholderScryDoubt" let bf_crypt_ciphertext : [Int32] = [ 0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253, 0x63727944, 0x6f756274 ] // Table for Base64 encoding let base64_code : [Character] = [ ".", "/", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" ] // Table for Base64 decoding let index_64 : [Int8] = [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1, -1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, -1, 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, -1, -1, -1, -1, -1 ] // MARK: - class JKBCrypt: NSObject { // MARK: Property List private var p : UnsafeMutablePointer<Int32> // [Int32] private var s : UnsafeMutablePointer<Int32> // [Int32] // MARK: - Override Methods override init() { self.p = nil self.s = nil } // MARK: - Public Class Methods /** Generates a salt with the provided number of rounds. :param: numberOfRounds The number of rounds to apply. The work factor increases exponentially as the `numberOfRounds` increases. :returns: String The generated salt */ class func generateSaltWithNumberOfRounds(rounds: UInt) -> String { var randomData : NSData = JKBCryptRandom.generateRandomSignedDataOfLength(BCRYPT_SALT_LEN) var salt : String salt = "$2a$" + ((rounds < 10) ? "0" : "") + "\(rounds)" + "$" salt += JKBCrypt.encodeData(randomData, ofLength: UInt(randomData.length)) return salt } /** Generates a salt with a defaulted set of 10 rounds. :returns: String The generated salt. */ class func generateSalt() -> String { return JKBCrypt.generateSaltWithNumberOfRounds(10) } /** Hashes the provided password with the provided salt. :param: password The password to hash. :param: salt The salt to use in the hash. The `salt` must be 16 characters in length. Also, the `salt` must be properly formatted with accepted version, revision, and salt rounds. If any of this is not true, nil is returned. :returns: String? The hashed password. */ class func hashPassword(password: String, withSalt salt: String) -> String? { var bCrypt : JKBCrypt var realSalt : String var hashedData : NSData var minor : Character = "\000"[0] var off : Int = 0 // If the salt length is too short, it is invalid if count(salt) < BCRYPT_SALT_LEN { return nil } // If the salt does not start with "$2", it is an invalid version if salt[0] != "$" || salt[1] != "2" { return nil } if salt[2] == "$" { off = 3 } else { off = 4 minor = salt[2] if minor != "a" || salt[3] != "$" { // Invalid salt revision. return nil } } // Extract number of rounds if salt[(Int)(off+2)] > "$" { // Missing salt rounds return nil } var range : Range = Range(start: off, end: off+2) let extactedRounds = salt[range].toInt() if extactedRounds == nil { // Invalid number of rounds return nil } var rounds : Int = extactedRounds! range = Range(start: off + 3, end: off + 25) realSalt = salt[range] var passwordPreEncoding : String = password if minor >= "a" { passwordPreEncoding += "\0" } var passwordData : NSData? = (passwordPreEncoding as NSString).dataUsingEncoding(NSUTF8StringEncoding) var saltData : NSData? = JKBCrypt.decode_base64(realSalt, ofMaxLength: BCRYPT_SALT_LEN) if passwordData != nil && saltData != nil { bCrypt = JKBCrypt() if let hashedData = bCrypt.hashPassword(passwordData!, withSalt: saltData!, numberOfRounds: rounds) { var hashedPassword : String = "$2" + ((minor >= "a") ? String(minor) : "") + "$" hashedPassword += ((rounds < 10) ? "0" : "") + "\(rounds)" + "$" var saltString = JKBCrypt.encodeData(saltData!, ofLength: UInt(saltData!.length)) var hashedString = JKBCrypt.encodeData(hashedData, ofLength: 23) return hashedPassword + saltString + hashedString } } return nil } /** Hashes the provided password with the provided hash and compares if the two hashes are equal. :param: password The password to hash. :param: hash The hash to use in generating and comparing the password. The `hash` must be properly formatted with accepted version, revision, and salt rounds. If any of this is not true, nil is returned. :returns: Bool? TRUE if the password hash matches the given hash; FALSE if the two do not match; nil if hash is improperly formatted. */ class func verifyPassword(password: String, matchesHash hash: String) -> Bool? { if let hashedPassword = JKBCrypt.hashPassword(password, withSalt: hash) { return hashedPassword == hash } else { return nil } } // MARK: - Private Class Methods /** Encodes an NSData composed of signed chararacters and returns slightly modified Base64 encoded string. :param: data The data to be encoded. Passing nil will result in nil being returned. :param: length The length. Must be greater than 0 and no longer than the length of data. :returns: String A Base64 encoded string. */ class private func encodeData(data: NSData, ofLength length: UInt) -> String { if data.length == 0 || length == 0 { // Invalid data so return nil. return String() } var len : Int = Int(length) if len > data.length { len = data.length } var offset : Int = 0 var c1 : UInt8 var c2 : UInt8 var result : String = String() var dataArray : [UInt8] = [UInt8](count: len, repeatedValue: 0) data.getBytes(&dataArray, length:len) while offset < len { c1 = dataArray[offset++] & 0xff result.append(base64_code[Int((c1 >> 2) & 0x3f)]) c1 = (c1 & 0x03) << 4 if offset >= len { result.append(base64_code[Int(c1 & 0x3f)]) break } c2 = dataArray[offset++] & 0xff c1 |= (c2 >> 4) & 0x0f result.append(base64_code[Int(c1 & 0x3f)]) c1 = (c2 & 0x0f) << 2 if offset >= len { result.append(base64_code[Int(c1 & 0x3f)]) break } c2 = dataArray[offset++] & 0xff c1 |= (c2 >> 6) & 0x03 result.append(base64_code[Int(c1 & 0x3f)]) result.append(base64_code[Int(c2 & 0x3f)]) } return result } /** Returns the Base64 encoded signed character of the provided unicode character. :param: x The 16-bit unicode character whose Base64 counterpart, if any, will be returned. :returns: Int8 The Base64 encoded signed character or -1 if none exists. */ class private func char64of(x: Character) -> Int8 { var xAsInt : Int32 = Int32(x.utf16Value()) if xAsInt < 0 || xAsInt > 128 - 1 { // The character would go out of bounds of the pre-calculated array so return -1. return -1 } // Return the matching Base64 encoded character. return index_64[Int(xAsInt)] } /** Decodes the provided Base64 encoded string to an NSData composed of signed characters. :param: s The Base64 encoded string. If this is nil, nil will be returned. :param: maxolen The maximum number of characters to decode. If this is not greater than 0 nil will be returned. :returns: NSData? An NSData or nil if the arguments are invalid. */ class private func decode_base64(s: String, ofMaxLength maxolen: Int) -> NSData? { var off : Int = 0 var slen : Int = count(s) var olen : Int = 0 var result : [Int8] = [Int8](count: maxolen, repeatedValue: 0) var c1 : Int8 var c2 : Int8 var c3 : Int8 var c4 : Int8 var o : Int8 if maxolen <= 0 { // Invalid number of characters. return nil } var v1 : UInt8 var v2 : UnicodeScalar while off < slen - 1 && olen < maxolen { c1 = JKBCrypt.char64of(s[off++]) c2 = JKBCrypt.char64of(s[off++]) if c1 == -1 || c2 == -1 { break } o = c1 << 2 o |= (c2 & 0x30) >> 4 result[olen] = o if ++olen >= maxolen || off >= slen { break } c3 = JKBCrypt.char64of(s[Int(off++)]) if c3 == -1 { break } o = (c2 & 0x0f) << 4 o |= (c3 & 0x3c) >> 2 result[olen] = o if ++olen >= maxolen || off >= slen { break } c4 = JKBCrypt.char64of(s[off++]) o = (c3 & 0x03) << 6 o |= c4 result[olen] = o ++olen } return NSData(bytes: result, length: olen) } /** Cyclically extracts a word of key material from the provided NSData. :param: d The NSData from which the word will be extracted. :param: offp The "pointer" (as a one-entry array) to the current offset into data. :returns: UInt32 The next word of material from the data. */ // class private func streamToWord(data: NSData, inout off offp: Int32) -> Int32 { class private func streamToWordWithData(data: UnsafeMutablePointer<Int8>, ofLength length: Int, inout off offp: Int32) -> Int32 { // var dataLength : Int = data.length // var dataArray : [Int8] = [Int8](count:d.length, repeatedValue: 0) // data.getBytes(&dataArray, length:dataLength) var i : Int var word : Int32 = 0 var off : Int32 = offp for i = 0; i < 4; i++ { word = (word << 8) | (Int32(data[Int(off)]) & 0xff) off = (off + 1) % Int32(length) } offp = off return word } // MARK: - Private Instance Methods /** Hashes the provided password with the salt for the number of rounds. :param: password The password to hash. :param: salt The salt to use in the hash. :param: numberOfRounds The number of rounds to apply. The salt must be 16 characters in length. The `numberOfRounds` must be between 4 and 31 inclusively. If any of this is not true, nil is returned. :returns: NSData? The hashed password. */ private func hashPassword(password: NSData, withSalt salt: NSData, numberOfRounds: Int) -> NSData? { var rounds : Int var i : Int var j : Int var clen : Int = 6 var cdata : [Int32] = bf_crypt_ciphertext if numberOfRounds < 4 || numberOfRounds > 31 { // Invalid number of rounds return nil } rounds = 1 << numberOfRounds if salt.length != BCRYPT_SALT_LEN { // Invalid salt length return nil } self.initKey() self.enhanceKeyScheduleWithData(salt, key: password) for i = 0; i < rounds; i++ { self.key(password) self.key(salt) } for i = 0; i < 64; i++ { for j = 0; j < (clen >> 1); j++ { self.encipher(&cdata, off: j << 1) } } var result : [Int8] = [Int8](count:clen * 4, repeatedValue: 0) j = 0 for i in 0..<clen { result[j++] = Int8(truncatingBitPattern: (cdata[i] >> 24) & 0xff) result[j++] = Int8(truncatingBitPattern: (cdata[i] >> 16) & 0xff) result[j++] = Int8(truncatingBitPattern: (cdata[i] >> 8) & 0xff) result[j++] = Int8(truncatingBitPattern: cdata[i] & 0xff) } deinitKey() return NSData(bytes: result, length: count(result)) } /** Enciphers the provided array using the Blowfish algorithm. :param: lr The left-right array containing two 32-bit half blocks. :param: off The offset into the array. :returns: <void> */ // private func encipher(inout lr: [Int32], off: Int) { private func encipher(/*inout*/ lr: UnsafeMutablePointer<Int32>, off: Int) { if off < 0 { // Invalid offset. return } var n : Int32 var l : Int32 = lr[off] var r : Int32 = lr[off + 1] l ^= p[0] var i : Int = 0 while i <= BLOWFISH_NUM_ROUNDS - 2 { // Feistel substitution on left word n = s.advancedBy(Int((l >> 24) & 0xff)).memory n = n &+ s.advancedBy(Int(0x100 | ((l >> 16) & 0xff))).memory n ^= s.advancedBy(Int(0x200 | ((l >> 8) & 0xff))).memory n = n &+ s.advancedBy(Int(0x300 | (l & 0xff))).memory r ^= n ^ p.advancedBy(++i).memory // Feistel substitution on right word n = s.advancedBy(Int((r >> 24) & 0xff)).memory n = n &+ s.advancedBy(Int(0x100 | ((r >> 16) & 0xff))).memory n ^= s.advancedBy(Int(0x200 | ((r >> 8) & 0xff))).memory n = n &+ s.advancedBy(Int(0x300 | (r & 0xff))).memory l ^= n ^ p.advancedBy(++i).memory } lr[off] = r ^ p.advancedBy(BLOWFISH_NUM_ROUNDS + 1).memory lr[off + 1] = l } /** Initializes the blowfish key schedule. :returns: <void> */ private func initKey() { // p = P_orig p = UnsafeMutablePointer<Int32>.alloc(count(P_orig)) p.initializeFrom(UnsafeMutablePointer<Int32>(P_orig), count: count(P_orig)) // s = S_orig s = UnsafeMutablePointer<Int32>.alloc(count(S_orig)) s.initializeFrom(UnsafeMutablePointer<Int32>(S_orig), count: count(S_orig)) } private func deinitKey() { p.destroy() p.dealloc(count(P_orig)) s.destroy() s.dealloc(count(S_orig)) } /** Keys the receiver's blowfish cipher using the provided key. :param: key The array containing the key. :returns: <void> */ // private func key(key: NSData) { private func key(key: NSData) { var i : Int var koffp : Int32 = 0 var lr : [Int32] = [0, 0] // var lr : UnsafeMutablePointer<Int32> = UnsafeMutablePointer<Int32>.alloc(2) // lr[0] = 0; lr[1] = 0 var plen : Int = 18 var slen : Int = 1024 var keyPointer : UnsafeMutablePointer<Int8> = UnsafeMutablePointer<Int8>(key.bytes) var keyLength : Int = key.length for i = 0; i < plen; i++ { p[i] = p[i] ^ JKBCrypt.streamToWordWithData(keyPointer, ofLength: keyLength, off: &koffp) } for i = 0; i < plen; i += 2 { self.encipher(&lr, off: 0) p[i] = lr[0] p[i + 1] = lr[1] } for i = 0; i < slen; i += 2 { self.encipher(&lr, off: 0) s[i] = lr[0] s[i + 1] = lr[1] } } /** Performs the "enhanced key schedule" step described by Provos and Mazieres in "A Future-Adaptable Password Scheme" http://www.openbsd.org/papers/bcrypt-paper.ps :param: data The salt data. :param: key The password data. :returns: <void> */ private func enhanceKeyScheduleWithData(data: NSData, key: NSData) { var i : Int var koffp : Int32 = 0 var doffp : Int32 = 0 var lr : [Int32] = [0, 0] // var lr : UnsafeMutablePointer<Int32> = UnsafeMutablePointer.alloc(2) // lr[0] = 0; lr[1] = 0 var plen : Int = 18 var slen : Int = 1024 var keyPointer : UnsafeMutablePointer<Int8> = UnsafeMutablePointer<Int8>(key.bytes) var keyLength : Int = key.length var dataPointer : UnsafeMutablePointer<Int8> = UnsafeMutablePointer<Int8>(data.bytes) var dataLength : Int = data.length for i = 0; i < plen; i++ { p[i] = p[i] ^ JKBCrypt.streamToWordWithData(keyPointer, ofLength: keyLength, off:&koffp) } for i = 0; i < plen; i += 2 { lr[0] ^= JKBCrypt.streamToWordWithData(dataPointer, ofLength: dataLength, off: &doffp) lr[1] ^= JKBCrypt.streamToWordWithData(dataPointer, ofLength: dataLength, off: &doffp) self.encipher(&lr, off: 0) p[i] = lr[0] p[i + 1] = lr[1] } for i = 0; i < slen; i += 2 { lr[0] ^= JKBCrypt.streamToWordWithData(dataPointer, ofLength: dataLength, off: &doffp) lr[1] ^= JKBCrypt.streamToWordWithData(dataPointer, ofLength: dataLength, off: &doffp) self.encipher(&lr, off: 0) s[i] = lr[0] s[i + 1] = lr[1] } } }
apache-2.0
566ed30d507b07dfac5aa469715409ba
59.139381
133
0.689475
2.900758
false
false
false
false
blackspotbear/MMDViewer
MMDViewer/PMXObject.swift
1
15503
import Foundation import GLKit import Metal import simd protocol AnimationCounter { init(beginFrameNum: Int, endFrameNum: Int) func increment() func currentFrame() -> Int func maxIt() -> Int } private func CopyMatrices(_ buffer: MTLBuffer, _ modelMatrix: GLKMatrix4, _ modelViewMatrix: GLKMatrix4, _ projectionMatrix: GLKMatrix4, _ normalMatrix: GLKMatrix4, _ shadowMatrix: GLKMatrix4, _ shadowMatrixGB: GLKMatrix4) { let matrixBufferSize = MemoryLayout<GLKMatrix4>.stride var dst = buffer.contents() var modelMatrix = modelMatrix var modelViewMatrix = modelViewMatrix var projectionMatrix = projectionMatrix var shadowMatrix = shadowMatrix var shadowMatrixGB = shadowMatrixGB var normalMatrix = normalMatrix memcpy(dst, &modelMatrix, matrixBufferSize) dst = dst.advanced(by: matrixBufferSize) memcpy(dst, &modelViewMatrix, matrixBufferSize) dst = dst.advanced(by: matrixBufferSize) memcpy(dst, &projectionMatrix, matrixBufferSize) dst = dst.advanced(by: matrixBufferSize) memcpy(dst, &shadowMatrix, matrixBufferSize) dst = dst.advanced(by: matrixBufferSize) memcpy(dst, &shadowMatrixGB, matrixBufferSize) dst = dst.advanced(by: matrixBufferSize) // shader's normal matrix is of type float3x3 // float3 alignment is 16byte (= sizeof(Float) * 4) memcpy(dst, &normalMatrix, MemoryLayout<float3x3>.size) } private func DefaultSampler(_ device: MTLDevice) -> MTLSamplerState { let pSamplerDescriptor: MTLSamplerDescriptor? = MTLSamplerDescriptor() if let sampler = pSamplerDescriptor { sampler.minFilter = .linear sampler.magFilter = .linear sampler.mipFilter = .linear sampler.maxAnisotropy = 1 sampler.sAddressMode = .repeat sampler.tAddressMode = .repeat sampler.rAddressMode = .repeat sampler.normalizedCoordinates = true sampler.lodMinClamp = 0 sampler.lodMaxClamp = Float.greatestFiniteMagnitude } else { fatalError("failed creating a sampler descriptor") } return device.makeSamplerState(descriptor: pSamplerDescriptor!)! } private func PrepareDepthStencilState(_ device: MTLDevice) -> MTLDepthStencilState { let pDepthStateDesc = MTLDepthStencilDescriptor() pDepthStateDesc.depthCompareFunction = .less pDepthStateDesc.isDepthWriteEnabled = true return device.makeDepthStencilState(descriptor: pDepthStateDesc)! } private class NormalCounter: AnimationCounter { let beginFrameNum: Int let endFrameNum: Int var frameNum: Int required init(beginFrameNum: Int, endFrameNum: Int) { self.beginFrameNum = beginFrameNum self.endFrameNum = endFrameNum frameNum = self.beginFrameNum } func increment() { frameNum += 1 if frameNum >= endFrameNum { frameNum = beginFrameNum } } func currentFrame() -> Int { return frameNum } func maxIt() -> Int { return -1 } } private class DebugCounter: AnimationCounter { let beginFrameNum: Int let endFrameNum: Int var frameNum: Int var slowNum = 0 var iterateNum = 0 required init(beginFrameNum: Int, endFrameNum: Int) { self.beginFrameNum = beginFrameNum self.endFrameNum = endFrameNum frameNum = self.beginFrameNum } func increment() { slowNum += 1 if slowNum >= 10 { slowNum = 0 iterateNum += 1 if iterateNum >= 5 { iterateNum = 0 frameNum += 1 if frameNum >= endFrameNum { frameNum = beginFrameNum } } } } func currentFrame() -> Int { return frameNum } func maxIt() -> Int { return iterateNum } } class Posture { let bone: Bone var q: GLKQuaternion var pos: GLKVector3 var wm: GLKMatrix4 // world matrix var worldPos: GLKVector3 { let p = GLKMatrix4MultiplyVector4(wm, GLKVector4MakeWithVector3(bone.pos, 1)) return GLKVector3Make(p.x, p.y, p.z) } var worldRot: GLKQuaternion { return GLKQuaternionMakeWithMatrix4(wm) } init(bone: Bone) { self.bone = bone q = GLKQuaternionIdentity pos = GLKVector3Make(0, 0, 0) wm = GLKMatrix4Identity } func reset() { q = GLKQuaternionIdentity pos = GLKVector3Make(0, 0, 0) wm = GLKMatrix4Identity } func updateTransformMatrix(_ postures: [Posture]) { var m = GLKMatrix4Multiply( GLKMatrix4MakeTranslation(pos.x, pos.y, pos.z), GLKMatrix4Multiply( GLKMatrix4MakeWithQuaternion(self.q), GLKMatrix4MakeTranslation(-bone.pos.x, -bone.pos.y, -bone.pos.z) ) ) if self.bone.parentBoneIndex < postures.count { m = postures[self.bone.parentBoneIndex].wm.multiply(m) } wm = m } } struct ShaderUniforms { let modelMatrix: float4x4 let modelViewMatrix: float4x4 let projectionMatrix: float4x4 let shadowMatrix: float4x4 let shadowMatrixGB: float4x4 let normalMatrix: float3x3 } struct ShaderMaterial { let ambientColor: float3 let diffuseColor: float3 let specularColor: float3 let specularPower: Float } private func PhysicsSolverMake(_ pmx: PMX) -> PhysicsSolving { let solver = PhysicsSolverMake() as! PhysicsSolving solver.build(pmx.rigidBodies, constraints: pmx.constraints, bones: pmx.bones) return solver } // Make right-handed orthographic matrix. // // right-handed: 10-th value of matrix has a negative sign. // "OC" stands for off-center. // // see http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho // and https://goo.gl/lJ1fb3 , https://goo.gl/Xlqrwf // and https://goo.gl/lD41Z7 , https://goo.gl/zqBkCU private func MakeOrthoOC(_ left: Float, _ right: Float, _ bottom: Float, _ top: Float, _ near: Float, _ far: Float) -> GLKMatrix4 { let sLength = 1.0 / (right - left) let sHeight = 1.0 / (top - bottom) let sDepth = 1.0 / (far - near) // "Metal Programming Guide" says: // Metal defines its Normalized Device Coordinate (NDC) system as a 2x2x1 cube // with its center at (0, 0, 0.5). The left and bottom for x and y, respectively, // of the NDC system are specified as -1. The right and top for x and y, respectively, // of the NDC system are specified as +1. // // see https://goo.gl/5wT5kg // Because of the reason, following formula is defferent from https://goo.gl/rFN8eS . return GLKMatrix4Make( 2.0 * sLength, 0.0, 0.0, 0.0, 0.0, 2.0 * sHeight, 0.0, 0.0, 0.0, 0.0, -sDepth, 0.0, -sLength * (left + right), -sHeight * (top + bottom), -sDepth * near, 1.0) } class PMXObject { var device: MTLDevice var pmx: PMX var vmd: VMD var curveTies: [CurveTie] var indexBuffer: MTLBuffer var uniformBuffer: MTLBuffer? var matrixPalette: MTLBuffer? var materialBuffer: MTLBuffer? var positionX: Float = 0 var positionY: Float = 0 var positionZ: Float = 0 var rotationX: Float = 0 var rotationY: Float = 0 var rotationZ: Float = 0 var scale: Float = 1 var vertexBufferProvider: BufferProvider var uniformBufferProvider: BufferProvider var mtrxBufferProvider: BufferProvider var materialBufferProvider: BufferProvider var currentVertexBuffer: MTLBuffer? var textures: [MetalTexture] = [] lazy var samplerState: MTLSamplerState = DefaultSampler(self.device) lazy var depthStencilState: MTLDepthStencilState = PrepareDepthStencilState(self.device) let counter: AnimationCounter let solver: PhysicsSolving var postures: [Posture] = [] var modelMatrix: GLKMatrix4 { return GLKMatrix4Identity.scale(scale, y: scale, z: scale).rotateAroundX(rotationX, y: rotationY, z: rotationZ).translate(positionX, y: positionY, z: positionZ) } var normalMatrix: GLKMatrix4 { return GLKMatrix4Identity.rotateAroundX(rotationX, y: rotationY, z: rotationZ) } private let vertexData: Data init(device: MTLDevice, pmx: PMX, vmd: VMD) { self.device = device self.pmx = pmx self.vmd = vmd self.curveTies = [CurveTie](repeating: CurveTie(), count: pmx.bones.count) for (i, bone) in self.pmx.bones.enumerated() { if let tie = self.vmd.curveTies[bone.name] { self.curveTies[i] = tie } } for i in 0..<self.pmx.bones.count { let posture = Posture(bone: self.pmx.bones[i]) self.postures.append(posture) } vertexData = PMXVertex2NSData(pmx.vertices)! vertexBufferProvider = BufferProvider( device: device, inflightBuffersCount: 3, data: vertexData) indexBuffer = device.makeBuffer(bytes: pmx.indices, length: pmx.indices.count * MemoryLayout<UInt16>.size, options: MTLResourceOptions())! self.uniformBufferProvider = BufferProvider( device: device, inflightBuffersCount: 3, sizeOfUniformsBuffer: MemoryLayout<ShaderUniforms>.stride) self.mtrxBufferProvider = BufferProvider( device: device, inflightBuffersCount: 3, sizeOfUniformsBuffer: MemoryLayout<float4x4>.size * 4 * pmx.bones.count) self.materialBufferProvider = BufferProvider( device: device, inflightBuffersCount: 3, sizeOfUniformsBuffer: MemoryLayout<ShaderMaterial>.stride * pmx.materials.count) for path in pmx.texturePaths { let ext = (path as NSString).pathExtension let body = (path as NSString).deletingPathExtension let texture = MetalTexture(resourceName: "data/mmd/" + body, ext: ext, mipmaped: false) texture.loadTexture(device, flip: true) textures.append(texture) } counter = NormalCounter(beginFrameNum: 0, endFrameNum: vmd.meta.frameCount) //counter = DebugCounter(beginFrameNum: 160, endFrameNum: vmd.frameCount) solver = PhysicsSolverMake(pmx) } func calc(_ renderer: Renderer) { // FKSolver(postures, vmd: vmd, frameNum: counter.currentFrame()) FKSolver(postures, curveTies: self.curveTies, frameNum: counter.currentFrame()) IKSolver(postures, maxIt: counter.maxIt()) GrantSolver(postures) for posture in postures { posture.updateTransformMatrix(postures) } PhysicsSolver(postures, physicsSolving: solver) currentVertexBuffer = vertexBufferProvider.nextBuffer() memcpy(currentVertexBuffer!.contents(), (vertexData as NSData).bytes, vertexData.count) applyMorph() uniformBuffer = sendUniforms(renderer) matrixPalette = sendMatrixPalette() materialBuffer = sendMaterials() } private func updateVertex(_ morph: Morph, _ weight: Float) { let p = currentVertexBuffer!.contents() let size = PMXVertex.packedSize for e in morph.elements { let ev = e as! MorphVertex var fp = p.advanced(by: size * ev.index).assumingMemoryBound(to: Float.self) fp.pointee += ev.trans.x * weight; fp = fp.advanced(by: 1) fp.pointee += ev.trans.y * weight; fp = fp.advanced(by: 1) fp.pointee += ev.trans.z * weight; fp = fp.advanced(by: 1) } } private func applyMorph() { let morphs = vmd.getMorph(counter.currentFrame()) if morphs.left == nil && morphs.right == nil { return } let from = Float(morphs.left != nil ? morphs.left![0].frameNum : counter.currentFrame()) let to = Float(morphs.right != nil ? morphs.right![0].frameNum : counter.currentFrame()) let t = from == to ? 1 : (Float(counter.currentFrame()) - from) / (to - from) if let ms = morphs.left { for vm in ms { if let pm = pmx.morphs[vm.name] { switch pm.type { case .vertex: updateVertex(pm, vm.weight * (1 - t)) case .group: break case .bone: break default: break } } } } if let ms = morphs.right { for vm in ms { if let pm = pmx.morphs[vm.name] { switch pm.type { case .vertex: updateVertex(pm, vm.weight * t) case .group: break case .bone: break default: break } } } } } func updateCounter() { counter.increment() } private func sendUniforms(_ renderer: Renderer) -> MTLBuffer { let uniformBuffer = uniformBufferProvider.nextBuffer() // "Metal Shading Language Guide" says: // In Metal, the origin of the pixel coordinate system of a texture is // defined at the top-left corner. // // So shadowMatrixGB's Y scale value is negative. // // see https://goo.gl/vgIYTf let modelViewMatrix = renderer.viewMatrix.multiply(modelMatrix) let sunMatrix = GLKMatrix4MakeLookAt(-10, 12, 0, 0, 12, 0, 0, 1, 0) // right-handed let orthoMatrix = MakeOrthoOC(-12, 12, -12, 12, 1, 20) let shadowMatrix = orthoMatrix.multiply(sunMatrix) let shadowMatrixGB = GLKMatrix4MakeTranslation(0.5, 0.5, 0.0).multiply(GLKMatrix4MakeScale(0.5, -0.5, 1.0)).multiply(shadowMatrix) CopyMatrices( uniformBuffer, modelMatrix, modelViewMatrix, renderer.projectionMatrix, normalMatrix, shadowMatrix, shadowMatrixGB) return uniformBuffer } private func sendMatrixPalette() -> MTLBuffer { let palette = self.mtrxBufferProvider.nextBuffer() var dst = palette.contents() for posture in postures { memcpy(dst, &posture.wm, MemoryLayout<GLKMatrix4>.size) dst = dst.advanced(by: MemoryLayout<GLKMatrix4>.stride) } return palette } private func sendMaterials() -> MTLBuffer { let materialBuffer = materialBufferProvider.nextBuffer() var materialPointer = materialBuffer.contents() for mat in pmx.materials { var material = ShaderMaterial( ambientColor: float3(mat.ambient.r, mat.ambient.g, mat.ambient.b), diffuseColor: float3(mat.diffuse.r, mat.diffuse.g, mat.diffuse.b), specularColor: float3(mat.specular.r, mat.specular.g, mat.specular.b), specularPower: mat.specularPower) memcpy(materialPointer, &material, MemoryLayout<ShaderMaterial>.size) materialPointer += MemoryLayout<ShaderMaterial>.stride } return materialBuffer } }
mit
148d86cf47e09e003f492264927c8948
31.706751
168
0.610591
4.435765
false
false
false
false
Desgard/Calendouer-iOS
Calendouer/Calendouer/App/Controller/debugin/DebugInViewViewController.swift
1
3155
// // DebugInViewViewController.swift // Calendouer // // Created by 段昊宇 on 2017/3/19. // Copyright © 2017年 Desgard_Duan. All rights reserved. // import UIKit class DebugInViewViewController: UIViewController { let cellData: [DebugIn] = [ DebugIn(id: "CalViewController"), DebugIn(id: "AnimationTestViewController"), DebugIn(id: "WeatherDetailViewController"), DebugIn(id: "AboutAppViewController"), ] var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() initialView() addSubView() configTableViewData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(false, animated: true) self.tabBarController?.tabBar.isHidden = true self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Ubuntu-Light", size: 17) ?? UIFont.systemFont(ofSize: 17), NSForegroundColorAttributeName: UIColor.white, ] } private func initialView() { self.title = "Debug In" tableView = UITableView(frame: view.bounds, style: .grouped) tableView.delegate = self tableView.dataSource = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "DefaultCell") } private func addSubView() { view.addSubview(tableView) } private func configTableViewData() { } } extension DebugInViewViewController: UITableViewDelegate { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellData.count } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let testVC = cellData[indexPath.row].getViewController() self.navigationController?.pushViewController(testVC, animated: true) } } extension DebugInViewViewController: UITableViewDataSource { public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "DefaultCell", for: indexPath) as UITableViewCell cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator cell.selectionStyle = UITableViewCellSelectionStyle.none cell.textLabel?.text = cellData[indexPath.row].identifier return cell } } class DebugIn: NSObject { public var identifier: String = "" public var objClassName: String = "" init(id: String) { self.identifier = id self.objClassName = id } public func getViewController() -> UIViewController { let nameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String let controllerClass: AnyClass = NSClassFromString("\(nameSpace).\(self.objClassName)")! let realClass = controllerClass as! UIViewController.Type let retController = realClass.init() return retController as UIViewController } }
mit
dcb7c49dea2f2253fb152c7e254cf198
32.468085
114
0.681182
5.287395
false
false
false
false
LbfAiYxx/douyuTV
DouYu/DouYu/Classes/Home/controller/FunnyViewController.swift
1
793
// // FunnyViewController.swift // DouYu // // Created by 刘冰峰 on 2017/1/16. // Copyright © 2017年 LBF. All rights reserved. // import UIKit class FunnyViewController: BaseViewController { fileprivate lazy var funnyVM = FunnyVM() } extension FunnyViewController{ override func requestData() { baseVM = funnyVM funnyVM.loadData { self.collectionview.reloadData() self.finishLoadData() } } } extension FunnyViewController{ override func setUpView() { super.setUpView() let layout = collectionview.collectionViewLayout as! UICollectionViewFlowLayout layout.headerReferenceSize = CGSize.zero collectionview.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 0) } }
mit
6a89c744ac0684f8583f040cbe9371c1
21.4
87
0.667092
4.694611
false
false
false
false
cuappdev/tcat-ios
TCAT/AppDelegate.swift
1
10612
// // AppDelegate.swift // TCAT // // Created by Kevin Greer on 9/7/16. // Copyright © 2016 cuappdev. All rights reserved. // import AppDevAnnouncements import Crashlytics import Fabric import Firebase import FutureNova import GoogleMaps import Intents import SafariServices import SwiftyJSON import UIKit import WhatsNewKit /// This is used for app-specific preferences let userDefaults = UserDefaults.standard @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private let encoder = JSONEncoder() private let userDataInits: [(key: String, defaultValue: Any)] = [ (key: Constants.UserDefaults.onboardingShown, defaultValue: false), (key: Constants.UserDefaults.recentSearch, defaultValue: [Any]()), (key: Constants.UserDefaults.favorites, defaultValue: [Any]()) ] private let networking: Networking = URLSession.shared.request func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Set up networking Endpoint.setupEndpointConfig() // Set Up Google Services FirebaseApp.configure() #if DEBUG GMSServices.provideAPIKey(Keys.googleMapsDebug.value) #else GMSServices.provideAPIKey(Keys.googleMapsRelease.value) #endif // Update shortcut items AppShortcuts.shared.updateShortcutItems() // Set Up Analytics #if !DEBUG Crashlytics.start(withAPIKey: Keys.fabricAPIKey.value) #endif // Log basic information let payload = AppLaunchedPayload() Analytics.shared.log(payload) setupUniqueIdentifier() for (key, defaultValue) in userDataInits { if userDefaults.value(forKey: key) == nil { if key == Constants.UserDefaults.favorites && sharedUserDefaults?.value(forKey: key) == nil { sharedUserDefaults?.set(defaultValue, forKey: key) } else { userDefaults.set(defaultValue, forKey: key) } } else if key == Constants.UserDefaults.favorites && sharedUserDefaults?.value(forKey: key) == nil { sharedUserDefaults?.set(userDefaults.value(forKey: key), forKey: key) } } // Track number of app opens for Store Review prompt StoreReviewHelper.incrementAppOpenedCount() // Debug - Always Show Onboarding // userDefaults.set(false, forKey: Constants.UserDefaults.onboardingShown) getBusStops() // Initalize first view based on context let showOnboarding = !userDefaults.bool(forKey: Constants.UserDefaults.onboardingShown) let parentHomeViewController = ParentHomeMapViewController( contentViewController: HomeMapViewController(), drawerViewController: FavoritesViewController(isEditing: false) ) let rootVC = showOnboarding ? OnboardingViewController(initialViewing: true) : parentHomeViewController let navigationController = showOnboarding ? OnboardingNavigationController(rootViewController: rootVC) : CustomNavigationController(rootViewController: rootVC) // Setup networking for AppDevAnnouncements AnnouncementNetworking.setupConfig( scheme: Keys.announcementsScheme.value, host: Keys.announcementsHost.value, commonPath: Keys.announcementsCommonPath.value, announcementPath: Keys.announcementsPath.value ) // Initalize window without storyboard self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = navigationController self.window?.makeKeyAndVisible() return true } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { handleShortcut(item: shortcutItem) } // MARK: - Helper Functions /// Creates and sets a unique identifier. If the device identifier changes, updates it. func setupUniqueIdentifier() { if let uid = UIDevice.current.identifierForVendor?.uuidString, uid != sharedUserDefaults?.string(forKey: Constants.UserDefaults.uid) { sharedUserDefaults?.set(uid, forKey: Constants.UserDefaults.uid) } } func handleShortcut(item: UIApplicationShortcutItem) { if let shortcutData = item.userInfo as? [String: Data] { guard let place = shortcutData["place"], let destination = try? decoder.decode(Place.self, from: place) else { print("[AppDelegate] Unable to access shortcutData['place']") return } let optionsVC = RouteOptionsViewController(searchTo: destination) if let navController = window?.rootViewController as? CustomNavigationController { navController.pushViewController(optionsVC, animated: false) } let payload = HomeScreenQuickActionUsedPayload(name: destination.name) Analytics.shared.log(payload) } } private func getAllStops() -> Future<Response<[Place]>> { return networking(Endpoint.getAllStops()).decode() } /// Get all bus stops and store in userDefaults func getBusStops() { getAllStops().observe { [weak self] result in guard let self = self else { return } DispatchQueue.main.async { switch result { case .value(let response): if response.data.isEmpty { self.handleGetAllStopsError() } else { let encodedObject = try? JSONEncoder().encode(response.data) userDefaults.set(encodedObject, forKey: Constants.UserDefaults.allBusStops) } case .error(let error): print("getBusStops error:", error.localizedDescription) self.handleGetAllStopsError() } } } } func showWhatsNew(items: [WhatsNew.Item]) { let whatsNew = WhatsNew( title: "WhatsNewKit", // The features you want to showcase items: items ) // Initialize WhatsNewViewController with WhatsNew let whatsNewViewController = WhatsNewViewController( whatsNew: whatsNew ) // Present it 🤩 UIApplication.shared.keyWindow?.presentInApp(whatsNewViewController) } /// Present an alert indicating bus stops weren't fetched. func handleGetAllStopsError() { let title = "Couldn't Fetch Bus Stops" let message = "The app will continue trying on launch. You can continue to use the app as normal." let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) UIApplication.shared.keyWindow?.presentInApp(alertController) } /// Open the app when opened via URL scheme func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { // URLs for testing // BusStop: ithaca-transit://getRoutes?lat=42.442558&long=-76.485336&stopName=Collegetown // PlaceResult: ithaca-transit://getRoutes?lat=42.44707979999999&long=-76.4885196&destinationName=Hans%20Bethe%20House let rootVC = HomeMapViewController() let navigationController = CustomNavigationController(rootViewController: rootVC) self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = navigationController self.window?.makeKeyAndVisible() let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems if url.absoluteString.contains("getRoutes") { // siri URL scheme var latitude: CLLocationDegrees? var longitude: CLLocationDegrees? var stopName: String? if let lat = items?.filter({ $0.name == "lat" }).first?.value, let long = items?.filter({ $0.name == "long" }).first?.value, let stop = items?.filter({ $0.name == "stopName" }).first?.value { latitude = Double(lat) longitude = Double(long) stopName = stop } if let latitude = latitude, let longitude = longitude, let stopName = stopName { let place = Place(name: stopName, type: .busStop, latitude: latitude, longitude: longitude) let optionsVC = RouteOptionsViewController(searchTo: place) navigationController.pushViewController(optionsVC, animated: false) return true } } return false } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { if #available(iOS 12.0, *) { if let intent = userActivity.interaction?.intent as? GetRoutesIntent, let latitude = intent.latitude, let longitude = intent.longitude, let searchTo = intent.searchTo, let stopName = searchTo.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed), let url = URL(string: "ithaca-transit://getRoutes?lat=\(latitude)&long=\(longitude)&stopName=\(stopName)") { UIApplication.shared.open(url, options: [:]) { didComplete in let intentDescription = userActivity.interaction?.intent.intentDescription ?? "No Intent Description" let payload = SiriShortcutUsedPayload( didComplete: didComplete, intentDescription: intentDescription, locationName: stopName ) Analytics.shared.log(payload) } return true } } return false } } extension UIWindow { /// Find the visible view controller in the root navigation controller and present passed in view controlelr. func presentInApp(_ viewController: UIViewController) { (rootViewController as? UINavigationController)?.visibleViewController?.present(viewController, animated: true) } }
mit
85abe9a0e26070a4007316c416ab3763
39.8
155
0.640649
5.398473
false
false
false
false
bluejava/GeoTools
GeoTools/SCNUtils.swift
1
8505
// // SCNUtils.swift // GeoTools // // Created by Glenn Crownover on 4/27/15. // Copyright (c) 2015 bluejava. All rights reserved. // // This is a collection of utilities and extensions that aid in working with SceneKit // The SCNVector3 extensions were largely copied from Kim Pedersen's SCNVector3Extensions project. Thanks Kim! import Foundation import SceneKit class SCNUtils { class func getNodeFromDAE(name: String) -> SCNNode? { var rnode = SCNNode() let nscene = SCNScene(named: name) if let nodeArray = nscene?.rootNode.childNodes { for cn in nodeArray { rnode.addChildNode(cn as! SCNNode) } return rnode } println("DAE File not found: \(name)!!") return nil } class func getStaticNodeFromDAE(name: String) -> SCNNode? { if let node = getNodeFromDAE(name) { node.physicsBody = SCNPhysicsBody(type: .Static, shape: SCNPhysicsShape(node: node, options: [ SCNPhysicsShapeTypeKey: SCNPhysicsShapeTypeConcavePolyhedron])) return node } return nil } class func getMat(textureFilename: String, ureps: CGFloat = 1.0, vreps: CGFloat = 1.0, directory: String? = nil, normalFilename: String? = nil, specularFilename: String? = nil) -> SCNMaterial { var nsb = NSBundle.mainBundle().pathForResource(textureFilename, ofType: nil, inDirectory: directory) let im = NSImage(contentsOfFile: nsb!) let mat = SCNMaterial() mat.diffuse.contents = im if(normalFilename != nil) { mat.normal.contents = NSImage(contentsOfFile: NSBundle.mainBundle().pathForResource(normalFilename, ofType: nil, inDirectory: directory)!) } if(specularFilename != nil) { mat.specular.contents = NSImage(contentsOfFile: NSBundle.mainBundle().pathForResource(specularFilename, ofType: nil, inDirectory: directory)!) } repeatMat(mat, wRepeat: ureps,hRepeat: vreps) return mat } class func repeatMat(mat: SCNMaterial, wRepeat: CGFloat, hRepeat: CGFloat) { mat.diffuse.contentsTransform = SCNMatrix4MakeScale(wRepeat, hRepeat, 1.0) mat.diffuse.wrapS = .WrapModeRepeat mat.diffuse.wrapT = .WrapModeRepeat mat.normal.wrapS = .WrapModeRepeat mat.normal.wrapT = .WrapModeRepeat mat.specular.wrapS = .WrapModeRepeat mat.specular.wrapT = .WrapModeRepeat } // Return the normal against the plane defined by the 3 vertices, specified in // counter-clockwise order. // note, this is an un-normalized normal. (ha.. wtf? yah, thats right) class func getNormal(v0: SCNVector3, v1: SCNVector3, v2: SCNVector3) -> SCNVector3 { // there are three edges defined by these 3 vertices, but we only need 2 to define the plane var edgev0v1 = v1 - v0 var edgev1v2 = v2 - v1 // Assume the verts are expressed in counter-clockwise order to determine normal return edgev0v1.cross(edgev1v2) } } // The following SCNVector3 extension comes from https://github.com/devindazzle/SCNVector3Extensions - with some changes by me extension SCNVector3 { /** * Negates the vector described by SCNVector3 and returns * the result as a new SCNVector3. */ func negate() -> SCNVector3 { return self * -1 } /** * Negates the vector described by SCNVector3 */ mutating func negated() -> SCNVector3 { self = negate() return self } /** * Returns the length (magnitude) of the vector described by the SCNVector3 */ func length() -> CGFloat { return sqrt(x*x + y*y + z*z) } /** * Normalizes the vector described by the SCNVector3 to length 1.0 and returns * the result as a new SCNVector3. */ func normalized() -> SCNVector3? { var len = length() if(len > 0) { return self / length() } else { return nil } } /** * Normalizes the vector described by the SCNVector3 to length 1.0. */ mutating func normalize() -> SCNVector3? { if let vn = normalized() { self = vn return self } return nil } mutating func normalizeOrZ() -> SCNVector3 { if let vn = normalized() { self = vn return self } return SCNVector3() } /** * Calculates the distance between two SCNVector3. Pythagoras! */ func distance(vector: SCNVector3) -> CGFloat { return (self - vector).length() } /** * Calculates the dot product between two SCNVector3. */ func dot(vector: SCNVector3) -> CGFloat { return x * vector.x + y * vector.y + z * vector.z } /** * Calculates the cross product between two SCNVector3. */ func cross(vector: SCNVector3) -> SCNVector3 { return SCNVector3Make(y * vector.z - z * vector.y, z * vector.x - x * vector.z, x * vector.y - y * vector.x) } func angle(vector: SCNVector3) -> CGFloat { // angle between 3d vectors P and Q is equal to the arc cos of their dot products over the product of // their magnitudes (lengths). // theta = arccos( (P • Q) / (|P||Q|) ) let dp = dot(vector) // dot product let magProduct = length() * vector.length() // product of lengths (magnitudes) return acos(dp / magProduct) // DONE } // Constrains (or reposition) this vector to fall within the specified min and max vectors. // Note - this assumes the max vector points to the outer-most corner (farthest from origin) while the // min vector represents the inner-most corner of the valid constraint space mutating func constrain(min: SCNVector3, max: SCNVector3) -> SCNVector3 { if(x < min.x) { self.x = min.x } if(x > max.x) { self.x = max.x } if(y < min.y) { self.y = min.y } if(y > max.y) { self.y = max.y } if(z < min.z) { self.z = min.z } if(z > max.z) { self.z = max.z } return self } } /** * Adds two SCNVector3 vectors and returns the result as a new SCNVector3. */ func + (left: SCNVector3, right: SCNVector3) -> SCNVector3 { return SCNVector3Make(left.x + right.x, left.y + right.y, left.z + right.z) } /** * Increments a SCNVector3 with the value of another. */ func += (inout left: SCNVector3, right: SCNVector3) { left = left + right } /** * Subtracts two SCNVector3 vectors and returns the result as a new SCNVector3. */ func - (left: SCNVector3, right: SCNVector3) -> SCNVector3 { return SCNVector3Make(left.x - right.x, left.y - right.y, left.z - right.z) } /** * Decrements a SCNVector3 with the value of another. */ func -= (inout left: SCNVector3, right: SCNVector3) { left = left - right } /** * Multiplies two SCNVector3 vectors and returns the result as a new SCNVector3. */ func * (left: SCNVector3, right: SCNVector3) -> SCNVector3 { return SCNVector3Make(left.x * right.x, left.y * right.y, left.z * right.z) } /** * Multiplies a SCNVector3 with another. */ func *= (inout left: SCNVector3, right: SCNVector3) { left = left * right } /** * Multiplies the x, y and z fields of a SCNVector3 with the same scalar value and * returns the result as a new SCNVector3. */ func * (vector: SCNVector3, scalar: CGFloat) -> SCNVector3 { return SCNVector3Make(vector.x * scalar, vector.y * scalar, vector.z * scalar) } /** * Multiplies the x and y fields of a SCNVector3 with the same scalar value. */ func *= (inout vector: SCNVector3, scalar: CGFloat) { vector = vector * scalar } /** * Divides two SCNVector3 vectors abd returns the result as a new SCNVector3 */ func / (left: SCNVector3, right: SCNVector3) -> SCNVector3 { return SCNVector3Make(left.x / right.x, left.y / right.y, left.z / right.z) } /** * Divides a SCNVector3 by another. */ func /= (inout left: SCNVector3, right: SCNVector3) { left = left / right } /** * Divides the x, y and z fields of a SCNVector3 by the same scalar value and * returns the result as a new SCNVector3. */ func / (vector: SCNVector3, scalar: CGFloat) -> SCNVector3 { return SCNVector3Make(vector.x / scalar, vector.y / scalar, vector.z / scalar) } /** * Divides the x, y and z of a SCNVector3 by the same scalar value. */ func /= (inout vector: SCNVector3, scalar: CGFloat) { vector = vector / scalar } /** * Calculates the SCNVector from lerping between two SCNVector3 vectors */ func SCNVector3Lerp(vectorStart: SCNVector3, vectorEnd: SCNVector3, t: CGFloat) -> SCNVector3 { return SCNVector3Make(vectorStart.x + ((vectorEnd.x - vectorStart.x) * t), vectorStart.y + ((vectorEnd.y - vectorStart.y) * t), vectorStart.z + ((vectorEnd.z - vectorStart.z) * t)) } /** * Project the vector, vectorToProject, onto the vector, projectionVector. */ func SCNVector3Project(vectorToProject: SCNVector3, projectionVector: SCNVector3) -> SCNVector3 { let scale: CGFloat = projectionVector.dot(vectorToProject) / projectionVector.dot(projectionVector) let v: SCNVector3 = projectionVector * scale return v }
mit
2b7b01b062487170ea00a2b8fbbbec10
26.607143
181
0.693954
3.304314
false
false
false
false
legendecas/Rocket.Chat.iOS
Rocket.Chat.Shared/Models/AuthSettings.swift
1
786
// // AuthSettings.swift // Rocket.Chat // // Created by Rafael K. Streit on 06/10/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import Foundation import RealmSwift import SwiftyJSON /// A server's public informations and settings public class AuthSettings: BaseModel { public dynamic var siteURL: String? public dynamic var cdnPrefixURL: String? // User public dynamic var useUserRealName = false // Rooms public dynamic var favoriteRooms = true // Authentication methods public dynamic var isUsernameEmailAuthenticationEnabled = false public dynamic var isGoogleAuthenticationEnabled = false public dynamic var isLDAPAuthenticationEnabled = false // File upload public dynamic var uploadStorageType: String? }
mit
013d348b790928fff94d84d741b2f8c2
24.322581
67
0.738854
4.845679
false
false
false
false
huangboju/Moots
UICollectionViewLayout/CollectionKit-master/Examples/ChatExample (Advance)/MessagesViewController.swift
1
7208
// // MessagesViewController.swift // CollectionKitExample // // Created by YiLun Zhao on 2016-02-12. // Copyright © 2016 lkzhao. All rights reserved. // import UIKit import CollectionKit class MessageDataProvider: ArrayDataProvider<Message> { init() { super.init(data: testMessages, identifierMapper: { (_, data) in return data.identifier }) } } class MessageLayout: SimpleLayout<Message> { override func simpleLayout(collectionSize: CGSize, dataProvider: CollectionDataProvider<Message>, sizeProvider: @escaping CollectionSizeProvider<Message>) -> [CGRect] { var frames: [CGRect] = [] var lastMessage: Message? var lastFrame: CGRect? let maxWidth: CGFloat = collectionSize.width for i in 0..<dataProvider.numberOfItems { let message = dataProvider.data(at: i) var yHeight: CGFloat = 0 var xOffset: CGFloat = 0 var cellFrame = MessageCell.frameForMessage(message, containerWidth: maxWidth) if let lastMessage = lastMessage, let lastFrame = lastFrame { if message.type == .image && lastMessage.type == .image && message.alignment == lastMessage.alignment { if message.alignment == .left && lastFrame.maxX + cellFrame.width + 2 < maxWidth { yHeight = lastFrame.minY xOffset = lastFrame.maxX + 2 } else if message.alignment == .right && lastFrame.minX - cellFrame.width - 2 > 0 { yHeight = lastFrame.minY xOffset = lastFrame.minX - 2 - cellFrame.width cellFrame.origin.x = 0 } else { yHeight = lastFrame.maxY + message.verticalPaddingBetweenMessage(lastMessage) } } else { yHeight = lastFrame.maxY + message.verticalPaddingBetweenMessage(lastMessage) } } cellFrame.origin.x += xOffset cellFrame.origin.y = yHeight lastFrame = cellFrame lastMessage = message frames.append(cellFrame) } return frames } } class MessagePresenter: WobblePresenter { var dataProvider: MessageDataProvider? weak var sourceView: UIView? var sendingMessage = false override func insert(collectionView: CollectionView, view: UIView, at index: Int, frame: CGRect) { super.insert(collectionView: collectionView, view: view, at: index, frame: frame) guard let messages = dataProvider?.data, let sourceView = sourceView, collectionView.hasReloaded, collectionView.reloading else { return } if sendingMessage && index == messages.count - 1 { // we just sent this message, lets animate it from inputToolbarView to it's position view.frame = collectionView.convert(sourceView.bounds, from: sourceView) view.alpha = 0 view.yaal.alpha.animateTo(1.0) view.yaal.bounds.animateTo(frame.bounds, stiffness: 400, damping: 40) } else if collectionView.visibleFrame.intersects(frame) { if messages[index].alignment == .left { let center = view.center view.center = CGPoint(x: center.x - view.bounds.width, y: center.y) view.yaal.center.animateTo(center, stiffness:250, damping: 20) } else if messages[index].alignment == .right { let center = view.center view.center = CGPoint(x: center.x + view.bounds.width, y: center.y) view.yaal.center.animateTo(center, stiffness:250, damping: 20) } else { view.alpha = 0 view.yaal.scale.from(0).animateTo(1) view.yaal.alpha.animateTo(1) } } } } class MessagesViewController: CollectionViewController { var loading = false let dataProvider = MessageDataProvider() let presenter = MessagePresenter() let newMessageButton = UIButton(type: .system) override var canBecomeFirstResponder: Bool { return true } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white: 0.97, alpha: 1.0) view.clipsToBounds = true newMessageButton.setImage(UIImage(named:"ic_send")!, for: .normal) newMessageButton.addTarget(self, action: #selector(send), for: .touchUpInside) newMessageButton.sizeToFit() newMessageButton.backgroundColor = .lightBlue newMessageButton.tintColor = .white view.addSubview(newMessageButton) collectionView.delegate = self collectionView.contentInset = UIEdgeInsetsMake(30, 10, 54, 10) collectionView.scrollIndicatorInsets = UIEdgeInsetsMake(30, 0, 54, 0) presenter.sourceView = newMessageButton presenter.dataProvider = dataProvider let provider = CollectionProvider( dataProvider: dataProvider, viewUpdater: { (view: MessageCell, data: Message, at: Int) in view.message = data } ) provider.layout = MessageLayout() provider.presenter = presenter self.provider = provider } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() newMessageButton.frame = CGRect(x: 0, y: view.bounds.height - 44, width: view.bounds.width, height: 44) let isAtBottom = collectionView.contentOffset.y >= collectionView.offsetFrame.maxY - 10 if !collectionView.hasReloaded { collectionView.reloadData() { return CGPoint(x: self.collectionView.contentOffset.x, y: self.collectionView.offsetFrame.maxY) } } if isAtBottom { if collectionView.hasReloaded { collectionView.setContentOffset(CGPoint(x: collectionView.contentOffset.x, y: collectionView.offsetFrame.maxY), animated: true) } else { collectionView.setContentOffset(CGPoint(x: collectionView.contentOffset.x, y: collectionView.offsetFrame.maxY), animated: true) } } } } // For sending new messages extension MessagesViewController { @objc func send() { let text = UUID().uuidString presenter.sendingMessage = true dataProvider.data.append(Message(true, content: text)) collectionView.reloadData() collectionView.scrollTo(edge: .bottom, animated:true) presenter.sendingMessage = false delay(1.0) { self.dataProvider.data.append(Message(false, content: text)) self.collectionView.reloadData() self.collectionView.scrollTo(edge: .bottom, animated:true) } } } extension MessagesViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { // PULL TO LOAD MORE // load more messages if we scrolled to the top if collectionView.hasReloaded, scrollView.contentOffset.y < 500, !loading { loading = true delay(0.5) { // Simulate network request let newMessages = testMessages.map{ $0.copy() } self.dataProvider.data = newMessages + self.dataProvider.data let oldContentHeight = self.collectionView.offsetFrame.maxY - self.collectionView.contentOffset.y self.collectionView.reloadData() { return CGPoint(x: self.collectionView.contentOffset.x, y: self.collectionView.offsetFrame.maxY - oldContentHeight) } self.loading = false } } } }
mit
d2a462a9c8745fb1a633f0284b6014de
34.328431
107
0.666158
4.670771
false
false
false
false
matheusbc/virtus
VirtusApp/VirtusApp/ViewController/JobsViewController.swift
1
1942
// // JobsViewController.swift // VirtusApp // // Copyright © 2017 Matheus B Campos. All rights reserved. // import UIKit /// The jobs list view controller. class JobsViewController: UITableViewController, Loadable { // MARK: Properties // The news view model. let jobsViewModel = JobsViewModel() override func viewDidLoad() { super.viewDidLoad() let loading = self.showLoading(self) tableView.tableFooterView = UIView() self.dismissLoading(loading) } } extension JobsViewController { override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return jobsViewModel.getListSize() } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Vagas" } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = createJobCell(cellForRowAt: indexPath) cell.textLabel?.text = jobsViewModel.description(cellForRowAt: indexPath.row) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let jobApplication = self.storyboard?.instantiateViewController(withIdentifier: "JobApplicationViewController") as! JobApplicationViewController jobApplication.jobName = jobsViewModel.description(cellForRowAt: indexPath.row) navigationController?.pushViewController(jobApplication, animated: true) } // MARK: Private methods /// Create table view cell for job. private func createJobCell(cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueReusableCell(withIdentifier: "JobCell", for: indexPath) } }
mit
a00490e08d05bda83f77aa9e1cfc4d94
33.052632
152
0.71458
5.134921
false
false
false
false
testpress/ios-app
ios-app/Extensions/Object.swift
1
1549
// // Object.swift // ios-app import Realm import RealmSwift protocol DetachableObject: AnyObject { func detached() -> Self } extension Object: DetachableObject { func detached() -> Self { let detached = type(of: self).init() for property in objectSchema.properties { guard let value = value(forKey: property.name) else { continue } if let detachable = value as? DetachableObject { detached.setValue(detachable.detached(), forKey: property.name) } else { // Then it is a primitive detached.setValue(value, forKey: property.name) } } return detached } } extension List: DetachableObject { func detached() -> List<Element> { let result = List<Element>() forEach { if let detachableObject = $0 as? DetachableObject, let element = detachableObject.detached() as? Element { result.append(element) } else { // Then it is a primitive result.append($0) } } return result } } extension Array { func detached() -> Array<Element> { var result = [Element]() forEach { if let detachableObject = $0 as? DetachableObject, let element = detachableObject.detached() as? Element { result.append(element) } else { result.append($0) } } return result } }
mit
2582051ebe4197460cbd2cc09107d661
25.706897
79
0.537766
4.886435
false
false
false
false
PJayRushton/StarvingStudentGuide
StarvingStudentGuide/DealDetailViewController.swift
1
6996
// // DealDetailViewController.swift // StarvingStudentGuide // // Created by Parker Rushton on 3/11/16. // Copyright © 2016 AppsByPJ. All rights reserved. // import UIKit class DealDetailViewController: UIViewController, SegueHandlerType { enum SegueIdentifier: String { case QuantityViewController } private let quantitySegueId = "QuantityViewController" // MARK: - Interface references @IBOutlet var viewGestureRecognizer: UITapGestureRecognizer! @IBOutlet weak var locationsStackView: UIStackView! @IBOutlet weak var locationsHeaderLabel: UILabel! @IBOutlet weak var headerLineView: UIView! @IBOutlet weak var firstLocationStackView: UIStackView! @IBOutlet var firstLocationGestureRecognizer: UITapGestureRecognizer! @IBOutlet weak var firstLocationLabel: UILabel! @IBOutlet weak var firstPhoneStackView: UIStackView! @IBOutlet weak var firstPhoneButton: UIButton! @IBOutlet weak var secondLocationStackView: UIStackView! @IBOutlet var secondLocationGestureRecognizer: UITapGestureRecognizer! @IBOutlet weak var secondLocationLabel: UILabel! @IBOutlet weak var secondPhoneStackView: UIStackView! @IBOutlet weak var secondPhoneButton: UIButton! @IBOutlet weak var categoryView: CategoryView! @IBOutlet weak var infoLabel: UILabel! @IBOutlet weak var detailLabel: UILabel! @IBOutlet weak var markUsedButton: GradientButton! // MARK: - Properties var deal: Deal! var quantityViewController: QuantityViewController? var userIsSure = false { didSet { viewGestureRecognizer?.enabled = userIsSure } } // MARK: - ViewController Lifecycle override func viewDidLoad() { super.viewDidLoad() updateUI() } // MARK: - IBActions @IBAction func phoneButtonPressed(sender: UIButton) { guard let phoneNumber = sender.titleLabel?.text else { return } CallHelper.call(phoneNumber) { success in if !success { UIAlertController.presentAlertWithOneButton(self, title: "Unable to make phone call", message: nil) } } } @IBAction func markUsedButtonPressed(sender: UIButton) { if !userIsSure { showUseVerification() } else { handleMarkUsed() } } @IBAction func viewWasTapped(sender: UITapGestureRecognizer) { userIsSure = false updateUI() } @IBAction func locationTapped(sender: UITapGestureRecognizer) { var searchString = firstLocationLabel.text! if sender == secondLocationGestureRecognizer { searchString = secondLocationLabel.text! } MapHelper.launchMap(searchString) } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { switch segueIdentifierForSegue(segue) { case .QuantityViewController: guard let quantityVC = segue.destinationViewController as? QuantityViewController else { fatalError() } self.quantityViewController = quantityVC quantityVC.update(withDeal: deal) } } } // MARK: - Private extension private extension DealDetailViewController { func showUseVerification() { markUsedButton.setTitle("Are you sure?", forState: .Normal) markUsedButton.startColor = .headerRed() markUsedButton.endColor = .headerRedDark() userIsSure = true } func handleMarkUsed() { deal.markOneUsed() userIsSure = false updateUI() } func updateUI() { guard let deal = deal else { return } title = deal.store.title updateLocations(deal) categoryView.category = deal.couponCategory infoLabel.text = deal.info detailLabel.text = deal.details updateMarkUsedButton(deal) quantityViewController?.update(withDeal: deal) userIsSure = false } func updateLocations(deal: Deal) { var noAddress = false var noPhone = false if let firstLocation = deal.store.locationsArray?.first, firstAddress = firstLocation.address { firstLocationLabel.text = firstAddress firstLocationLabel.textColor = firstLocation.searchable ? .linkBlue() : .blackColor() firstLocationGestureRecognizer.enabled = firstLocation.searchable } else { firstLocationStackView.hidden = true noAddress = true } if let firstPhone = deal.store.locationsArray?.first?.phoneNumber { firstPhoneButton.setTitle(firstPhone, forState: .Normal) } else { firstPhoneStackView.hidden = true noPhone = true } if deal.store.locations.count > 1 { if let secondLocation = deal.store.locationsArray?.last, secondAddress = secondLocation.address { locationsHeaderLabel.text = "Locations" secondLocationLabel?.text = secondAddress secondLocationLabel.textColor = secondLocation.searchable ? .linkBlue() : .blackColor() secondLocationGestureRecognizer.enabled = secondLocation.searchable } else { secondLocationStackView.hidden = true } if let secondPhone = deal.store.locationsArray?.last?.phoneNumber { secondPhoneButton.setTitle(secondPhone, forState: .Normal) } else { secondPhoneStackView.hidden = true } } else { secondLocationStackView.hidden = true secondPhoneStackView.hidden = true } locationsStackView.hidden = noAddress && noPhone } func updateMarkUsedButton(deal: Deal) { markUsedButton.startColor = .mainColor() markUsedButton.endColor = .mainColorDark() if deal.quantity < 0 { markUsedButton.setTitle("UNLIMITED", forState: .Normal) markUsedButton.setTitleColor(.blackColor(), forState: .Normal) markUsedButton.enabled = false markUsedButton.startColor = .clearColor() markUsedButton.endColor = .clearColor() markUsedButton.backgroundColor = .clearColor() } else if deal.available == 0 { markUsedButton.enabled = false markUsedButton.startColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.6) markUsedButton.endColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.6) markUsedButton.setTitleColor(UIColor.blackColor().colorWithAlphaComponent(0.5), forState: .Normal) markUsedButton.setTitle("All used!", forState: .Normal) } else { markUsedButton.setTitle("Mark 1 used", forState: .Normal) } } }
mit
72ffe98efd810588b238ffa2a00d03a4
32.629808
115
0.641887
5.596
false
false
false
false
zq54zquan/SwiftDoubanFM
iDoubanFm/iDoubanFm/tools/DMConstant.swift
1
510
// // DMConstant.swift // iDoubanFm // // Created by zhou quan on 7/1/14. // Copyright (c) 2014 zquan. All rights reserved. // /* DOUBANDOMAIN = "http://www.douban.com/" LOGINPATH = "j/app/login" CHANNELPATH = "j/app/radio/channels" SONGSPATH = "j/app/radio/people" */ let DOUBANDOMAIN = "http://www.douban.com/" let LOGINPATH = "j/app/login" let CHANNELPATH = "j/app/radio/channels" let SONGSPATH = "j/app/radio/people" let FMDOMAIN = "http://douban.fm/" let RECENTCHANNELPATH = "j/explore/recent_chls"
mit
a29ff4752f018801ff4058bbcc82dfa0
22.227273
50
0.690196
2.524752
false
false
false
false
jilouc/kuromoji-swift
kuromoji-swift/io/DataOutputStream.swift
1
2158
// // DataOutputStream.swift // kuromoji-swift // // Created by Jean-Luc Dagon on 19/11/2016. // Copyright © 2016 Cocoapps. All rights reserved. // import Foundation extension OutputStream { func writeInt32(_ int: UInt32) { write([UInt8((int & 0xFF000000) >> 24), UInt8((int & 0xFF0000) >> 16), UInt8((int & 0xFF00) >> 8), UInt8(int & 0xFF)], maxLength: 4) } func writeInt16(_ int: Int16) { write([UInt8((int & Int16(bitPattern: 0xFF00)) >> 8), UInt8(int & 0xFF)], maxLength: 2) } func writeInt(_ int: Int) { writeInt32(UInt32(bitPattern: Int32(int))) } func writeString(_ string: String) { let bytes = [UInt8](string.utf8) writeInt16(Int16(bytes.count)) write(bytes, maxLength: bytes.count) } } extension InputStream { func readInt32() -> Int32 { var bytes: [UInt8] = [UInt8](repeating: 0, count: 4) self.read(&bytes, maxLength: 4) return Int32(bitPattern: ((UInt32(bytes[0]) << 24) & 0xFF000000) | ((UInt32(bytes[1]) << 16) & 0xFF0000) | ((UInt32(bytes[2]) << 8) & 0xFF00) | ((UInt32(bytes[3])) & 0xFF)) } func readInt16() -> Int16 { var bytes: [UInt8] = [UInt8](repeating: 0, count: 2) self.read(&bytes, maxLength: 2) return Int16(bitPattern: ((UInt16(bytes[0]) << 8) & 0xFF00) | (UInt16(bytes[1]) & 0xFF)) } func readString() -> String { let length = Int(readInt16()) var bytes = [UInt8](repeating: 0, count: length) read(&bytes, maxLength: length) return String(bytes: bytes, encoding: .utf8)! } func readInt() -> Int { return Int(readInt32()) } func readBytes() -> [UInt8] { var data = Data() let chunkSize = 4096 while hasBytesAvailable { var bytes = [UInt8](repeating: 0, count: chunkSize) let readBytes = read(&bytes, maxLength: chunkSize) data.append(bytes, count: readBytes) } return data.withUnsafeBytes { return [UInt8](UnsafeBufferPointer(start: $0, count: data.count)) } } }
apache-2.0
11abce984cd06481ef71ad9ffab97882
29.380282
180
0.564673
3.536066
false
false
false
false
ZWCoder/KMLive
KMLive/KMLive/KMFoundation/UIKit/UIView+Additions.swift
1
2614
// // UIView+Additions.swift // KMDriver // // Created by 联合创想 on 16/12/8. // Copyright © 2016年 KMXC. All rights reserved. // import Foundation import UIKit extension UIView { /// Left public var km_Left:CGFloat{ get{ return self.frame.origin.x } set{ var frame = self.frame frame.origin.x = newValue self.frame = frame } } /// Top public var km_Top:CGFloat{ get{ return self.frame.origin.y } set{ var frame = self.frame frame.origin.y = newValue self.frame = frame } } /// Right public var km_Right:CGFloat{ get{ return self.km_Left + self.km_Width } set{ var frame = self.frame frame.origin.y = newValue self.frame = frame } } ///Bottom public var km_Bottom: CGFloat{ get{ return self.km_Top + self.km_Height } set{ var frame = self.frame frame.origin.y = newValue - frame.size.height self.frame = frame } } /// Width public var km_Width: CGFloat{ get{ return self.frame.size.width } set{ var frame = self.frame frame.size.width = newValue self.frame = frame } } /// Height public var km_Height: CGFloat{ get{ return self.frame.size.height } set{ var frame = self.frame frame.size.height = newValue self.frame = frame } } ///CenterX public var km_CenterX : CGFloat{ get{ return self.center.x } set{ self.center = CGPoint(x: newValue, y: self.center.y) } } /// CenterY public var km_CenterY : CGFloat{ get{ return self.center.y } set{ self.center = CGPoint(x: self.center.x, y: newValue) } } /// Origin public var km_Origin: CGPoint{ get{ return self.frame.origin } set{ self.km_Left = newValue.x self.km_Top = newValue.y } } /// Size public var km_Size: CGSize{ get{ return self.frame.size } set{ self.km_Width = newValue.width self.km_Height = newValue.height } } }
mit
b2d5e3ff785a51f72bcc0bbfec764185
18.425373
64
0.453323
4.29538
false
false
false
false
J3D1-WARR10R/WikiRaces
WikiRaces/Shared/Menu View Controllers/MenuViewController/MenuView/MenuView+Setup.swift
2
11066
// // MenuView+Setup.swift // WikiRaces // // Created by Andrew Finke on 2/23/19. // Copyright © 2019 Andrew Finke. All rights reserved. // import UIKit import WKRUIKit extension MenuView { // MARK: - Top View - /// Sets up the top view of the menu func setupTopView() { setupLabels() setupButtons() medalView.translatesAutoresizingMaskIntoConstraints = false topView.addSubview(medalView) titleLabelConstraint = titleLabel.topAnchor.constraint(equalTo: topView.safeAreaLayoutGuide.topAnchor) joinButtonWidthConstraint = joinButton.widthAnchor.constraint(equalToConstant: 0) joinButtonHeightConstraint = joinButton.heightAnchor.constraint(equalToConstant: 0) joinButtonLeftConstraint = joinButton.leftAnchor.constraint(equalTo: topView.leftAnchor, constant: 0) createButtonWidthConstraint = createButton.widthAnchor.constraint(equalToConstant: 0) publicButtonWidthConstraint = publicButton.widthAnchor.constraint(equalToConstant: 0) privateButtonLeftConstraint = publicButton.leftAnchor.constraint(equalTo: topView.leftAnchor, constant: 0) privateButtonWidthConstraint = privateButton.widthAnchor.constraint(equalToConstant: 0) backButtonWidth = backButton.widthAnchor.constraint(equalToConstant: 30) statsButtonLeftConstraint = statsButton.leftAnchor.constraint(equalTo: topView.leftAnchor, constant: 0) statsButtonWidthConstraint = statsButton.widthAnchor.constraint(equalToConstant: 0) backButtonLeftConstraintForStats = backButton.leftAnchor.constraint(equalTo: statsButton.leftAnchor) backButtonLeftConstraintForJoinOptions = backButton.leftAnchor.constraint(equalTo: publicButton.leftAnchor) backButtonLeftConstraintForJoinOptions.isActive = true let constraints = [ titleLabelConstraint!, medalView.topAnchor.constraint(equalTo: topView.topAnchor), medalView.bottomAnchor.constraint(equalTo: topView.bottomAnchor), medalView.leftAnchor.constraint(equalTo: topView.leftAnchor), medalView.rightAnchor.constraint(equalTo: topView.rightAnchor), titleLabel.leftAnchor.constraint(equalTo: topView.leftAnchor, constant: 30), titleLabel.widthAnchor.constraint(equalTo: topView.widthAnchor), subtitleLabel.leftAnchor.constraint(equalTo: topView.leftAnchor, constant: 30), subtitleLabel.widthAnchor.constraint(equalTo: topView.widthAnchor), subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10), joinButtonWidthConstraint!, joinButtonHeightConstraint!, joinButtonLeftConstraint!, createButtonWidthConstraint!, publicButtonWidthConstraint!, privateButtonLeftConstraint!, privateButtonWidthConstraint!, backButtonWidth!, statsButtonLeftConstraint!, statsButtonWidthConstraint!, joinButton.topAnchor.constraint(equalTo: subtitleLabel.bottomAnchor, constant: 40.0), publicButton.topAnchor.constraint(equalTo: joinButton.topAnchor), statsButton.topAnchor.constraint(equalTo: joinButton.topAnchor), createButton.heightAnchor.constraint(equalTo: joinButton.heightAnchor), publicButton.heightAnchor.constraint(equalTo: joinButton.heightAnchor), privateButton.heightAnchor.constraint(equalTo: joinButton.heightAnchor), statsButton.heightAnchor.constraint(equalTo: joinButton.heightAnchor), createButton.leftAnchor.constraint(equalTo: joinButton.leftAnchor), privateButton.leftAnchor.constraint(equalTo: publicButton.leftAnchor), createButton.topAnchor.constraint(equalTo: joinButton.bottomAnchor, constant: 20.0), privateButton.topAnchor.constraint(equalTo: createButton.topAnchor), plusButton.leftAnchor.constraint(equalTo: joinButton.leftAnchor), plusButton.topAnchor.constraint(equalTo: createButton.bottomAnchor, constant: 20.0), plusButton.widthAnchor.constraint(equalTo: backButton.widthAnchor), plusButton.heightAnchor.constraint(equalTo: backButton.widthAnchor), backButton.topAnchor.constraint(equalTo: privateButton.bottomAnchor, constant: 20.0), backButton.heightAnchor.constraint(equalTo: backButton.widthAnchor, multiplier: 1) ] NSLayoutConstraint.activate(constraints) } /// Sets up the buttons private func setupButtons() { joinButton.title = "join" joinButton.translatesAutoresizingMaskIntoConstraints = false joinButton.addTarget(self, action: #selector(showJoinOptions), for: .touchUpInside) topView.addSubview(joinButton) createButton.title = "create" createButton.translatesAutoresizingMaskIntoConstraints = false createButton.addTarget(self, action: #selector(createRace), for: .touchUpInside) topView.addSubview(createButton) publicButton.title = "public" publicButton.translatesAutoresizingMaskIntoConstraints = false publicButton.addTarget(self, action: #selector(joinPublicRace), for: .touchUpInside) topView.addSubview(publicButton) privateButton.title = "private" privateButton.translatesAutoresizingMaskIntoConstraints = false privateButton.addTarget(self, action: #selector(joinPrivateRace), for: .touchUpInside) topView.addSubview(privateButton) statsButton.title = "stats" statsButton.translatesAutoresizingMaskIntoConstraints = false statsButton.addTarget(self, action: #selector(statsButtonPressed), for: .touchUpInside) topView.addSubview(statsButton) if #available(iOS 13.4, *) { backButton.isPointerInteractionEnabled = true plusButton.isPointerInteractionEnabled = true } backButton.setImage(UIImage(named: "Back")!, for: .normal) backButton.translatesAutoresizingMaskIntoConstraints = false backButton.addTarget(self, action: #selector(backButtonPressed), for: .touchUpInside) topView.addSubview(backButton) let config = UIImage.SymbolConfiguration(weight: .semibold) plusButton.setImage(UIImage(systemName: "plus", withConfiguration: config)!, for: .normal) plusButton.translatesAutoresizingMaskIntoConstraints = false plusButton.addTarget(self, action: #selector(plusButtonPressed), for: .touchUpInside) topView.addSubview(plusButton) } /// Sets up the labels private func setupLabels() { titleLabel.translatesAutoresizingMaskIntoConstraints = false topView.addSubview(titleLabel) subtitleLabel.text = "Conquer the encyclopedia\nof everything." subtitleLabel.numberOfLines = 2 subtitleLabel.translatesAutoresizingMaskIntoConstraints = false subtitleLabel.clipsToBounds = true topView.addSubview(subtitleLabel) } // MARK: - Bottom View - /// Sets up the bottom views func setupBottomView() { let stackView = setupStatsStackView() bottomView.addSubview(movingPuzzleView) puzzleViewHeightConstraint = movingPuzzleView.heightAnchor.constraint(equalToConstant: 75) let constraints = [ puzzleViewHeightConstraint!, movingPuzzleView.leftAnchor.constraint(equalTo: bottomView.leftAnchor), movingPuzzleView.rightAnchor.constraint(equalTo: bottomView.rightAnchor), movingPuzzleView.bottomAnchor.constraint(equalTo: bottomView.bottomAnchor), stackView.leftAnchor.constraint(equalTo: bottomView.leftAnchor, constant: 15), stackView.rightAnchor.constraint(equalTo: bottomView.rightAnchor, constant: -15), stackView.topAnchor.constraint(equalTo: bottomView.topAnchor), stackView.bottomAnchor.constraint(equalTo: movingPuzzleView.topAnchor) ] NSLayoutConstraint.activate(constraints) } /// Sets up the stack view that holds the menu tiles private func setupStatsStackView() -> UIStackView { let statsStackView = UIStackView() statsStackView.distribution = .fillEqually statsStackView.translatesAutoresizingMaskIntoConstraints = false bottomView.addSubview(statsStackView) let leftMenuTile = MenuTile(title: "WIKI POINTS") leftMenuTile.value = PlayerStatsManager.shared.multiplayerPoints statsStackView.addArrangedSubview(leftMenuTile) let middleMenuTile = MenuTile(title: "AVG PER RACE") middleMenuTile.isAverage = true middleMenuTile.value = PlayerUserDefaultsStat.multiplayerAverage.value() statsStackView.addArrangedSubview(middleMenuTile) let leftThinLine = WKRUIThinLineView() middleMenuTile.addSubview(leftThinLine) let rightThinLine = WKRUIThinLineView() middleMenuTile.addSubview(rightThinLine) let rightMenuTile = MenuTile(title: "RACES PLAYED") rightMenuTile.value = PlayerStatsManager.shared.multiplayerRaces statsStackView.addArrangedSubview(rightMenuTile) let constraints = [ leftThinLine.leftAnchor.constraint(equalTo: middleMenuTile.leftAnchor), leftThinLine.topAnchor.constraint(equalTo: middleMenuTile.topAnchor, constant: 30), leftThinLine.bottomAnchor.constraint(equalTo: middleMenuTile.bottomAnchor, constant: -25), leftThinLine.widthAnchor.constraint(equalToConstant: 2), rightThinLine.rightAnchor.constraint(equalTo: middleMenuTile.rightAnchor), rightThinLine.topAnchor.constraint(equalTo: middleMenuTile.topAnchor, constant: 30), rightThinLine.bottomAnchor.constraint(equalTo: middleMenuTile.bottomAnchor, constant: -25), rightThinLine.widthAnchor.constraint(equalToConstant: 2) ] NSLayoutConstraint.activate(constraints) leftMenuTile.addTarget(self, action: #selector(menuTilePressed), for: .touchUpInside) middleMenuTile.addTarget(self, action: #selector(menuTilePressed), for: .touchUpInside) rightMenuTile.addTarget(self, action: #selector(menuTilePressed), for: .touchUpInside) self.leftMenuTile = leftMenuTile self.middleMenuTile = middleMenuTile self.rightMenuTile = rightMenuTile PlayerStatsManager.shared.menuStatsUpdated = { points, races, average in DispatchQueue.main.async { self.leftMenuTile?.value = points self.middleMenuTile?.value = average self.rightMenuTile?.value = races } } if Defaults.isFastlaneSnapshotInstance { self.leftMenuTile?.value = 140 self.middleMenuTile?.value = 140/72 self.rightMenuTile?.value = 72 } return statsStackView } }
mit
c7217b44aefdf1644edb8e9173aaa0af
45.491597
115
0.712698
5.787134
false
false
false
false
alienxp03/MetalDemo
MetalDemo/GPUTester.swift
1
2053
// // GPUTester.swift // MetalDemo // // Created by tokwan on 9/13/15. // Copyright © 2015 alienxp03. All rights reserved. // import UIKit class GPUTester: Tester { func pow(size: Int) -> [Float] { var vector = [Float](count: size, repeatedValue: 0) for (index, _) in vector.enumerate() { vector[index] = Float(index) } let (device, _, defaultLibrary, commandBuffer, computeCommandEncoder) = initMetal() let sigmoidProgram = defaultLibrary.newFunctionWithName("pow") let computePipelineFilter = try! device.newComputePipelineStateWithFunction(sigmoidProgram!) computeCommandEncoder.setComputePipelineState(computePipelineFilter) let vectorByteLength = vector.count * sizeofValue(vector[0]) let inVectorBuffer = device.newBufferWithBytes(&vector, length: vectorByteLength, options: .CPUCacheModeWriteCombined) computeCommandEncoder.setBuffer(inVectorBuffer, offset: 0, atIndex: 0) var resultdata = [Float](count:vector.count, repeatedValue: 0) let outVectorBuffer = device.newBufferWithBytes(&resultdata, length: vectorByteLength, options: .CPUCacheModeWriteCombined) computeCommandEncoder.setBuffer(outVectorBuffer, offset: 0, atIndex: 1) let threadsPerGroup = MTLSize(width:32, height:1, depth:1) let numThreadgroups = MTLSize(width:(vector.count + 31) / 32, height:1, depth:1) computeCommandEncoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerGroup) computeCommandEncoder.endEncoding() commandBuffer.commit() commandBuffer.waitUntilCompleted() let data = NSData(bytesNoCopy: outVectorBuffer.contents(), length: vector.count*sizeof(Float), freeWhenDone: false) var finalResultArray = [Float](count: vector.count, repeatedValue: 0) data.getBytes(&finalResultArray, length:vector.count * sizeof(Float)) return finalResultArray } }
mit
ee473e2db3d45e3545674ac6d20f0918
41.75
131
0.685185
4.839623
false
true
false
false
Chrisphy/Xpense-Trackr
Xpense Trackr/Expenses.swift
1
1887
// // Expenses.swift // Xpense Trackr // // Created by CHRIS CHONG on 1/05/2017. // Copyright © 2017 CHRIS CHONG. All rights reserved. // import UIKit class Expenses : NSObject, NSCoding { //Storage Paths static let Directory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first! static let Archive = Directory.appendingPathComponent("expenses") struct propertyKey { static let name = "name" static let photo = "photo" static let expenseValue = "value" } var name: String var photo: UIImage? var expenseValue: Double //MARK: Initialization init?(name: String, photo: UIImage?, value: Double) { // The name must not be empty guard !name.isEmpty else { return nil } guard (value > 0) else{ return nil } // Initialize stored properties. self.name = name self.photo = photo self.expenseValue = value } func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: propertyKey.name) aCoder.encode(photo, forKey: propertyKey.photo) aCoder.encode(expenseValue, forKey: propertyKey.expenseValue) } required convenience init?(coder aDecoder: NSCoder) { // The name is required. guard let name = aDecoder.decodeObject(forKey: propertyKey.name) as? String else { print("Decoding failed.") return nil } // Cast for photo let photo = aDecoder.decodeObject(forKey: propertyKey.photo) as? UIImage let expenseValue = aDecoder.decodeDouble(forKey: propertyKey.expenseValue) // initialiser self.init(name: name, photo: photo, value: expenseValue) } }
mit
ca4cf1ca7456879b39bb36983f7ac72a
24.146667
98
0.584305
4.75063
false
false
false
false
fhchina/ReactiveCocoa
ReactiveCocoa/Swift/FoundationExtensions.swift
161
1727
// // FoundationExtensions.swift // ReactiveCocoa // // Created by Justin Spahr-Summers on 2014-10-19. // Copyright (c) 2014 GitHub. All rights reserved. // import Foundation import Result extension NSNotificationCenter { /// Returns a producer of notifications posted that match the given criteria. /// This producer will not terminate naturally, so it must be explicitly /// disposed to avoid leaks. public func rac_notifications(name: String? = nil, object: AnyObject? = nil) -> SignalProducer<NSNotification, NoError> { return SignalProducer { observer, disposable in let notificationObserver = self.addObserverForName(name, object: object, queue: nil) { notification in sendNext(observer, notification) } disposable.addDisposable { self.removeObserver(notificationObserver) } } } } extension NSURLSession { /// Returns a producer that will execute the given request once for each /// invocation of start(). public func rac_dataWithRequest(request: NSURLRequest) -> SignalProducer<(NSData, NSURLResponse), NSError> { return SignalProducer { observer, disposable in let task = self.dataTaskWithRequest(request) { (data, response, error) in if let data = data, response = response { sendNext(observer, (data, response)) sendCompleted(observer) } else { sendError(observer, error) } } disposable.addDisposable { task.cancel() } task.resume() } } } /// Removes all nil values from the given sequence. internal func ignoreNil<T, S: SequenceType where S.Generator.Element == Optional<T>>(sequence: S) -> [T] { var results: [T] = [] for value in sequence { if let value = value { results.append(value) } } return results }
mit
21f826b9c5c04c5e7734b06a812068dc
26.412698
122
0.710481
3.925
false
false
false
false
apple/swift
test/DebugInfo/thunks.swift
36
1090
// RUN: %target-swift-frontend -emit-ir -g %s -o - | %FileCheck %s // RUN: %target-swift-frontend -emit-sil -emit-verbose-sil -g %s -o - | %FileCheck %s --check-prefix=SIL-CHECK // REQUIRES: objc_interop import Foundation class Foo : NSObject { @objc dynamic func foo(_ f: (Int64) -> Int64, x: Int64) -> Int64 { return f(x) } } let foo = Foo() let y = 3 as Int64 let i = foo.foo(-, x: y) // CHECK: define {{.*}}@"$ss5Int64VABIyByd_A2BIegyd_TR" // CHECK-NOT: ret // CHECK: call {{.*}}, !dbg ![[LOC:.*]] // CHECK: ![[FILE:[0-9]+]] = !DIFile(filename: "<compiler-generated>", directory: "") // CHECK: ![[THUNK:.*]] = distinct !DISubprogram(linkageName: "$ss5Int64VABIyByd_A2BIegyd_TR" // CHECK-SAME: file: ![[FILE]] // CHECK-NOT: line: // CHECK-SAME: flags: DIFlagArtificial // CHECK-SAME: ){{$}} // CHECK: ![[LOC]] = !DILocation(line: 0, scope: ![[THUNK]]) // SIL-CHECK: sil shared {{.*}}@$ss5Int64VABIyByd_A2BIegyd_TR // SIL-CHECK-NOT: return // SIL-CHECK: apply {{.*}}auto_gen
apache-2.0
3494c3f454d61d434d572ae7f354a0ba
36.586207
110
0.559633
3.114286
false
false
false
false
mortorqrobotics/morscout-ios
MorScout/View Controllers/JoinTeamVC.swift
1
1475
// // JoinTeamVC.swift // MorScout // // Created by Farbod Rafezy on 3/11/16. // Copyright © 2016 MorTorq. All rights reserved. // import Foundation class JoinTeamVC: UIViewController { @IBOutlet weak var teamCodeField: UITextField! override func viewDidLoad() { super.viewDidLoad() teamCodeField.becomeFirstResponder() } @IBAction func joinClick(_ sender: UIButton) { httpRequest(morTeamURL + "/teams/code/\(teamCodeField.text!)/join", type: "POST") { responseText in if responseText == "You already have a team" { alert(title: "Failed", message: "Seems like you already have a team.", buttonText: "OK", viewController: self) } else if responseText == "Team does not exist" { alert(title: "Team does not exist", message: "That team doesn't exist. Try another code.", buttonText: "OK", viewController: self) } else if responseText == "You are banned from this team" { alert(title: "Banned", message: "Jeez, looks like you were banned from this team.", buttonText: "OK", viewController: self) } else { let team = parseJSON(responseText) storage.set(false, forKey: "noTeam") storage.set(team["id"].stringValue, forKey: "team") storage.set("member", forKey: "position") self.goTo(viewController: "reveal") } } } }
mit
fe07a508bb2b64c82766d05a6227eca1
36.794872
146
0.600407
4.360947
false
false
false
false
tjnet/MultipleTableViewModernNewsApp
NewsAppSample/ArticleShowViewController.swift
1
1418
// // ArticleShowViewController.swift // NewsAppSample // // Created by jun on 2015/02/15. // Copyright (c) 2015年 edu.self. All rights reserved. // import UIKit import WebKit class ArticleShowViewController: UIViewController { var webView: WKWebView var link: NSString = "" required init(coder aDecoder: NSCoder) { self.webView = WKWebView(frame: CGRectZero) super.init(coder: aDecoder) } override init() { self.webView = WKWebView(frame: CGRectZero) super.init() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { self.webView = WKWebView(frame: CGRectZero) super.init() } override func viewDidLoad() { view.addSubview(webView) webView.setTranslatesAutoresizingMaskIntoConstraints(false) let height = NSLayoutConstraint(item: webView, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 1, constant: 0) let width = NSLayoutConstraint(item: webView, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 1, constant: 0) view.addConstraints([height, width]) // let url = NSURL(string:"http://www.appcoda.com") let url = NSURL(string: link) let request = NSURLRequest(URL:url!) webView.loadRequest(request) } }
mit
e1c4b5a45451048ed7b39d23d599bfe2
29.12766
155
0.649011
4.466877
false
false
false
false
aquarchitect/MyKit
Sources/Shared/Frameworks/ExtensionProtocols/ColorHexing.swift
1
2107
// // ColorHexing.swift // MyKit // // Created by Hai Nguyen. // Copyright (c) 2015 Hai Nguyen. // import CoreGraphics public protocol ColorHexing: class { init(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) init(hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) #if os(iOS) @discardableResult func getRed(_ red: UnsafeMutablePointer<CGFloat>?, green: UnsafeMutablePointer<CGFloat>?, blue: UnsafeMutablePointer<CGFloat>?, alpha: UnsafeMutablePointer<CGFloat>?) -> Bool @discardableResult func getHue(_ hue: UnsafeMutablePointer<CGFloat>?, saturation: UnsafeMutablePointer<CGFloat>?, brightness: UnsafeMutablePointer<CGFloat>?, alpha: UnsafeMutablePointer<CGFloat>?) -> Bool #elseif os(macOS) func getRed(_ red: UnsafeMutablePointer<CGFloat>?, green: UnsafeMutablePointer<CGFloat>?, blue: UnsafeMutablePointer<CGFloat>?, alpha: UnsafeMutablePointer<CGFloat>?) func getHue(_ hue: UnsafeMutablePointer<CGFloat>?, saturation: UnsafeMutablePointer<CGFloat>?, brightness: UnsafeMutablePointer<CGFloat>?, alpha: UnsafeMutablePointer<CGFloat>?) #endif } public extension ColorHexing { var hexUInt: UInt { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 self.getRed(&r, green: &g, blue: &b, alpha: &a) return UInt(r * 255) << 16 | UInt(g * 255) << 8 | UInt(b * 255) << 0 } init(hexUInt value: UInt, alpha: CGFloat = 1) { let r = CGFloat((value & 0xFF0000) >> 16) / 255 let g = CGFloat((value & 0x00FF00) >> 8) / 255 let b = CGFloat((value & 0x0000FF) >> 0) / 255 self.init(red: r, green: g, blue: b, alpha: alpha) } } public extension ColorHexing { var hexString: String { return String(format: "#%06X", hexUInt) } init?(hexString value: String) { guard let hex = value.hexUInt else { return nil } self.init(hexUInt: hex, alpha: 1) } } #if os(iOS) import UIKit extension UIColor: ColorHexing {} #elseif os(macOS) import AppKit extension NSColor: ColorHexing {} #endif
mit
775741a1ec79ced7b8719c1a494485e0
30.924242
189
0.667774
4.075435
false
false
false
false
alobanov/Dribbble
Dribbble/shared/network/DribbbleAPI.swift
1
2813
// // DribbbleAPI.swift // Dribbble // // Created by Lobanov Aleksey on 18.01.17. // Copyright © 2017 Lobanov Aleksey. All rights reserved. // import Foundation import RxSwift import Moya import Alamofire private extension String { var URLEscapedString: String { return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)! } } /// Method identifier enum NetworkReqestType { case shots case shotComments case unknown } enum DribbbleAPI { // // Shots http://developer.dribbble.com/v1/shots/ // case shots(page: Int, list: String?, timeframe: String?, date: Date?, sort: String?) // // Shot comments http://developer.dribbble.com/v1/shots/471756/comments // case shotComments(shotID: Int, page: Int, perPage: Int) } extension DribbbleAPI : TargetType { /// The method used for parameter encoding. public var parameterEncoding: ParameterEncoding { return URLEncoding.default } public var task: Task { switch self { default: return .request } } var base: String { return "https://api.dribbble.com/v1/" } var baseURL: URL { return URL(string: base)! } var path: String { switch self { case .shots(_, _, _, _, _): return "shots" case .shotComments(let shotID, _, _): return "shots/\(shotID)/comments" } } var method: Moya.Method { switch self { case .shots, .shotComments: return HTTPMethod.get } } var parameters: [String: Any]? { switch self { case .shots(let page, let list, let timeframe, let date, let sort): var shotsPrm = [String: AnyObject]() shotsPrm["page"] = page as AnyObject? shotsPrm["per_page"] = 50 as AnyObject? if let l = list {shotsPrm["list"] = l as AnyObject?} if let t = timeframe {shotsPrm["timeframe"] = t as AnyObject?} if let d = date {shotsPrm["date"] = d as AnyObject?} if let s = sort {shotsPrm["sort"] = s as AnyObject?} print(shotsPrm) return shotsPrm case .shotComments(_, let page, let perPage): var commentPrm = [String: Int]() commentPrm["page"] = page commentPrm["per_page"] = perPage return commentPrm } } var sampleData: Data { switch self { case .shots(let page, _, _, _, _): if page == 1 { return JSONReader.readJSONData("Feed") } else { return JSONReader.readJSONData("FeedPage2") } case .shotComments: return JSONReader.readJSONData("Comment") } } var methodIdentifier: Int { switch self { case .shots: return 1 case .shotComments: return 2 } } } func urlTransform(_ route: TargetType) -> String { return route.baseURL.appendingPathComponent(route.path).absoluteString }
mit
f46b5f57984c38927f0913e912a2c4c3
21.861789
90
0.627312
4.075362
false
false
false
false
roambotics/swift
test/Generics/issue-52932.swift
2
1469
// RUN: %target-typecheck-verify-swift -debug-generic-signatures 2>&1 | %FileCheck %s // https://github.com/apple/swift/issues/52932 // CHECK-LABEL: .ScalarProtocol@ // CHECK-NEXT: Requirement signature: <Self where Self : ScalarMultiplicative, Self == Self.[ScalarMultiplicative]Scalar> public protocol ScalarProtocol: ScalarMultiplicative where Self == Scalar { } // CHECK-LABEL: .ScalarMultiplicative@ // CHECK-NEXT: Requirement signature: <Self where Self.[ScalarMultiplicative]Scalar : ScalarProtocol> public protocol ScalarMultiplicative { associatedtype Scalar : ScalarProtocol } // CHECK-LABEL: .MapReduceArithmetic@ // CHECK-NEXT: Requirement signature: <Self where Self : Collection, Self : ScalarMultiplicative, Self.[Sequence]Element : ScalarMultiplicative, Self.[ScalarMultiplicative]Scalar == Self.[Sequence]Element.[ScalarMultiplicative]Scalar> public protocol MapReduceArithmetic : ScalarMultiplicative, Collection where Element : ScalarMultiplicative, Scalar == Element.Scalar { } // CHECK-LABEL: .Tensor@ // CHECK-NEXT: Requirement signature: <Self where Self : MapReduceArithmetic, Self.[Sequence]Element : BinaryFloatingPoint, Self.[Sequence]Element == Self.[ScalarMultiplicative]Scalar> public protocol Tensor : MapReduceArithmetic where Scalar : BinaryFloatingPoint, Element == Scalar { var magnitude: Scalar { get set } } extension Tensor { public var magnitude: Scalar { return self.reduce(0) { $0 + $1 * $1 }.squareRoot() } }
apache-2.0
8a8ec8a6fe0d65cac79777ddfd3a62e9
49.655172
234
0.771273
4.619497
false
false
false
false
material-components/material-components-ios-codelabs
MDC-102/Swift/Complete/Shrine/Shrine/HomeViewController.swift
1
6289
/* Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import MaterialComponents class HomeViewController: UICollectionViewController { var shouldDisplayLogin = true //TODO: Add an appBarViewController property var appBarViewController = MDCAppBarViewController() override func viewDidLoad() { super.viewDidLoad() self.view.tintColor = .black self.view.backgroundColor = .white self.title = "Shrine" self.collectionView?.backgroundColor = .white // AppBar Setup //TODO: Add the appBar controller and views self.addChildViewController(self.appBarViewController) self.view.addSubview(self.appBarViewController.view) self.appBarViewController.didMove(toParentViewController: self) // Set the tracking scroll view. self.appBarViewController.headerView.trackingScrollView = self.collectionView // Setup Navigation Items //TODO: Create the items and set them on the view controller's navigationItems properties let menuItemImage = UIImage(named: "MenuItem") let templatedMenuItemImage = menuItemImage?.withRenderingMode(.alwaysTemplate) let menuItem = UIBarButtonItem(image: templatedMenuItemImage, style: .plain, target: self, action: #selector(menuItemTapped(sender:))) self.navigationItem.leftBarButtonItem = menuItem let searchItemImage = UIImage(named: "SearchItem") let templatedSearchItemImage = searchItemImage?.withRenderingMode(.alwaysTemplate) let searchItem = UIBarButtonItem(image: templatedSearchItemImage, style: .plain, target: nil, action: nil) let tuneItemImage = UIImage(named: "TuneItem") let templatedTuneItemImage = tuneItemImage?.withRenderingMode(.alwaysTemplate) let tuneItem = UIBarButtonItem(image: templatedTuneItemImage, style: .plain, target: nil, action: nil) self.navigationItem.rightBarButtonItems = [ tuneItem, searchItem ] } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if (self.collectionViewLayout is UICollectionViewFlowLayout) { let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout let HORIZONTAL_SPACING: CGFloat = 8.0 let itemDimension: CGFloat = (self.view.frame.size.width - 3.0 * HORIZONTAL_SPACING) * 0.5 let itemSize = CGSize(width: itemDimension, height: itemDimension) flowLayout.itemSize = itemSize } if (self.shouldDisplayLogin) { let loginViewController = LoginViewController(nibName: nil, bundle: nil) self.present(loginViewController, animated: false, completion: nil) self.shouldDisplayLogin = false } } //MARK - Methods @objc func menuItemTapped(sender: Any) { let loginViewController = LoginViewController(nibName: nil, bundle: nil) self.present(loginViewController, animated: true, completion: nil) } //MARK - UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //TODO: Set the number of cells to be equal to the number of products in the catalog return Catalog.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = self.collectionView?.dequeueReusableCell(withReuseIdentifier: "ProductCell", for: indexPath) as! ProductCell //TODO: Set the properties of the cell to reflect to product from the model let product = Catalog.productAtIndex(index: indexPath.row) cell.imageView.image = UIImage(named: product.imageName) cell.nameLabel.text = product.productName cell.priceLabel.text = product.price return cell } } //MARK: - UIScrollViewDelegate // The following four methods must be forwarded to the tracking scroll view in order to implement // the Flexible Header's behavior. //TODO: Send the scrollView delegate messages to our appBar's headerView extension HomeViewController { override func scrollViewDidScroll(_ scrollView: UIScrollView) { if (scrollView == self.appBarViewController.headerView.trackingScrollView) { self.appBarViewController.headerView.trackingScrollDidScroll() } } override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if (scrollView == self.appBarViewController.headerView.trackingScrollView) { self.appBarViewController.headerView.trackingScrollDidEndDecelerating() } } override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { let headerView = self.appBarViewController.headerView if (scrollView == headerView.trackingScrollView) { headerView.trackingScrollDidEndDraggingWillDecelerate(decelerate) } } override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let headerView = self.appBarViewController.headerView if (scrollView == headerView.trackingScrollView) { headerView.trackingScrollWillEndDragging(withVelocity: velocity, targetContentOffset: targetContentOffset) } } }
apache-2.0
12c0e2c97c13afe97100bb5b5f1d504b
39.314103
97
0.691843
5.68112
false
false
false
false
liakhandrii/genetic_cars
simulation/GeneticCar/GeneticCar/ViewController.swift
1
1360
// // ViewController.swift // GeneticCar // // Created by Andrew Liakh on 3/27/17. // Copyright © 2017 Andrew Liakh. All rights reserved. // import Cocoa import SpriteKit import GameplayKit class ViewController: NSViewController { @IBOutlet var skView: SKView! override func viewDidLoad() { super.viewDidLoad() // Load 'GameScene.sks' as a GKScene. This provides gameplay related content // including entities and graphs. if let scene = GKScene(fileNamed: "GameScene") { // Get the SKScene from the loaded GKScene if let sceneNode = scene.rootNode as! GameScene? { // Copy gameplay related content over to the scene sceneNode.entities = scene.entities sceneNode.graphs = scene.graphs // Set the scale mode to scale to fit the window sceneNode.scaleMode = .aspectFill // Present the scene if let view = self.skView { view.presentScene(sceneNode) view.ignoresSiblingOrder = true view.showsFPS = true view.showsNodeCount = true } } } } }
mit
fe657c7be5e0540e5f8d43b2b0c6d83f
27.914894
84
0.52465
5.546939
false
false
false
false
glaurent/MessagesHistoryBrowser
MessagesHistoryBrowser/MessageFormatter.swift
1
7588
// // MessageFormatter.swift // MessagesHistoryBrowser // // Created by Guillaume Laurent on 18/10/15. // Copyright © 2015 Guillaume Laurent. All rights reserved. // import Cocoa class MessageFormatter { let dateFormatter = DateFormatter() let fullDateFormatter = DateFormatter() let noMessageString = "<no message>" let meString = "me" let unknownContact = "<unknown>" var ShowTerseTime:Bool = true { didSet { dateFormatter.dateStyle = ShowTerseTime ? .none : .short } } var showDetailedSender = false let dateParagraphStyle = NSMutableParagraphStyle() let contactNameParagraphStyle = NSMutableParagraphStyle() let separatorParagraphStyle = NSMutableParagraphStyle() let meColor = NSColor.clear let contactColor = NSColor(calibratedRed: 0.231, green: 0.518, blue: 0.941, alpha: 1) // NSColor(red: 0x66 / 255.0, green: 0x66 / 255.0, blue: 0xff / 255.0, alpha: 1.0) let searchHighlightColor = NSColor(calibratedRed: 0.951, green: 0.165, blue: 0.276, alpha: 1) // NSColor.red init() { dateFormatter.timeStyle = .short dateFormatter.dateStyle = .none fullDateFormatter.timeStyle = .long fullDateFormatter.dateStyle = .long // ShowTerseTime = true dateParagraphStyle.alignment = .center // dateParagraphStyle.lineSpacing = 15 dateParagraphStyle.paragraphSpacing = 15 dateParagraphStyle.paragraphSpacingBefore = 15 contactNameParagraphStyle.alignment = .center // contactNameParagraphStyle.lineSpacing = 15 contactNameParagraphStyle.paragraphSpacing = 25 contactNameParagraphStyle.paragraphSpacingBefore = 25 } // used for log saves // func formatMessageAsString(_ message:ChatMessage) -> String { let messageContent = message.content ?? noMessageString let sender = message.isFromMe ? meString : message.chat.contact.name let dateString = dateFormatter.string(from: message.date as Date) let messageContentAndSender = "\(dateString) - \(sender) : \(messageContent)" return messageContentAndSender } func formatMessage(_ message:ChatMessage, withHighlightTerm highlightTerm:String? = nil) -> NSAttributedString? { guard let messageContent = message.content else { return nil } guard messageContent != "" else { return nil } let result = formatMessagePreamble(message, detailed: showDetailedSender) // highlight message content // // let messageContentNS = NSString(string:" - \(message.index) : " + messageContent + "\n") // has to be an NSString because we use rangeOfString below let messageContentNS = NSString(string:" : " + messageContent + "\n") // has to be an NSString because we use rangeOfString below let highlightedMessage = NSMutableAttributedString(string: messageContentNS as String, attributes: [NSAttributedString.Key.foregroundColor : NSColor.textColor]) if let highlightTerm = highlightTerm { let rangeOfSearchedTerm = messageContentNS.range(of: highlightTerm) highlightedMessage.addAttribute(NSAttributedString.Key.foregroundColor, value: searchHighlightColor, range: rangeOfSearchedTerm) } result.append(highlightedMessage) return result } func formatMessagePreamble(_ message:ChatMessage, detailed:Bool) -> NSMutableAttributedString { let dateString = NSMutableAttributedString(string: dateFormatter.string(from: message.date as Date)) if detailed { let chatContact = message.contact let sender:NSMutableAttributedString if message.isFromMe { sender = NSMutableAttributedString(string: meString, attributes: [NSAttributedString.Key.foregroundColor : NSColor.textColor, NSAttributedString.Key.backgroundColor : meColor]) } else { sender = NSMutableAttributedString(string: chatContact.name , attributes: [NSAttributedString.Key.foregroundColor : NSColor.textColor, NSAttributedString.Key.backgroundColor : contactColor]) } let dateString = NSMutableAttributedString(string: dateFormatter.string(from: message.date as Date), attributes:[NSAttributedString.Key.foregroundColor : NSColor.textColor]) dateString.append(NSAttributedString(string: " - ")) // dateString.appendAttributedString(NSAttributedString(string: " - \(message.index) -")) dateString.append(sender) return dateString } else { let range = NSRange(location: 0, length: dateString.length) if message.isFromMe { dateString.addAttribute(NSAttributedString.Key.backgroundColor, value: meColor, range: range) } else { dateString.addAttribute(NSAttributedString.Key.backgroundColor, value: contactColor, range: range) } dateString.addAttribute(NSAttributedString.Key.foregroundColor, value: NSColor.textColor, range: range) return dateString } } func formatMessageDate(_ messageDate:Date) -> NSAttributedString { let res = NSMutableAttributedString(string: fullDateFormatter.string(from: messageDate) + "\n") let range = NSRange(location: 0, length: res.length) // res.addAttribute(NSParagraphStyleAttributeName, value: dateParagraphStyle, range: range) // res.addAttribute(NSForegroundColorAttributeName, value: NSColor.lightGrayColor(), range: range) res.addAttributes([ NSAttributedString.Key.paragraphStyle : dateParagraphStyle, NSAttributedString.Key.foregroundColor : NSColor.lightGray], range: range) return res } func formatMessageContact(_ messageContact:ChatContact) -> NSAttributedString { let res = NSMutableAttributedString(string: messageContact.name + "\n") let range = NSRange(location: 0, length: res.length) res.addAttributes([ NSAttributedString.Key.font : NSFont.boldSystemFont(ofSize: 13.0), NSAttributedString.Key.paragraphStyle : contactNameParagraphStyle, NSAttributedString.Key.foregroundColor : NSColor.darkGray], range: range) return res } let separatorString:NSAttributedString = { let separatorParagraphStyle = NSMutableParagraphStyle() separatorParagraphStyle.alignment = .center separatorParagraphStyle.paragraphSpacing = 10 separatorParagraphStyle.paragraphSpacingBefore = 5 let res = NSMutableAttributedString(string: "_____\n") let range = NSRange(location: 0, length: res.length) res.addAttributes([ NSAttributedString.Key.font : NSFont.systemFont(ofSize: 15.0), NSAttributedString.Key.paragraphStyle : separatorParagraphStyle, NSAttributedString.Key.foregroundColor : NSColor.lightGray], range: range) return res }() func colorForMessageService(_ serviceName:String) -> NSColor? { var color:NSColor? switch serviceName { case "iMessage": color = NSColor.blue case "SMS" : color = NSColor.green case "jabber": color = NSColor.orange default: color = nil } return color } }
gpl-3.0
7e3e520d974900411babc8edae30bd69
36.374384
185
0.66324
5.346723
false
true
false
false
burnsra/SquidBar
SquidBar/AppDelegate.swift
1
10560
// // AppDelegate.swift // SquidBar // // Created by Robert Burns on 2/11/16. // Copyright © 2016 Robert Burns. All rights reserved. // import Cocoa import EonilFileSystemEvents @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var statusMenu: NSMenu! @IBOutlet weak var preferencesWindow: NSWindow! @IBOutlet weak var serverStatusMenuItem: NSMenuItem! @IBOutlet weak var serverStartMenuItem: NSMenuItem! @IBOutlet weak var serverStopMenuItem: NSMenuItem! @IBOutlet weak var configurationFileTextfield: NSTextField! @IBOutlet weak var executableFileTextField: NSTextField! @IBOutlet weak var startOnLaunchCheckBox: NSButton! @IBOutlet weak var watchNetworkCheckBox: NSButton! @IBOutlet weak var launchOnLoginCheckBox: NSButton! let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(NSVariableStatusItemLength) let preferenceController = PreferenceController() let squidController = SquidController() var monitor = nil as FileSystemEventMonitor? var queue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0) func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application if (preferenceController.squidStartOnLaunch == true) { if (!squidController.isSquidRunning()) { squidController.startSquid() } } delay(4) { self.updateStatusMenuItems() } } func applicationDidBecomeActive(notification: NSNotification) { // Insert code here to enter the foreground state let onEvents = { (events:[FileSystemEvent]) -> () in dispatch_async(dispatch_get_main_queue()) { for ev in events { if (self.preferenceController.squidWatchNetwork == true) { NSLog("\(Global.Application.statusNetworkChange)") if (ev.flag.description.rangeOfString("ItemRenamed") != nil) { NSLog("\(Global.Application.statusNetworkChangeValid)") // Add a delay so DNS entries are updated for the network change delay(1) { let nameServers = self.getNameServers(ev.path) if (nameServers != nil) { showNotification(Global.Application.statusRestartingNetwork) NSLog("\(Global.Application.statusRestartingNetwork)") //NSLog("..\(ev.flag.description) (\(ev.path))") NSLog("Server DNS entries (\(nameServers!))") self.squidController.restartSquid() } } } else { NSLog("\(Global.Application.statusNetworkChangeValid)") NSLog("\(Global.Application.statusNetworkChangeFlag) \(ev.flag.description)") } } } } } monitor = FileSystemEventMonitor(pathsToWatch: ["/etc/resolv.conf", "/private/var/run/resolv.conf"], latency: 1, watchRoot: false, queue: queue, callback: onEvents) updateStatusMenuItems() } func applicationWillResignActive(notification: NSNotification) { // Insert code here to leave the foreground state } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application monitor = nil squidController.stopSquid() } override func awakeFromNib() { let icon = NSImage(named: NSImageNameQuickLookTemplate) icon?.template = true statusItem.image = icon statusItem.menu = statusMenu statusItem.toolTip = "\(Global.Application.bundleName) \(Global.Application.bundleVersion)" } @IBAction func clickQuit(sender: NSMenuItem) { monitor = nil squidController.stopSquid() delay(4) { NSApplication.sharedApplication().terminate(self) } } @IBAction func openAbout(sender: NSMenuItem) { NSApplication.sharedApplication().orderFrontStandardAboutPanel(sender) NSApplication.sharedApplication().activateIgnoringOtherApps(true) } @IBAction func openDocumentation(sender: NSMenuItem) { if let url: NSURL = NSURL(string: "\(Global.Application.bundleProject)") { NSWorkspace.sharedWorkspace().openURL(url) } } @IBAction func openPreferences(sender: NSMenuItem) { self.preferencesWindow!.orderFront(self) NSApplication.sharedApplication().activateIgnoringOtherApps(true) if preferenceController.squidExecutable != nil { executableFileTextField.stringValue = preferenceController.squidExecutable! } if preferenceController.squidConfiguration != nil { configurationFileTextfield.stringValue = preferenceController.squidConfiguration! } if preferenceController.squidStartOnLaunch != nil { if (preferenceController.squidStartOnLaunch! == true) { startOnLaunchCheckBox.state = NSOnState } else { startOnLaunchCheckBox.state = NSOffState } } if preferenceController.squidWatchNetwork != nil { if (preferenceController.squidWatchNetwork! == true) { watchNetworkCheckBox.state = NSOnState } else { watchNetworkCheckBox.state = NSOffState } } if applicationIsInStartUpItems() == true { launchOnLoginCheckBox.state = NSOnState } else { launchOnLoginCheckBox.state = NSOffState } } @IBAction func resetPreferences(sender: NSButton) { preferenceController.resetDefaultPreferences() preferenceController.synchronizePreferences() executableFileTextField.stringValue = preferenceController.squidExecutable! configurationFileTextfield.stringValue = preferenceController.squidConfiguration! if (preferenceController.squidStartOnLaunch == true) { startOnLaunchCheckBox.state = NSOnState } else { startOnLaunchCheckBox.state = NSOffState } if (preferenceController.squidWatchNetwork == true) { watchNetworkCheckBox.state = NSOnState } else { watchNetworkCheckBox.state = NSOffState } preferenceController.synchronizePreferences() } @IBAction func browseConfigurationLoc(sender: NSButton) { configurationFileTextfield.stringValue = getDir(true, canChooseDirectories: false) preferenceController.squidConfiguration = configurationFileTextfield.stringValue preferenceController.synchronizePreferences() } @IBAction func browseExecutableLoc(sender: NSButton) { executableFileTextField.stringValue = getDir(true, canChooseDirectories: false) preferenceController.squidExecutable = executableFileTextField.stringValue preferenceController.synchronizePreferences() } @IBAction func startOnLaunch(sender: NSButton) { if startOnLaunchCheckBox.state == NSOnState { preferenceController.squidStartOnLaunch = true } else if (startOnLaunchCheckBox.state == NSOffState) { preferenceController.squidStartOnLaunch = false } preferenceController.synchronizePreferences() } @IBAction func launchOnLogin(sender: NSButton) { setLaunchAtStartup(Bool(sender.state)) } @IBAction func watchNetwork(sender: NSButton) { if watchNetworkCheckBox.state == NSOnState { preferenceController.squidWatchNetwork = true } else if (watchNetworkCheckBox.state == NSOffState) { preferenceController.squidWatchNetwork = false } preferenceController.synchronizePreferences() } @IBAction func serverStart(sender: NSMenuItem) { resetServerStatusMenuItem() squidController.restartSquid() delay(8) { self.updateStatusMenuItems() } } @IBAction func serverStop(sender: NSMenuItem) { resetServerStatusMenuItem() squidController.stopSquid() delay(4) { self.updateStatusMenuItems() } } func resetServerStatusMenuItem() { self.serverStatusMenuItem.title = "\(Global.Application.statusUnknown)" self.serverStatusMenuItem.hidden = false self.serverStartMenuItem.hidden = true self.serverStopMenuItem.hidden = true } func updateStatusMenuItems() { if squidController.isSquidRunning() { self.serverStatusMenuItem.hidden = false self.serverStartMenuItem.hidden = true self.serverStopMenuItem.hidden = false if let port = squidController.getPort() { self.serverStatusMenuItem.title = "\(Global.Application.statusListening) \(port)" } } else { self.serverStatusMenuItem.title = "\(Global.Application.statusUnknown)" self.serverStatusMenuItem.hidden = true self.serverStartMenuItem.hidden = false self.serverStopMenuItem.hidden = true } } func getNameServers(file: String) -> String? { let resolveFile = file var nameServers = "" do { let content = try String(contentsOfFile: resolveFile, encoding: NSUTF8StringEncoding) let contentArray = content.componentsSeparatedByString("\n") for (_, element) in contentArray.enumerate() { let lineContent = element.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) if ((lineContent.rangeOfString("nameserver") != nil)) { if let port = lineContent.componentsSeparatedByString(" ").last { if (nameServers.characters.count > 1) { nameServers.appendContentsOf(",") } nameServers.appendContentsOf(port.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())) } } } return nameServers } catch _ as NSError { return nil } } }
mit
4c84096ec497f1f31a8b7cf4d73116d6
37.9631
172
0.630931
5.439979
false
false
false
false
BronxDupaix/WaffleLuv
WaffleLuv/Reachability.swift
26
12799
/* Copyright (c) 2014, Ashley Mills All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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. */ // Reachability.swift version 2.2beta2 import SystemConfiguration import Foundation public enum ReachabilityError: ErrorType { case FailedToCreateWithAddress(sockaddr_in) case FailedToCreateWithHostname(String) case UnableToSetCallback case UnableToSetDispatchQueue } public let ReachabilityChangedNotification = "ReachabilityChangedNotification" func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutablePointer<Void>) { let reachability = Unmanaged<Reachability>.fromOpaque(COpaquePointer(info)).takeUnretainedValue() dispatch_async(dispatch_get_main_queue()) { reachability.reachabilityChanged(flags) } } public class Reachability: NSObject { public typealias NetworkReachable = (Reachability) -> () public typealias NetworkUnreachable = (Reachability) -> () public enum NetworkStatus: CustomStringConvertible { case NotReachable, ReachableViaWiFi, ReachableViaWWAN public var description: String { switch self { case .ReachableViaWWAN: return "Cellular" case .ReachableViaWiFi: return "WiFi" case .NotReachable: return "No Connection" } } } // MARK: - *** Public properties *** public var whenReachable: NetworkReachable? public var whenUnreachable: NetworkUnreachable? public var reachableOnWWAN: Bool public var notificationCenter = NSNotificationCenter.defaultCenter() public var currentReachabilityStatus: NetworkStatus { if isReachable() { if isReachableViaWiFi() { return .ReachableViaWiFi } if isRunningOnDevice { return .ReachableViaWWAN } } return .NotReachable } public var currentReachabilityString: String { return "\(currentReachabilityStatus)" } private var previousFlags: SCNetworkReachabilityFlags? // MARK: - *** Initialisation methods *** required public init(reachabilityRef: SCNetworkReachability) { reachableOnWWAN = true self.reachabilityRef = reachabilityRef } public convenience init(hostname: String) throws { let nodename = (hostname as NSString).UTF8String guard let ref = SCNetworkReachabilityCreateWithName(nil, nodename) else { throw ReachabilityError.FailedToCreateWithHostname(hostname) } self.init(reachabilityRef: ref) } public class func reachabilityForInternetConnection() throws -> Reachability { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) guard let ref = withUnsafePointer(&zeroAddress, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { throw ReachabilityError.FailedToCreateWithAddress(zeroAddress) } return Reachability(reachabilityRef: ref) } public class func reachabilityForLocalWiFi() throws -> Reachability { var localWifiAddress: sockaddr_in = sockaddr_in(sin_len: __uint8_t(0), sin_family: sa_family_t(0), sin_port: in_port_t(0), sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) localWifiAddress.sin_len = UInt8(sizeofValue(localWifiAddress)) localWifiAddress.sin_family = sa_family_t(AF_INET) // IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0 let address: UInt32 = 0xA9FE0000 localWifiAddress.sin_addr.s_addr = in_addr_t(address.bigEndian) guard let ref = withUnsafePointer(&localWifiAddress, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { throw ReachabilityError.FailedToCreateWithAddress(localWifiAddress) } return Reachability(reachabilityRef: ref) } // MARK: - *** Notifier methods *** public func startNotifier() throws { guard !notifierRunning else { return } var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque()) if !SCNetworkReachabilitySetCallback(reachabilityRef!, callback, &context) { stopNotifier() throw ReachabilityError.UnableToSetCallback } if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef!, reachabilitySerialQueue) { stopNotifier() throw ReachabilityError.UnableToSetDispatchQueue } // Perform an intial check dispatch_async(reachabilitySerialQueue) { () -> Void in let flags = self.reachabilityFlags self.reachabilityChanged(flags) } notifierRunning = true } public func stopNotifier() { defer { notifierRunning = false } guard let reachabilityRef = reachabilityRef else { return } SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil) } // MARK: - *** Connection test methods *** public func isReachable() -> Bool { let flags = reachabilityFlags return isReachableWithFlags(flags) } public func isReachableViaWWAN() -> Bool { let flags = reachabilityFlags // Check we're not on the simulator, we're REACHABLE and check we're on WWAN return isRunningOnDevice && isReachable(flags) && isOnWWAN(flags) } public func isReachableViaWiFi() -> Bool { let flags = reachabilityFlags // Check we're reachable if !isReachable(flags) { return false } // Must be on WiFi if reachable but not on an iOS device (i.e. simulator) if !isRunningOnDevice { return true } // Check we're NOT on WWAN return !isOnWWAN(flags) } // MARK: - *** Private methods *** private var isRunningOnDevice: Bool = { #if (arch(i386) || arch(x86_64)) && os(iOS) return false #else return true #endif }() private var notifierRunning = false private var reachabilityRef: SCNetworkReachability? private let reachabilitySerialQueue = dispatch_queue_create("uk.co.ashleymills.reachability", DISPATCH_QUEUE_SERIAL) private func reachabilityChanged(flags: SCNetworkReachabilityFlags) { guard previousFlags != flags else { return } if isReachableWithFlags(flags) { if let block = whenReachable { block(self) } } else { if let block = whenUnreachable { block(self) } } notificationCenter.postNotificationName(ReachabilityChangedNotification, object:self) previousFlags = flags } private func isReachableWithFlags(flags: SCNetworkReachabilityFlags) -> Bool { if !isReachable(flags) { return false } if isConnectionRequiredOrTransient(flags) { return false } if isRunningOnDevice { if isOnWWAN(flags) && !reachableOnWWAN { // We don't want to connect when on 3G. return false } } return true } // WWAN may be available, but not active until a connection has been established. // WiFi may require a connection for VPN on Demand. private func isConnectionRequired() -> Bool { return connectionRequired() } private func connectionRequired() -> Bool { let flags = reachabilityFlags return isConnectionRequired(flags) } // Dynamic, on demand connection? private func isConnectionOnDemand() -> Bool { let flags = reachabilityFlags return isConnectionRequired(flags) && isConnectionOnTrafficOrDemand(flags) } // Is user intervention required? private func isInterventionRequired() -> Bool { let flags = reachabilityFlags return isConnectionRequired(flags) && isInterventionRequired(flags) } private func isOnWWAN(flags: SCNetworkReachabilityFlags) -> Bool { #if os(iOS) return flags.contains(.IsWWAN) #else return false #endif } private func isReachable(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.Reachable) } private func isConnectionRequired(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.ConnectionRequired) } private func isInterventionRequired(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.InterventionRequired) } private func isConnectionOnTraffic(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.ConnectionOnTraffic) } private func isConnectionOnDemand(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.ConnectionOnDemand) } func isConnectionOnTrafficOrDemand(flags: SCNetworkReachabilityFlags) -> Bool { return !flags.intersect([.ConnectionOnTraffic, .ConnectionOnDemand]).isEmpty } private func isTransientConnection(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.TransientConnection) } private func isLocalAddress(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.IsLocalAddress) } private func isDirect(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.IsDirect) } private func isConnectionRequiredOrTransient(flags: SCNetworkReachabilityFlags) -> Bool { let testcase:SCNetworkReachabilityFlags = [.ConnectionRequired, .TransientConnection] return flags.intersect(testcase) == testcase } private var reachabilityFlags: SCNetworkReachabilityFlags { guard let reachabilityRef = reachabilityRef else { return SCNetworkReachabilityFlags() } var flags = SCNetworkReachabilityFlags() let gotFlags = withUnsafeMutablePointer(&flags) { SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0)) } if gotFlags { return flags } else { return SCNetworkReachabilityFlags() } } override public var description: String { var W: String if isRunningOnDevice { W = isOnWWAN(reachabilityFlags) ? "W" : "-" } else { W = "X" } let R = isReachable(reachabilityFlags) ? "R" : "-" let c = isConnectionRequired(reachabilityFlags) ? "c" : "-" let t = isTransientConnection(reachabilityFlags) ? "t" : "-" let i = isInterventionRequired(reachabilityFlags) ? "i" : "-" let C = isConnectionOnTraffic(reachabilityFlags) ? "C" : "-" let D = isConnectionOnDemand(reachabilityFlags) ? "D" : "-" let l = isLocalAddress(reachabilityFlags) ? "l" : "-" let d = isDirect(reachabilityFlags) ? "d" : "-" return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" } deinit { stopNotifier() reachabilityRef = nil whenReachable = nil whenUnreachable = nil } }
apache-2.0
3f1c3e14f2b82716299c8e2fac5cc051
34.065753
196
0.659739
5.593969
false
false
false
false
HJliu1123/LearningNotes-LHJ
April/Xbook/Xbook/pushNewBook/VIew/HJPushTitleViewController.swift
1
1304
// // HJPushTitleViewController.swift // Xbook // // Created by liuhj on 16/3/7. // Copyright © 2016年 liuhj. All rights reserved. // import UIKit typealias HJPushTitleCallBack = (Title:String)->Void class HJPushTitleViewController: UIViewController { var textField : UITextField? var callBack : HJPushTitleCallBack? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.textField = UITextField(frame: CGRectMake(15, 60, SCREEN_WIDTH - 30, 30)) self.textField?.borderStyle = .RoundedRect self.textField?.placeholder = "书评标题" self.textField?.font = UIFont(name: MY_FONT, size: 15) self.view.addSubview(self.textField!) self.textField?.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func sure() { self.callBack?(Title: self.textField!.text!) self.dismissViewControllerAnimated(true) { () -> Void in } } func close() { self.dismissViewControllerAnimated(true) { () -> Void in } } }
apache-2.0
9c74b765dc0a672fa1423249291bbb5f
22.089286
86
0.607889
4.684783
false
false
false
false
Bijiabo/F-Client-iOS
F/Library/FNetwork.swift
1
3205
// // FNetwork.swift // F // // Created by huchunbo on 15/11/16. // Copyright © 2015年 TIDELAB. All rights reserved. // import Foundation import Alamofire import SwiftyJSON class FNetwork { class func POST (path path: String, parameters: [String : AnyObject]? = nil, host: String = Config.host, encoding: ParameterEncoding = ParameterEncoding.JSON , completionHandler: (request: NSURLRequest, response: NSHTTPURLResponse?, json: SwiftyJSON.JSON, error:ErrorType?) -> Void) { Alamofire .request(.POST, "\(host)\(path)", parameters: parameters, encoding: ParameterEncoding.JSON) .responseSwiftyJSON({ (request, response, json, error) in completionHandler(request: request, response: response, json: json, error: error) }) } class func GET (path path: String, parameters: [String : AnyObject]? = nil, host: String = Config.host, encoding: ParameterEncoding = ParameterEncoding.JSON , completionHandler: (request: NSURLRequest, response: NSHTTPURLResponse?, json: SwiftyJSON.JSON, error:ErrorType?) -> Void) { Alamofire .request(.GET, "\(host)\(path)", parameters: parameters, encoding: ParameterEncoding.JSON) .responseSwiftyJSON({ (request, response, json, error) in completionHandler(request: request, response: response, json: json, error: error) }) } class func DELETE (path path: String, parameters: [String : AnyObject]? = nil, host: String = Config.host, encoding: ParameterEncoding = ParameterEncoding.JSON , completionHandler: (request: NSURLRequest, response: NSHTTPURLResponse?, json: SwiftyJSON.JSON, error:ErrorType?) -> Void) { Alamofire .request(.DELETE, "\(host)\(path)", parameters: parameters, encoding: ParameterEncoding.JSON) .responseSwiftyJSON({ (request, response, json, error) in completionHandler(request: request, response: response, json: json, error: error) }) } class func UPLOAD (path path: String, multipartFormData: MultipartFormData -> Void, host: String = Config.host, encoding: ParameterEncoding = ParameterEncoding.JSON , completionHandler: (request: NSURLRequest, response: NSHTTPURLResponse?, json: SwiftyJSON.JSON, error:ErrorType?) -> Void, failedHandler: (success: Bool, description: String)->Void) { Alamofire.upload( .POST, "\(host)\(path)", multipartFormData: multipartFormData, encodingCompletion: { encodingResult in var result = (success: false, description: "") switch encodingResult { case .Success(let upload, _, _): upload.responseSwiftyJSON({ (request, response, json, error) in completionHandler(request: request, response: response, json: json, error: error) }) case .Failure(_): result.description = "upload failure." failedHandler(success: result.success, description: result.description) } } ) } }
gpl-2.0
32b121588e6ba9ad33c56ad8eb0e15e7
48.276923
352
0.627733
5.066456
false
true
false
false
HLoveMe/HSomeFunctions-swift-
HScrollView/HScrollView/HScrollView/Tool/UIImageCache.swift
1
3845
// // Cache.swift // 对网络和本地图片的缓存功能 // // Created by 朱子豪 on 16/3/8. // Copyright © 2016年 朱子豪. All rights reserved. // import UIKit /** * 得到图片协议 */ public protocol imageAbleConversion{ func getImage(option:(UIImage?)->()); } /** * 得到图片路径/名字 */ public protocol StringConversion{ func getString()->String; } extension String:imageAbleConversion,StringConversion{ public func getString() -> String { return self } public func getImage(option:(UIImage?)->()){ UIImageCache.getImage(self, option: option) } } extension UIImage:imageAbleConversion{ public func getImage(option:(UIImage?)->()){ return option(self) } } extension NSURL:imageAbleConversion,StringConversion{ public func getString() -> String { return self.absoluteString } public func getImage(option:(UIImage?)->()){ UIImageCache.getImage(self, option: option) } } class UIImageCache{ static var outTime = 7 //天 static var path:String = { var document = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).last! document.appendContentsOf("/scroll-image") let manager = NSFileManager.defaultManager() if(!manager.fileExistsAtPath(document)){ try? manager.createDirectoryAtPath(document, withIntermediateDirectories: true, attributes: nil) } return document }() static func getImage(imageOption:StringConversion,option:(UIImage?)->()){ //本地文件 let image:UIImage? = UIImage.init(named:imageOption.getString()) if let _ = image{return option(image)} //网络已经保存 var data:NSData? var temp = path temp.appendContentsOf("//"+(imageOption.getString() as NSString).lastPathComponent) data = NSData.init(contentsOfFile:temp) if let _ = data { return option(UIImage.init(data: data!))} //网络 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in let url = NSURL.init(string: imageOption.getString()) guard let _ = url else {return option(nil)} data = NSData.init(contentsOfURL:url!) dispatch_sync(dispatch_get_main_queue(), { () -> Void in guard let _ = data else{return option(nil)} option(UIImage.init(data: data!)) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in data?.writeToFile(temp, atomically:true) } }) } } /**删除本地加载的图片 lib/cache/scroll-image */ static func deleteAllCache()->(){ let manager = NSFileManager.defaultManager() let paths:[String]? = try? manager.contentsOfDirectoryAtPath(path) guard let _ = paths else{return} paths!.map { (one) -> Void in try? manager.removeItemAtPath((path as NSString).stringByAppendingPathComponent(one)) } } /**删除过期图片 lib/cache/scroll-image */ static func deleteOutTimeFile()->(){ let manager = NSFileManager.defaultManager() let paths:[String]? = try? manager.contentsOfDirectoryAtPath(path) guard let _ = paths else{return} let now:Double = NSDate.init().timeIntervalSince1970 paths!.map { (one) -> Void in let dic = try? manager.attributesOfItemAtPath(one) let date:NSDate = dic![NSFileCreationDate] as! NSDate let old:Double = date.timeIntervalSince1970 let len = abs(now-old) if(Int(len) >= outTime * 24 * 3600){ try? manager.removeItemAtPath(one) } } } }
apache-2.0
a38c828bf4ab021eb7040142584a8452
33.453704
109
0.615323
4.402367
false
false
false
false
AgaKhanFoundation/WCF-iOS
Pods/OAuthSwift/Sources/HMAC.swift
2
1442
// // HMAC.swift // OAuthSwift // // Created by Dongri Jin on 1/28/15. // Copyright (c) 2015 Dongri Jin. All rights reserved. // import Foundation open class HMAC { let key: [UInt8] = [] class internal func sha1(key: Data, message: Data) -> Data? { let blockSize = 64 var key = key.bytes let message = message.bytes if key.count > blockSize { key = SHA1(key).calculate() } else if key.count < blockSize { // padding key += [UInt8](repeating: 0, count: blockSize - key.count) } var ipad = [UInt8](repeating: 0x36, count: blockSize) for idx in key.indices { ipad[idx] = key[idx] ^ ipad[idx] } var opad = [UInt8](repeating: 0x5c, count: blockSize) for idx in key.indices { opad[idx] = key[idx] ^ opad[idx] } let ipadAndMessageHash = SHA1(ipad + message).calculate() let mac = SHA1(opad + ipadAndMessageHash).calculate() return Data(bytes: UnsafePointer<UInt8>(mac), count: mac.count) } } extension HMAC: OAuthSwiftSignatureDelegate { public static func sign(hashMethod: OAuthSwiftHashMethod, key: Data, message: Data) -> Data? { switch hashMethod { case .sha1: return sha1(key: key, message: message) case .none: assertionFailure("Must no sign with none") return nil } } }
bsd-3-clause
a51fa3a5ae76e2e5236110b5884b7a47
25.218182
98
0.576283
3.774869
false
false
false
false
mitolog/SIOSocket-swift
SIOSocket-Swift/Sources/SIOSocket.playground/Contents.swift
1
1396
//: Playground - noun: a place where people can play import JavaScriptCore /* Call javascript function ver1 */ let context:JSContext = JSContext() context.evaluateScript("var factorial = function(n) { if(n<0){return;}if(n===0){return 1;}return n*factorial(n-1); }") let result: JSValue = context.evaluateScript("factorial(3)") print(result.toInt32()) /* Call javascript function ver2 */ //let context:JSContext = JSContext() //context.evaluateScript("var factorial = function(n) { if(n<0){return;}if(n===0){return 1;}return n*factorial(n-1); }") //let factorial:JSValue = context.objectForKeyedSubscript("factorial") //let result:JSValue = factorial.callWithArguments([3]) //print(result.toInt32()) /* Retrieve JSValue test */ //context.evaluateScript("var areas = {'okinawa':['Ginowan', 'Urasoe', 'Naha']};") //let areas = context.objectForKeyedSubscript("areas").toObject() //areas["okinawa"] // //let withTransports = ["'polling'", "'websocket'"] //withTransports.joinWithSeparator(",") /* Call swift callback from javascript */ //let context = JSContext() //let say: @convention(block) String -> String = { str in // return "say \(str)!" //} //context.setObject(unsafeBitCast(say, AnyObject!.self), forKeyedSubscript: "say") //print(context.evaluateScript("say('hello')")) // //let sayFunc = context.objectForKeyedSubscript("say") //print(sayFunc.callWithArguments(["hello2"]))
mit
36a284eb9144933df240886975d8f31a
33.04878
120
0.707736
3.644909
false
false
false
false
manavgabhawala/UberSDK
Shared/UberRequestReceipt.swift
1
5127
// // UberRequestReceipt.swift // UberSDK // // Created by Manav Gabhawala on 6/13/15. // // import Foundation @objc public final class UberRequestReceipt : NSObject, JSONCreateable { /// Unique identifier representing a Request. @objc public let requestID: String /// Describes the charges made against the rider. @objc public let charges : [UberReceiptDetail] /// Describes the surge charge. May be null if surge pricing was not in effect. @objc public let surgeCharge : UberReceiptDetail? /// Adjustments made to the charges such as promotions, and fees. @objc public let chargeAdjustments : [UberReceiptDetail] /// The summation of the charges. @objc public let normalFare : Double /// The summation of the normal_fare and surge_charge. @objc public let subtotal : Double /// The total amount charged to the users payment method. This is the the subtotal (split if applicable) with taxes included. @objc public let totalCharged : Double /// The total amount still owed after attempting to charge the user. May be null if amount was paid in full. @objc public let totalOwed : Double /// http://en.wikipedia.org/wiki/ISO_4217 ISO 4217 currency code. @objc public let currencyCode : String /// Time duration of the trip in ISO 8061 HH:MM:SS format. @objc public let duration : String /// Time duration of the trip as an NSTimeInterval. @objc public var timeDuration : NSTimeInterval { let components = duration.componentsSeparatedByString(":") assert(components.count == 3, "There needs to be 3 components in the time. The hours, minutes and seconds. The string provided was \(duration)") let hours = Double(components.first!)! let minutes = Double(components[1])! let seconds = Double(components.last!)! return (((hours * 60.0) + minutes) * 60.0) + seconds } /// Distance of the trip charged. @objc public let distance : String /// The localized unit of distance. @objc public let distanceUnits : String @objc public override var description : String { return "Receipt for trip \(timeDuration) and \(distance)\(distanceUnits) long. Total Cost: \(totalCharged)\(currencyCode)" } public required init?(JSON: [NSObject : AnyObject]) { surgeCharge = UberReceiptDetail(JSON: JSON["surge_charge"] as? [NSObject: AnyObject]) guard let id = JSON["request_id"] as? String, let normal = JSON["normal_fare"] as? Double, let sub = JSON["subtotal"] as? Double, let charged = JSON["total_charged"] as? Double, let owed = JSON["total_owed"] as? Double, let currency = JSON["currency_code"] as? String, let dur = JSON["duration"] as? String, let dist = JSON["distance"] as? String, let distUnits = JSON["distance_label"] as? String else { requestID = ""; normalFare = 0; subtotal = 0; totalCharged = 0; totalOwed = 0; currencyCode = ""; duration = ""; distance = ""; distanceUnits = ""; charges = []; chargeAdjustments = [] super.init() return nil } requestID = id normalFare = normal subtotal = sub totalCharged = charged totalOwed = owed currencyCode = currency duration = dur distance = dist distanceUnits = distUnits charges = UberReceiptDetail.createArray(JSON["charges"] as? [[NSObject: AnyObject]]) chargeAdjustments = UberReceiptDetail.createArray(JSON["charge_adjustments"] as? [[NSObject: AnyObject]]) super.init() } } /// A generalized class that can be a part of a receipt either as surge charge, a charge adjustment or even the general charges field. @objc public final class UberReceiptDetail : NSObject, JSONCreateable { /// The name of the charge. @objc public let name: String /// The amount @objc public let amount: Double /// The type of the receipt. Can be used in Swift only. For objective-c see the receiptType property. public let type: UberReceiptDetailType /// The type of the receipt as a string. For Swift type-safety, see the type property and the UberReceiptDetailType enum. @objc public var receiptType : String { return type.rawValue } @objc public override var description : String { return "Receipt Detail \(name) amounted to \(amount)" } public init?(JSON: [NSObject : AnyObject]) { guard let name = JSON["name"] as? String, let amount = JSON["amount"] as? Double, let rawType = JSON["type"] as? String else { self.name = ""; self.amount = 0; self.type = .Unknown super.init() return nil } self.name = name self.amount = amount self.type = UberReceiptDetailType(rawValue: rawType) ?? .Unknown super.init() } class func createArray(JSON: [[NSObject: AnyObject]]?) -> [UberReceiptDetail] { var array = [UberReceiptDetail]() guard let JSON = JSON else { return array } for item in JSON { if let newDetail = UberReceiptDetail(JSON: item) { array.append(newDetail) } } return array } } /// An enumeration that contains the possible types for an uber receipt. public enum UberReceiptDetailType : String { case BaseFare = "base_fare" case Distance = "distance" case Time = "time" case Surge = "surge" case SafeRideFee = "safe_ride_fee" case RoundingDown = "rounding_down" case Promotion = "promotion" case Unknown = "unknown" }
apache-2.0
d7741962c1737de242f67b40c5a4926e
36.985185
399
0.714648
3.664761
false
false
false
false
patrickreynolds/MagicMove
MagicMove/CustomTransitionExamples.swift
1
2948
// // CustomTransitionExamples.swift // MagicMove // // Created by Patrick Reynolds on 1/24/16. // Copyright © 2016 Patrick Reynolds. All rights reserved. // import UIKit // MARK: Fade Transition class FadeTransition: NSObject, UIViewControllerAnimatedTransitioning { let duration = 1.0 let originFrame = CGRect.zero func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return duration } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView()! let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! containerView.addSubview(toView) toView.alpha = 0.0 UIView.animateWithDuration(duration, animations: { toView.alpha = 1.0 }, completion: { _ in transitionContext.completeTransition(true) }) } } // MARK: Spin Transition enum SpinTransitionConstants: String { case BasicAnimationKeyPath case RotationAnimationKey var value: String { switch self { case .BasicAnimationKeyPath: return "transform.rotation.z" case .RotationAnimationKey: return "rotationAnimation" } } } class SpinTransition: NSObject, UIViewControllerAnimatedTransitioning { let duration = 0.5 let originFrame = CGRect.zero let rotations = 1.0 func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return duration } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView()! let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)! let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! toView.alpha = 0.0 containerView.addSubview(fromView) containerView.addSubview(toView) spinView(fromView, duration: duration, rotations: rotations) UIView.animateWithDuration(duration, delay: 0, options: .CurveEaseInOut, animations: { fromView.alpha = 0.0 toView.alpha = 1.0 }, completion: { _ in transitionContext.completeTransition(true) }) } // Private Helpers private func spinView(view: UIView, duration: NSTimeInterval, rotations: Double) { let rotationAnimation = CABasicAnimation(keyPath: SpinTransitionConstants.BasicAnimationKeyPath.value) rotationAnimation.toValue = Double(M_PI) * rotations * 2.0 rotationAnimation.duration = duration rotationAnimation.cumulative = true view.layer.addAnimation(rotationAnimation, forKey: SpinTransitionConstants.RotationAnimationKey.value) } }
mit
f03ee2bcfeebd8aba81b9083f438ffec
31.744444
110
0.683407
5.858847
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Browser/Tabs/RemoteTabsPanel.swift
2
30645
// 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 UIKit import Account import Shared import SnapKit import Storage import Sync protocol RemotePanelDelegate: AnyObject { func remotePanelDidRequestToSignIn() func remotePanelDidRequestToCreateAccount() func remotePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) func remotePanel(didSelectURL url: URL, visitType: VisitType) } // MARK: - RemoteTabsPanel class RemoteTabsPanel: UIViewController, Themeable, Loggable { var themeManager: ThemeManager var themeObserver: NSObjectProtocol? var notificationCenter: NotificationProtocol var remotePanelDelegate: RemotePanelDelegate? var profile: Profile lazy var tableViewController = RemoteTabsTableViewController() init(profile: Profile, themeManager: ThemeManager = AppContainer.shared.resolve(), notificationCenter: NotificationProtocol = NotificationCenter.default) { self.profile = profile self.themeManager = themeManager self.notificationCenter = notificationCenter super.init(nibName: nil, bundle: nil) notificationCenter.addObserver(self, selector: #selector(notificationReceived), name: .FirefoxAccountChanged, object: nil) notificationCenter.addObserver(self, selector: #selector(notificationReceived), name: .ProfileDidFinishSyncing, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableViewController.profile = profile tableViewController.remoteTabsPanel = self addChild(tableViewController) self.view.addSubview(tableViewController.view) tableViewController.view.snp.makeConstraints { make in make.top.left.right.bottom.equalTo(self.view) } tableViewController.didMove(toParent: self) listenForThemeChange() applyTheme() } func applyTheme() { view.backgroundColor = themeManager.currentTheme.colors.layer4 tableViewController.tableView.backgroundColor = themeManager.currentTheme.colors.layer3 tableViewController.tableView.separatorColor = themeManager.currentTheme.colors.borderPrimary tableViewController.tableView.reloadData() tableViewController.refreshTabs() } func forceRefreshTabs() { tableViewController.refreshTabs(updateCache: true) } @objc func notificationReceived(_ notification: Notification) { switch notification.name { case .FirefoxAccountChanged, .ProfileDidFinishSyncing: DispatchQueue.main.async { self.tableViewController.refreshTabs() } break default: // no need to do anything at all browserLog.warning("Received unexpected notification \(notification.name)") break } } } enum RemoteTabsError { case notLoggedIn case noClients case noTabs case failedToSync func localizedString() -> String { switch self { // This does not have a localized string because we have a whole specific screen for it. case .notLoggedIn: return "" case .noClients: return .EmptySyncedTabsPanelNullStateDescription case .noTabs: return .RemoteTabErrorNoTabs case .failedToSync: return .RemoteTabErrorFailedToSync } } } protocol RemoteTabsPanelDataSource: UITableViewDataSource, UITableViewDelegate { } protocol CollapsibleTableViewSection: AnyObject { func hideTableViewSection(_ section: Int) } // MARK: - RemoteTabsPanelClientAndTabsDataSource class RemoteTabsPanelClientAndTabsDataSource: NSObject, RemoteTabsPanelDataSource { struct UX { static let HeaderHeight = SiteTableViewControllerUX.RowHeight static let IconBorderColor = UIColor.Photon.Grey30 static let IconBorderWidth: CGFloat = 0.5 } weak var collapsibleSectionDelegate: CollapsibleTableViewSection? weak var remoteTabPanel: RemoteTabsPanel? var clientAndTabs: [ClientAndTabs] var hiddenSections = Set<Int>() private let siteImageHelper: SiteImageHelper private var theme: Theme init(remoteTabPanel: RemoteTabsPanel, clientAndTabs: [ClientAndTabs], profile: Profile, theme: Theme) { self.remoteTabPanel = remoteTabPanel self.clientAndTabs = clientAndTabs self.siteImageHelper = SiteImageHelper(profile: profile) self.theme = theme } @objc private func sectionHeaderTapped(sender: UIGestureRecognizer) { guard let section = sender.view?.tag else { return } collapsibleSectionDelegate?.hideTableViewSection(section) } func numberOfSections(in tableView: UITableView) -> Int { return self.clientAndTabs.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.hiddenSections.contains(section) { return 0 } return self.clientAndTabs[section].tabs.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let headerView = tableView.dequeueReusableHeaderFooterView( withIdentifier: SiteTableViewHeader.cellIdentifier) as? SiteTableViewHeader else { return nil } let clientTabs = self.clientAndTabs[section] let client = clientTabs.client let isCollapsed = hiddenSections.contains(section) let viewModel = SiteTableViewHeaderModel(title: client.name, isCollapsible: true, collapsibleState: isCollapsed ? ExpandButtonState.right : ExpandButtonState.down) headerView.configure(viewModel) headerView.showBorder(for: .bottom, true) headerView.showBorder(for: .top, section != 0) // Configure tap to collapse/expand section headerView.tag = section let tapGesture = UITapGestureRecognizer(target: self, action: #selector(sectionHeaderTapped(sender:))) headerView.addGestureRecognizer(tapGesture) headerView.applyTheme(theme: theme) /* * A note on timestamps. * We have access to two timestamps here: the timestamp of the remote client record, * and the set of timestamps of the client's tabs. * Neither is "last synced". The client record timestamp changes whenever the remote * client uploads its record (i.e., infrequently), but also whenever another device * sends a command to that client -- which can be much later than when that client * last synced. * The client's tabs haven't necessarily changed, but it can still have synced. * Ideally, we should save and use the modified time of the tabs record itself. * This will be the real time that the other client uploaded tabs. */ return headerView } func tabAtIndexPath(_ indexPath: IndexPath) -> RemoteTab { return clientAndTabs[indexPath.section].tabs[indexPath.item] } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: TwoLineImageOverlayCell.cellIdentifier, for: indexPath) as? TwoLineImageOverlayCell else { return UITableViewCell() } let tab = tabAtIndexPath(indexPath) cell.titleLabel.text = tab.title cell.descriptionLabel.text = tab.URL.absoluteString cell.leftImageView.layer.borderColor = UX.IconBorderColor.cgColor cell.leftImageView.layer.borderWidth = UX.IconBorderWidth cell.accessoryView = nil getFavicon(for: tab) { [weak cell] image in cell?.leftImageView.image = image cell?.leftImageView.backgroundColor = .clear } cell.applyTheme(theme: theme) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) let tab = tabAtIndexPath(indexPath) // Remote panel delegate for cell selection remoteTabPanel?.remotePanelDelegate?.remotePanel(didSelectURL: tab.URL, visitType: VisitType.typed) } private func getFavicon(for remoteTab: RemoteTab, completion: @escaping (UIImage?) -> Void) { let faviconUrl = remoteTab.URL.absoluteString let site = Site(url: faviconUrl, title: remoteTab.title) siteImageHelper.fetchImageFor(site: site, imageType: .favicon, shouldFallback: false) { image in completion(image) } } } // MARK: - RemoteTabsPanelErrorDataSource class RemoteTabsPanelErrorDataSource: NSObject, RemoteTabsPanelDataSource, ThemeApplicable { weak var remoteTabsPanel: RemoteTabsPanel? var error: RemoteTabsError var notLoggedCell: UITableViewCell? private var theme: Theme init(remoteTabsPanel: RemoteTabsPanel, error: RemoteTabsError, theme: Theme) { self.remoteTabsPanel = remoteTabsPanel self.error = error self.notLoggedCell = nil self.theme = theme } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if let cell = self.notLoggedCell { cell.updateConstraints() } return tableView.bounds.height } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { // Making the footer height as small as possible because it will disable button tappability if too high. return 1 } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch error { case .notLoggedIn: let cell = RemoteTabsNotLoggedInCell(remoteTabsPanel: remoteTabsPanel, theme: theme) self.notLoggedCell = cell return cell default: let cell = RemoteTabsErrorCell(error: self.error, theme: theme) self.notLoggedCell = nil return cell } } func applyTheme(theme: Theme) { self.theme = theme } } // MARK: - RemoteTabsErrorCell class RemoteTabsErrorCell: UITableViewCell, ReusableCell, ThemeApplicable { struct UX { static let EmptyStateInstructionsWidth = 170 static let EmptyStateTopPaddingInBetweenItems: CGFloat = 15 static let EmptyTabContentOffset: CGFloat = -180 } let titleLabel = UILabel() let emptyStateImageView = UIImageView() let instructionsLabel = UILabel() var theme: Theme init(error: RemoteTabsError, theme: Theme) { self.theme = theme super.init(style: .default, reuseIdentifier: RemoteTabsErrorCell.cellIdentifier) selectionStyle = .none separatorInset = UIEdgeInsets(top: 0, left: 1000, bottom: 0, right: 0) let containerView = UIView() contentView.addSubview(containerView) emptyStateImageView.image = UIImage.templateImageNamed(ImageIdentifiers.emptySyncImageName) containerView.addSubview(emptyStateImageView) emptyStateImageView.snp.makeConstraints { (make) -> Void in make.top.equalTo(containerView) make.centerX.equalTo(containerView) } titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont titleLabel.text = .EmptySyncedTabsPanelStateTitle titleLabel.textAlignment = .center containerView.addSubview(titleLabel) instructionsLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight instructionsLabel.text = error.localizedString() instructionsLabel.textAlignment = .center instructionsLabel.numberOfLines = 0 containerView.addSubview(instructionsLabel) titleLabel.snp.makeConstraints { make in make.top.equalTo(emptyStateImageView.snp.bottom).offset(UX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(emptyStateImageView) } instructionsLabel.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(UX.EmptyStateTopPaddingInBetweenItems / 2) make.centerX.equalTo(containerView) make.width.equalTo(UX.EmptyStateInstructionsWidth) } containerView.snp.makeConstraints { make in // Let the container wrap around the content make.top.equalTo(emptyStateImageView.snp.top) make.left.bottom.right.equalTo(instructionsLabel) // And then center it in the overlay view that sits on top of the UITableView make.centerX.equalTo(contentView) // Sets proper top constraint for iPhone 6 in portrait and for iPad. make.centerY.equalTo(contentView.snp.centerY).offset(UX.EmptyTabContentOffset).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(contentView.snp.top).offset(20).priority(1000) } containerView.backgroundColor = .clear applyTheme(theme: theme) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func applyTheme(theme: Theme) { emptyStateImageView.tintColor = theme.colors.textPrimary titleLabel.textColor = theme.colors.textPrimary instructionsLabel.textColor = theme.colors.textPrimary backgroundColor = theme.colors.layer3 } } // MARK: - RemoteTabsNotLoggedInCell class RemoteTabsNotLoggedInCell: UITableViewCell, ReusableCell, ThemeApplicable { struct UX { static let EmptyStateSignInButtonCornerRadius: CGFloat = 4 static let EmptyStateSignInButtonHeight = 44 static let EmptyStateSignInButtonWidth = 200 static let EmptyTabContentOffset: CGFloat = -180 } var remoteTabsPanel: RemoteTabsPanel? let instructionsLabel = UILabel() let signInButton = UIButton() let titleLabel = UILabel() let emptyStateImageView = UIImageView() var theme: Theme init(remoteTabsPanel: RemoteTabsPanel?, theme: Theme) { self.theme = theme super.init(style: .default, reuseIdentifier: RemoteTabsErrorCell.cellIdentifier) selectionStyle = .none self.remoteTabsPanel = remoteTabsPanel let createAnAccountButton = UIButton(type: .system) emptyStateImageView.image = UIImage.templateImageNamed(ImageIdentifiers.emptySyncImageName) contentView.addSubview(emptyStateImageView) titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont titleLabel.text = .EmptySyncedTabsPanelStateTitle titleLabel.textAlignment = .center contentView.addSubview(titleLabel) instructionsLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight instructionsLabel.text = .EmptySyncedTabsPanelNotSignedInStateDescription instructionsLabel.textAlignment = .center instructionsLabel.numberOfLines = 0 contentView.addSubview(instructionsLabel) signInButton.setTitle(.Settings.Sync.ButtonTitle, for: []) signInButton.setTitleColor(UIColor.Photon.White100, for: []) signInButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .subheadline) signInButton.layer.cornerRadius = UX.EmptyStateSignInButtonCornerRadius signInButton.clipsToBounds = true signInButton.addTarget(self, action: #selector(signIn), for: .touchUpInside) contentView.addSubview(signInButton) createAnAccountButton.setTitle(.RemoteTabCreateAccount, for: []) createAnAccountButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .caption1) createAnAccountButton.addTarget(self, action: #selector(createAnAccount), for: .touchUpInside) contentView.addSubview(createAnAccountButton) emptyStateImageView.snp.makeConstraints { (make) -> Void in make.centerX.equalTo(instructionsLabel) // Sets proper top constraint for iPhone 6 in portrait and for iPad. make.centerY.equalTo(contentView).offset(UX.EmptyTabContentOffset + 30).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(contentView.snp.top).priority(1000) } titleLabel.snp.makeConstraints { make in make.top.equalTo(emptyStateImageView.snp.bottom) .offset(RemoteTabsErrorCell.UX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(emptyStateImageView) } createAnAccountButton.snp.makeConstraints { (make) -> Void in make.centerX.equalTo(signInButton) make.top.equalTo(signInButton.snp.bottom).offset(RemoteTabsErrorCell.UX.EmptyStateTopPaddingInBetweenItems) } applyTheme(theme: theme) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func applyTheme(theme: Theme) { emptyStateImageView.tintColor = theme.colors.textPrimary titleLabel.textColor = theme.colors.textPrimary instructionsLabel.textColor = theme.colors.textPrimary signInButton.backgroundColor = theme.colors.textAccent backgroundColor = theme.colors.layer4 } @objc fileprivate func signIn() { if let remoteTabsPanel = self.remoteTabsPanel { TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .syncSignIn) remoteTabsPanel.remotePanelDelegate?.remotePanelDidRequestToSignIn() } } @objc fileprivate func createAnAccount() { if let remoteTabsPanel = self.remoteTabsPanel { TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .syncCreateAccount) remoteTabsPanel.remotePanelDelegate?.remotePanelDidRequestToCreateAccount() } } override func updateConstraints() { if UIWindow.isLandscape && !(DeviceInfo.deviceModel().contains("iPad")) { instructionsLabel.snp.remakeConstraints { make in make.top.equalTo(titleLabel.snp.bottom) .offset(RemoteTabsErrorCell.UX.EmptyStateTopPaddingInBetweenItems) make.width.equalTo(RemoteTabsErrorCell.UX.EmptyStateInstructionsWidth) // Sets proper landscape layout for bigger phones: iPhone 6 and on. make.left.lessThanOrEqualTo(contentView.snp.left).offset(80).priority(100) // Sets proper landscape layout for smaller phones: iPhone 4 & 5. make.right.lessThanOrEqualTo(contentView.snp.centerX).offset(-30).priority(1000) } signInButton.snp.remakeConstraints { make in make.height.equalTo(UX.EmptyStateSignInButtonHeight) make.width.equalTo(UX.EmptyStateSignInButtonWidth) make.centerY.equalTo(emptyStateImageView) .offset(2 * RemoteTabsErrorCell.UX.EmptyStateTopPaddingInBetweenItems) // Sets proper landscape layout for bigger phones: iPhone 6 and on. make.right.greaterThanOrEqualTo(contentView.snp.right).offset(-70).priority(100) // Sets proper landscape layout for smaller phones: iPhone 4 & 5. make.left.greaterThanOrEqualTo(contentView.snp.centerX).offset(10).priority(1000) } } else { instructionsLabel.snp.remakeConstraints { make in make.top.equalTo(titleLabel.snp.bottom) .offset(RemoteTabsErrorCell.UX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(contentView) make.width.equalTo(RemoteTabsErrorCell.UX.EmptyStateInstructionsWidth) } signInButton.snp.remakeConstraints { make in make.centerX.equalTo(contentView) make.top.equalTo(instructionsLabel.snp.bottom) .offset(RemoteTabsErrorCell.UX.EmptyStateTopPaddingInBetweenItems) make.height.equalTo(UX.EmptyStateSignInButtonHeight) make.width.equalTo(UX.EmptyStateSignInButtonWidth) } } super.updateConstraints() } } // MARK: - RemoteTabsTableViewController class RemoteTabsTableViewController: UITableViewController, Themeable { struct UX { static let RowHeight = SiteTableViewControllerUX.RowHeight } weak var remoteTabsPanel: RemoteTabsPanel? var profile: Profile! var themeManager: ThemeManager var themeObserver: NSObjectProtocol? var notificationCenter: NotificationProtocol var tableViewDelegate: RemoteTabsPanelDataSource? { didSet { tableView.dataSource = tableViewDelegate tableView.delegate = tableViewDelegate } } fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(longPress)) }() init(themeManager: ThemeManager = AppContainer.shared.resolve(), notificationCenter: NotificationProtocol = NotificationCenter.default) { self.themeManager = themeManager self.notificationCenter = notificationCenter super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.addGestureRecognizer(longPressRecognizer) tableView.register(SiteTableViewHeader.self, forHeaderFooterViewReuseIdentifier: SiteTableViewHeader.cellIdentifier) tableView.register(TwoLineImageOverlayCell.self, forCellReuseIdentifier: TwoLineImageOverlayCell.cellIdentifier) tableView.rowHeight = UX.RowHeight tableView.separatorInset = .zero tableView.tableFooterView = UIView() // prevent extra empty rows at end tableView.delegate = nil tableView.dataSource = nil tableView.accessibilityIdentifier = AccessibilityIdentifiers.TabTray.syncedTabs listenForThemeChange() applyTheme() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) (navigationController as? ThemedNavigationController)?.applyTheme() // Add a refresh control if the user is logged in and the control was not added before. If the user is not // logged in, remove any existing control. if profile.hasSyncableAccount() && refreshControl == nil { addRefreshControl() } refreshTabs(updateCache: true) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if refreshControl != nil { removeRefreshControl() } } func applyTheme() { tableView.separatorColor = themeManager.currentTheme.colors.layerLightGrey30 if let delegate = tableViewDelegate as? RemoteTabsPanelErrorDataSource { delegate.applyTheme(theme: themeManager.currentTheme) } } // MARK: - Refreshing TableView func addRefreshControl() { let control = UIRefreshControl() control.addTarget(self, action: #selector(onRefreshPulled), for: .valueChanged) refreshControl = control tableView.refreshControl = control } func removeRefreshControl() { tableView.refreshControl = nil refreshControl = nil } @objc func onRefreshPulled() { refreshControl?.beginRefreshing() refreshTabs(updateCache: true) } func endRefreshing() { // Always end refreshing, even if we failed! refreshControl?.endRefreshing() // Remove the refresh control if the user has logged out in the meantime if !profile.hasSyncableAccount() { removeRefreshControl() } } func updateDelegateClientAndTabData(_ clientAndTabs: [ClientAndTabs]) { guard let remoteTabsPanel = remoteTabsPanel else { return } if clientAndTabs.isEmpty { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(remoteTabsPanel: remoteTabsPanel, error: .noClients, theme: themeManager.currentTheme) } else { let nonEmptyClientAndTabs = clientAndTabs.filter { !$0.tabs.isEmpty } if nonEmptyClientAndTabs.isEmpty { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(remoteTabsPanel: remoteTabsPanel, error: .noTabs, theme: themeManager.currentTheme) } else { let tabsPanelDataSource = RemoteTabsPanelClientAndTabsDataSource(remoteTabPanel: remoteTabsPanel, clientAndTabs: nonEmptyClientAndTabs, profile: profile, theme: themeManager.currentTheme) tabsPanelDataSource.collapsibleSectionDelegate = self self.tableViewDelegate = tabsPanelDataSource } } self.tableView.reloadData() } func refreshTabs(updateCache: Bool = false, completion: (() -> Void)? = nil) { guard let remoteTabsPanel = remoteTabsPanel else { return } assert(Thread.isMainThread) // Short circuit if the user is not logged in guard profile.hasSyncableAccount() else { self.endRefreshing() self.tableViewDelegate = RemoteTabsPanelErrorDataSource(remoteTabsPanel: remoteTabsPanel, error: .notLoggedIn, theme: themeManager.currentTheme) return } // Get cached tabs. self.profile.getCachedClientsAndTabs().uponQueue(.main) { result in guard let clientAndTabs = result.successValue else { self.endRefreshing() self.tableViewDelegate = RemoteTabsPanelErrorDataSource(remoteTabsPanel: remoteTabsPanel, error: .failedToSync, theme: self.themeManager.currentTheme) return } // Update UI with cached data. self.updateDelegateClientAndTabData(clientAndTabs) if updateCache { // Fetch updated tabs. self.profile.getClientsAndTabs().uponQueue(.main) { result in if let clientAndTabs = result.successValue { // Update UI with updated tabs. self.updateDelegateClientAndTabData(clientAndTabs) } self.endRefreshing() completion?() } } else { self.endRefreshing() completion?() } } } @objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == .began else { return } let touchPoint = longPressGestureRecognizer.location(in: tableView) guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return } presentContextMenu(for: indexPath) } } extension RemoteTabsTableViewController: CollapsibleTableViewSection { func hideTableViewSection(_ section: Int) { guard let dataSource = tableViewDelegate as? RemoteTabsPanelClientAndTabsDataSource else { return } if dataSource.hiddenSections.contains(section) { dataSource.hiddenSections.remove(section) } else { dataSource.hiddenSections.insert(section) } tableView.reloadData() } } // MARK: LibraryPanelContextMenu extension RemoteTabsTableViewController: LibraryPanelContextMenu { func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) { guard let contextMenu = completionHandler() else { return } self.present(contextMenu, animated: true, completion: nil) } func getSiteDetails(for indexPath: IndexPath) -> Site? { guard let tab = (tableViewDelegate as? RemoteTabsPanelClientAndTabsDataSource)?.tabAtIndexPath(indexPath) else { return nil } return Site(url: String(describing: tab.URL), title: tab.title) } func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonRowActions]? { return getRemoteTabContexMenuActions(for: site, remotePanelDelegate: remoteTabsPanel?.remotePanelDelegate) } }
mpl-2.0
d9a1b7e90fcbf463bc2e0e5a5e12205c
39.006527
120
0.655441
5.559688
false
false
false
false
Constructor-io/constructorio-client-swift
UserApplication/Screens/Search/ViewModel/SearchResultViewModel.swift
1
872
// // SearchResultViewModel.swift // UserApplication // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import Foundation import ConstructorAutocomplete import UIKit public struct SearchResultViewModel{ public let title: String public let price: Double public let priceString: String public let imageURL: String public let description: String public let fallbackImage: () -> UIImage public init(searchResult: CIOResult){ self.title = searchResult.value self.price = searchResult.data.metadata["price"] as? Double ?? 0.00 self.imageURL = searchResult.data.imageURL ?? "" self.fallbackImage = { return UIImage(named: "icon_logo")! } self.description = searchResult.data.metadata["description"] as? String ?? "" self.priceString = "$\(self.price)" } }
mit
b50da707e6d85bddf6941cb1b4454935
27.096774
85
0.685419
4.39899
false
false
false
false
juheon0615/HandongSwift2
HandongAppSwift/SWXMLHash.swift
3
10756
// // SWXMLHash.swift // // Copyright (c) 2014 David Mohundro // // 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 /// Simple XML parser. public class SWXMLHash { /** Method to parse XML passed in as a string. :param: xml The XML to be parsed :returns: An XMLIndexer instance that is used to look up elements in the XML */ class public func parse(xml: String) -> XMLIndexer { return parse((xml as NSString).dataUsingEncoding(NSUTF8StringEncoding)!) } /** Method to parse XML passed in as an NSData instance. :param: xml The XML to be parsed :returns: An XMLIndexer instance that is used to look up elements in the XML */ class public func parse(data: NSData) -> XMLIndexer { var parser = XMLParser() return parser.parse(data) } } /// The implementation of NSXMLParserDelegate and where the parsing actually happens. class XMLParser : NSObject, NSXMLParserDelegate { var parsingElement: String = "" override init() { currentNode = root super.init() } var lastResults: String = "" var root = XMLElement(name: "root") var currentNode: XMLElement var parentStack = [XMLElement]() func parse(data: NSData) -> XMLIndexer { // clear any prior runs of parse... expected that this won't be necessary, but you never know parentStack.removeAll(keepCapacity: false) root = XMLElement(name: "root") parentStack.append(root) let parser = NSXMLParser(data: data) parser.delegate = self parser.parse() return XMLIndexer(root) } func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName: String?, attributes attributeDict: [NSObject : AnyObject]) { self.parsingElement = elementName currentNode = parentStack[parentStack.count - 1].addElement(elementName, withAttributes: attributeDict) parentStack.append(currentNode) lastResults = "" } func parser(parser: NSXMLParser!, foundCharacters string: String!) { if parsingElement == currentNode.name { lastResults += string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } } func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) { parsingElement = elementName if !lastResults.isEmpty { currentNode.text = lastResults } parentStack.removeLast() } } /// Returned from SWXMLHash, allows easy element lookup into XML data. public enum XMLIndexer : SequenceType { case Element(XMLElement) case List([XMLElement]) case Error(NSError) /// The underlying XMLElement at the currently indexed level of XML. public var element: XMLElement? { get { switch self { case .Element(let elem): return elem default: return nil } } } /// All elements at the currently indexed level public var all: [XMLIndexer] { get { switch self { case .List(let list): var xmlList = [XMLIndexer]() for elem in list { xmlList.append(XMLIndexer(elem)) } return xmlList case .Element(let elem): return [XMLIndexer(elem)] default: return [] } } } /// All child elements from the currently indexed level public var children: [XMLIndexer] { get { var list = [XMLIndexer]() for elem in all.map({ $0.element! }) { for keyVal in elem.children.values { for elem in keyVal { list.append(XMLIndexer(elem)) } } } return list } } /** Allows for element lookup by matching attribute values. :param: attr should the name of the attribute to match on :param: _ should be the value of the attribute to match on :returns: instance of XMLIndexer */ public func withAttr(attr: String, _ value: String) -> XMLIndexer { let attrUserInfo = [NSLocalizedDescriptionKey: "XML Attribute Error: Missing attribute [\"\(attr)\"]"] let valueUserInfo = [NSLocalizedDescriptionKey: "XML Attribute Error: Missing attribute [\"\(attr)\"] with value [\"\(value)\"]"] switch self { case .List(let list): if let elem = list.filter({$0.attributes[attr] == value}).first { return .Element(elem) } return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: valueUserInfo)) case .Element(let elem): if let attr = elem.attributes[attr] { if attr == value { return .Element(elem) } return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: valueUserInfo)) } return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: attrUserInfo)) default: return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: attrUserInfo)) } } /** Initializes the XMLIndexer :param: _ should be an instance of XMLElement, but supports other values for error handling :returns: instance of XMLIndexer */ public init(_ rawObject: AnyObject) { switch rawObject { case let value as XMLElement: self = .Element(value) default: self = .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: nil)) } } /** Find an XML element at the current level by element name :param: key The element name to index by :returns: instance of XMLIndexer to match the element (or elements) found by key */ public subscript(key: String) -> XMLIndexer { get { let userInfo = [NSLocalizedDescriptionKey: "XML Element Error: Incorrect key [\"\(key)\"]"] switch self { case .Element(let elem): if let match = elem.children[key] { if match.count == 1 { return .Element(match[0]) } else { return .List(match) } } return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo)) default: return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo)) } } } /** Find an XML element by index within a list of XML Elements at the current level :param: index The 0-based index to index by :returns: instance of XMLIndexer to match the element (or elements) found by key */ public subscript(index: Int) -> XMLIndexer { get { let userInfo = [NSLocalizedDescriptionKey: "XML Element Error: Incorrect index [\"\(index)\"]"] switch self { case .List(let list): if index <= list.count { return .Element(list[index]) } return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo)) case .Element(let elem): if index == 0 { return .Element(elem) } else { return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo)) } default: return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo)) } } } typealias GeneratorType = XMLIndexer public func generate() -> IndexingGenerator<[XMLIndexer]> { return all.generate() } } /// XMLIndexer extensions extension XMLIndexer: BooleanType { /// True if a valid XMLIndexer, false if an error type public var boolValue: Bool { get { switch self { case .Error: return false default: return true } } } } /// Models an XML element, including name, text and attributes public class XMLElement { /// The name of the element public let name: String /// The inner text of the element, if it exists public var text: String? /// The attributes of the element public var attributes = [String:String]() var children = [String:[XMLElement]]() /** Initialize an XMLElement instance :param: name The name of the element to be initialized :returns: a new instance of XMLElement */ init(name: String) { self.name = name } /** Adds a new XMLElement underneath this instance of XMLElement :param: name The name of the new element to be added :param: withAttributes The attributes dictionary for the element being added :returns: The XMLElement that has now been added */ func addElement(name: String, withAttributes attributes: NSDictionary) -> XMLElement { let element = XMLElement(name: name) if var group = children[name] { group.append(element) children[name] = group } else { children[name] = [element] } for (keyAny,valueAny) in attributes { let key = keyAny as! String let value = valueAny as! String element.attributes[key] = value } return element } }
mit
26ae5a0d616181a86afda54660b9c709
31.39759
172
0.596876
4.991183
false
false
false
false
exponent/exponent
packages/expo-dev-menu/ios/DevMenuViewController.swift
2
3539
// Copyright 2015-present 650 Industries. All rights reserved. import UIKit class DevMenuViewController: UIViewController { static let JavaScriptDidLoadNotification = Notification.Name("RCTJavaScriptDidLoadNotification") static let ContentDidAppearNotification = Notification.Name("RCTContentDidAppearNotification") private let manager: DevMenuManager private var reactRootView: DevMenuRootView? private var hasCalledJSLoadedNotification: Bool = false init(manager: DevMenuManager) { self.manager = manager super.init(nibName: nil, bundle: nil) edgesForExtendedLayout = UIRectEdge.init(rawValue: 0) extendedLayoutIncludesOpaqueBars = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateProps() { reactRootView?.appProperties = initialProps() } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() maybeRebuildRootView() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() reactRootView?.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) forceRootViewToRenderHack() reactRootView?.becomeFirstResponder() } override var shouldAutorotate: Bool { get { return true } } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { get { return UIInterfaceOrientationMask.portrait } } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { get { return UIInterfaceOrientation.portrait } } @available(iOS 12.0, *) override var overrideUserInterfaceStyle: UIUserInterfaceStyle { get { return manager.userInterfaceStyle } set {} } // MARK: private private func initialProps() -> [String: Any] { return [ "enableDevelopmentTools": true, "showOnboardingView": manager.shouldShowOnboarding(), "devMenuItems": manager.serializedDevMenuItems(), "devMenuScreens": manager.serializedDevMenuScreens(), "appInfo": manager.session?.appInfo ?? [:], "uuid": UUID.init().uuidString, "openScreen": manager.session?.openScreen ?? NSNull() ] } // RCTRootView assumes it is created on a loading bridge. // in our case, the bridge has usually already loaded. so we need to prod the view. private func forceRootViewToRenderHack() { if !hasCalledJSLoadedNotification, let bridge = manager.appInstance.bridge { let notification = Notification(name: DevMenuViewController.JavaScriptDidLoadNotification, object: nil, userInfo: ["bridge": bridge]) reactRootView?.javaScriptDidLoad(notification) hasCalledJSLoadedNotification = true } } private func maybeRebuildRootView() { guard let bridge = manager.appInstance.bridge else { return } if reactRootView?.bridge != bridge { if reactRootView != nil { reactRootView?.removeFromSuperview() reactRootView = nil } hasCalledJSLoadedNotification = false reactRootView = DevMenuRootView(bridge: bridge, moduleName: "main", initialProperties: initialProps()) reactRootView?.frame = view.bounds reactRootView?.backgroundColor = UIColor.clear if isViewLoaded, let reactRootView = reactRootView { view.addSubview(reactRootView) view.setNeedsLayout() } } else { updateProps() } } }
bsd-3-clause
d4e28e098e611904863bb3bd2afba9ee
28.491667
139
0.713478
4.922114
false
false
false
false
dfed/Relativity
Sources/Relativity/ErrorHandler.swift
1
1707
// // ErrorHandler.swift // Relativity // // Created by Dan Federman on 3/29/17. // Copyright © 2017 Dan Federman. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // //    http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation public final class ErrorHandler { // MARK: Public Static Properties public static var customAssertBody: ((_ condition: Bool, _ message: String, _ file: StaticString, _ line: UInt) -> Void)? = nil public static let defaultAssertBody: (_ condition: Bool, _ message: String, _ file: StaticString, _ line: UInt) -> Void = { condition, message, file, line in guard !condition else { return } Swift.assertionFailure(message, file: file, line: line) } // MARK: Public Static Methods public static func assert(_ condition: Bool, _ message: String, file: StaticString = #file, line: UInt = #line) -> Void { (ErrorHandler.customAssertBody ?? ErrorHandler.defaultAssertBody)(condition, message, file, line) } public static func assertionFailure(_ message: String, file: StaticString = #file, line: UInt = #line) -> Void { assert(false, message, file: file, line: line) } }
apache-2.0
7d8a17c83a720439f210a3ba63ecd882
34.458333
161
0.666863
4.131068
false
false
false
false
devinross/curry-fire
Examples/Examples/DimeViewController.swift
1
2041
// // DimeViewController.swift // Created by Devin Ross on 9/12/16. // /* curryfire || https://github.com/devinross/curry-fire 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 curryfire class DimeViewController: UIViewController { override func loadView() { super.loadView() self.view.backgroundColor = UIColor.white let cardView = UIView(frame: CGRectCenteredInRect(self.view.bounds, 100, 100), backgroundColor: UIColor.random(), cornerRadius: 10) cardView.autoresizingMask = [.flexibleTopMargin,.flexibleBottomMargin,.flexibleRightMargin,.flexibleLeftMargin] cardView.centerX = self.view.width + 100 self.view.addSubview(cardView) self.view.addTapGesture { (sender) in let start = CGFloat(self.view.width + 100.0), end = CGFloat(-100.0) cardView.centerX = start cardView.turnOnADime(self.view.width/2, duration: 1, delay: 0, completion: { (finished) in cardView.turnOnADime(end, duration: 1, delay: 0, completion: { (finished) in }) }) } } }
mit
464ac529178553988f3d21ddf8f65ff3
29.462687
133
0.748163
4.098394
false
false
false
false
TMTBO/TTARefresher
TTARefresher/Classes/Base/TTARefresherAutoFooter.swift
1
3900
// // TTARefresherAutoFooter.swift // Pods // // Created by TobyoTenma on 11/05/2017. // // import UIKit open class TTARefresherAutoFooter: TTARefresherFooter { public var isAutoRefresh = true /// The percent when the footer appear will get refresh, default is 1.0 public var triggerAutoRefreshPercent: CGFloat = 1.0 open override var state: TTARefresherState { didSet { if state == oldValue { return } if state == .refreshing { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { [weak self] in guard let `self` = self else { return } self.executeRefreshingHandler() }) } else if state == .noMoreData || state == .idle { if oldValue == .refreshing { endRefreshingCompletionHandler?() } } } } open override var isHidden: Bool { didSet { if !oldValue && isHidden { state = .idle scrollView?.contentInset.bottom -= bounds.height } else if oldValue && !isHidden { scrollView?.contentInset.bottom += bounds.height guard let scrollView = scrollView else { return } frame.origin.y = scrollView.contentSize.height } } } override open func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) guard let scrollView = scrollView else { return } if let _ = newSuperview { if isHidden == false { scrollView.contentInset.bottom += bounds.height } frame.origin.y = scrollView.contentSize.height } else { guard isHidden == true else { return } scrollView.contentInset.bottom -= bounds.height } } } // MARK: - Override Methods extension TTARefresherAutoFooter { override open func scrollViewContentSizeDidChange(_ change: [NSKeyValueChangeKey : Any]?) { super.scrollViewContentSizeDidChange(change) guard let scrollView = scrollView else { return } frame.origin.y = scrollView.contentSize.height } override open func scrollViewContentOffsetDidChange(_ change: [NSKeyValueChangeKey : Any]?) { super.scrollViewContentOffsetDidChange(change) guard let scrollView = scrollView else { return } if state != .idle || !isAutoRefresh || frame.origin.y == 0 { return } guard scrollView.contentInset.top + scrollView.contentSize.height > scrollView.bounds.height else { return } let offsetY = scrollView.contentSize.height - scrollView.bounds.height + bounds.height * triggerAutoRefreshPercent + scrollView.contentInset.bottom - bounds.height guard scrollView.contentOffset.y >= offsetY else { return } if let change = change, let old = change[.oldKey] as? CGPoint, let new = change[.newKey] as? CGPoint, new.y <= old.y { return } beginRefreshing() } override open func scrollViewPanStateDidChange(_ change: [NSKeyValueChangeKey : Any]?) { super.scrollViewPanStateDidChange(change) guard let scrollView = scrollView else { return } if state != .idle { return } if scrollView.panGestureRecognizer.state == .ended { if scrollView.contentInset.top + scrollView.contentSize.height <= scrollView.bounds.height { guard scrollView.contentOffset.y >= -scrollView.contentInset.top else { return } beginRefreshing() } else { guard scrollView.contentOffset.y >= scrollView.contentSize.height + scrollView.contentInset.bottom - scrollView.bounds.height else { return } beginRefreshing() } } } }
mit
d39e314fe685a94de530ddc783597310
38
171
0.608205
5.277402
false
false
false
false
640Labs/pubnub
Tests/iOS Tests-Swift/PNPresenceTests.swift
1
15165
// // PNPresenceTests.swift // PubNub Tests // // Created by Vadim Osovets on 8/19/15. // // import UIKit import XCTest class PNPresenceTests: PNBasicClientTestCase { override func isRecording() -> Bool { return false } let uniqueChannelName = "2EC925F0-B996-47A4-AF54-A605E1A9AEBA" let uniqueGroupName = "2EC925F0-B996-47A4-AF54-A605E1A9AEBA" func testHereNow() { let testExpectation = self.expectationWithDescription("network") self.client.hereNowWithCompletion { (result: PNPresenceGlobalHereNowResult!, status: PNErrorStatus!) -> Void in XCTAssertNil(status) XCTAssertEqual(result.operation, PNOperationType.HereNowGlobalOperation, "Wrong operation") XCTAssertNotNil(result.data) XCTAssertEqual(result.statusCode, 200) let expectedChannels: ([String: NSDictionary]) = [ "0_5098427633369088" : [ "occupancy" : 1, "uuids" : [[ "uuid" : "JejuFan--79001" ]] ], "0_5650661106515968" : [ "occupancy" : 1, "uuids" : [[ "uuid" : "JejuFan--79001" ]] ], "all_activity" : [ "occupancy" : 1, "uuids" : [[ "uuid" : "JejuFan--79001" ]] ] ] let resultChannels = result.data.channels as! ([String: NSDictionary]) XCTAssert(resultChannels == expectedChannels, "Result and expected channels are not equal.") testExpectation.fulfill() } waitForExpectationsWithTimeout(5, handler: { (error) -> Void in XCTAssertNil(error, "Encountered error with publish call") }) } func testHereNowWithVerbosityNowUUID() { let testExpectation = self.expectationWithDescription("network") self.client.hereNowWithVerbosity(PNHereNowVerbosityLevel.UUID, completion: { (result: PNPresenceGlobalHereNowResult!, status: PNErrorStatus!) -> Void in XCTAssertNil(status) XCTAssertEqual(result.operation, PNOperationType.HereNowGlobalOperation, "Wrong operation") XCTAssertNotNil(result.data) XCTAssertEqual(result.statusCode, 200); let expectedChannels: ([String: NSDictionary]) = [ "0_5098427633369088" : [ "occupancy" : 1, "uuids" : ["JejuFan--79001"] ], "0_5650661106515968" : [ "occupancy" : 1, "uuids" : [ "JejuFan--79001" ] ], "all_activity" : [ "occupancy" : 1, "uuids" : [ "JejuFan--79001" ] ]] let resultChannels = result.data.channels as! ([String: NSDictionary]) XCTAssert(resultChannels == expectedChannels, "Result and expected channels are not equal.") testExpectation.fulfill() }) waitForExpectationsWithTimeout(5, handler: { (error) -> Void in XCTAssertNil(error, "Encountered error with publish call") }) } func testHereNowWithVerbosityNowState() { let testExpectation = self.expectationWithDescription("network") self.client.hereNowWithVerbosity(PNHereNowVerbosityLevel.State, completion: { (result: PNPresenceGlobalHereNowResult!, status: PNErrorStatus!) -> Void in XCTAssertNil(status) XCTAssertEqual(result.operation, PNOperationType.HereNowGlobalOperation, "Wrong operation") XCTAssertNotNil(result.data) XCTAssertEqual(result.statusCode, 200); let expectedChannels: ([String: NSDictionary]) = [ "0_5098427633369088" : [ "uuids" : [ [ "uuid" : "JejuFan--79001" ] ], "occupancy" : 1 ], "0_5650661106515968" : [ "uuids" : [ [ "uuid" : "JejuFan--79001" ] ], "occupancy" : 1 ], "all_activity" : [ "uuids" : [ [ "uuid" : "JejuFan--79001" ] ], "occupancy" : 1 ] ] let resultChannels = result.data.channels as! ([String: NSDictionary]) XCTAssert(resultChannels == expectedChannels, "Result and expected channels are not equal.") testExpectation.fulfill() }) waitForExpectationsWithTimeout(5, handler: { (error) -> Void in XCTAssertNil(error, "Encountered error with publish call") }) } func testHereNowWithVerbosityNowOccupancy() { let testExpectation = self.expectationWithDescription("network") self.client.hereNowWithVerbosity(PNHereNowVerbosityLevel.Occupancy, completion: { (result: PNPresenceGlobalHereNowResult!, status: PNErrorStatus!) -> Void in XCTAssertNil(status) XCTAssertEqual(result.operation, PNOperationType.HereNowGlobalOperation, "Wrong operation") XCTAssertNotNil(result.data) XCTAssertEqual(result.statusCode, 200); let expectedChannels: ([String: NSDictionary]) = [ "0_5098427633369088" : [ "occupancy" : 1 ], "0_5650661106515968" : [ "occupancy" : 1 ], "all_activity" : [ "occupancy" : 1 ]] let resultChannels = result.data.channels as! ([String: NSDictionary]) XCTAssert(resultChannels == expectedChannels, "Result and expected channels are not equal.") testExpectation.fulfill() }) waitForExpectationsWithTimeout(5, handler: { (error) -> Void in XCTAssertNil(error, "Encountered error with publish call") }) } func testHereNowForChannel() { let testExpectation = self.expectationWithDescription("network") self.client.hereNowForChannel(uniqueChannelName, withCompletion: { (result: PNPresenceChannelHereNowResult!, status: PNErrorStatus!) -> Void in XCTAssertNil(status) XCTAssertEqual(result.operation, PNOperationType.HereNowForChannelOperation, "Wrong operation") XCTAssertNotNil(result.data) XCTAssertEqual(result.statusCode, 200); XCTAssertEqual(result.data.occupancy, 0, "Result and expected channels are not equal.") XCTAssert(result.data.uuids as! NSArray == [], "Result and expected channels are not equal.") testExpectation.fulfill() }) waitForExpectationsWithTimeout(5, handler: { (error) -> Void in XCTAssertNil(error, "Encountered error with publish call") }) } func testHereNowForChannelWithVerbosityOccupancy() { let testExpectation = self.expectationWithDescription("network") self.client.hereNowForChannel(uniqueChannelName, withVerbosity: PNHereNowVerbosityLevel.Occupancy) { (result: PNPresenceChannelHereNowResult!, status: PNErrorStatus!) -> Void in XCTAssertNil(status) XCTAssertEqual(result.operation, PNOperationType.HereNowForChannelOperation, "Wrong operation") XCTAssertNotNil(result.data) XCTAssertEqual(result.statusCode, 200); XCTAssertEqual(result.data.occupancy, 0, "Result and expected channels are not equal.") testExpectation.fulfill() } waitForExpectationsWithTimeout(5, handler: { (error) -> Void in XCTAssertNil(error, "Encountered error with publish call") }) } func testHereNowForChannelWithVerbosityState() { let testExpectation = self.expectationWithDescription("network") self.client.hereNowForChannel(uniqueChannelName, withVerbosity: PNHereNowVerbosityLevel.State) { (result: PNPresenceChannelHereNowResult!, status: PNErrorStatus!) -> Void in XCTAssertNil(status) XCTAssertEqual(result.operation, PNOperationType.HereNowForChannelOperation, "Wrong operation") XCTAssertNotNil(result.data) XCTAssertEqual(result.statusCode, 200); XCTAssertEqual(result.data.occupancy, 0, "Result and expected channels are not equal.") XCTAssert(result.data.uuids as! NSArray == [], "Result and expected channels are not equal.") testExpectation.fulfill() } waitForExpectationsWithTimeout(5, handler: { (error) -> Void in XCTAssertNil(error, "Encountered error with publish call") }) } func testHereNowForChannelWithVerbosityUUID() { let testExpectation = self.expectationWithDescription("network") self.client.hereNowForChannel(uniqueChannelName, withVerbosity: PNHereNowVerbosityLevel.UUID) { (result: PNPresenceChannelHereNowResult!, status: PNErrorStatus!) -> Void in XCTAssertNil(status) XCTAssertEqual(result.operation, PNOperationType.HereNowForChannelOperation, "Wrong operation") XCTAssertNotNil(result.data) XCTAssertEqual(result.statusCode, 200); XCTAssertEqual(result.data.occupancy, 0, "Result and expected channels are not equal.") XCTAssert(result.data.uuids as! NSArray == [], "Result and expected channels are not equal.") testExpectation.fulfill() } waitForExpectationsWithTimeout(5, handler: { (error) -> Void in XCTAssertNil(error, "Encountered error with publish call") }) } func testHereNowForChannelGroup() { let testExpectation = self.expectationWithDescription("network") self.client.hereNowForChannelGroup(uniqueGroupName, withCompletion: { (result: PNPresenceChannelGroupHereNowResult!, status: PNErrorStatus!) -> Void in XCTAssertNil(status) XCTAssertEqual(result.operation, PNOperationType.HereNowForChannelGroupOperation, "Wrong operation") XCTAssertNotNil(result.data) XCTAssertEqual(result.statusCode, 200); XCTAssert(result.data.channels as NSDictionary == [:], "Result and expected channels are not equal.") testExpectation.fulfill() }) waitForExpectationsWithTimeout(5, handler: { (error) -> Void in XCTAssertNil(error, "Encountered error with publish call") }) } func testHereNowForChannelGroupWithVerbosityOccupancy() { let testExpectation = self.expectationWithDescription("network") self.client.hereNowForChannelGroup(uniqueGroupName, withVerbosity: PNHereNowVerbosityLevel.Occupancy) { (result: PNPresenceChannelGroupHereNowResult!, status: PNErrorStatus!) -> Void in XCTAssertNil(status) XCTAssertEqual(result.operation, PNOperationType.HereNowForChannelGroupOperation, "Wrong operation") XCTAssertNotNil(result.data) XCTAssertEqual(result.statusCode, 200); XCTAssert(result.data.channels as NSDictionary == [:], "Result and expected channels are not equal.") testExpectation.fulfill() } waitForExpectationsWithTimeout(5, handler: { (error) -> Void in XCTAssertNil(error, "Encountered error with publish call") }) } func testHereNowForChannelGroupWithVerbosityState() { let testExpectation = self.expectationWithDescription("network") self.client.hereNowForChannelGroup(uniqueGroupName, withVerbosity: PNHereNowVerbosityLevel.State) { (result: PNPresenceChannelGroupHereNowResult!, status: PNErrorStatus!) -> Void in XCTAssertNil(status) XCTAssertEqual(result.operation, PNOperationType.HereNowForChannelGroupOperation, "Wrong operation") XCTAssertNotNil(result.data) XCTAssertEqual(result.statusCode, 200); XCTAssert(result.data.channels as NSDictionary == [:], "Result and expected channels are not equal.") testExpectation.fulfill() } waitForExpectationsWithTimeout(5, handler: { (error) -> Void in XCTAssertNil(error, "Encountered error with publish call") }) } func testHereNowForChannelGroupWithVerbosityUUID() { let testExpectation = self.expectationWithDescription("network") self.client.hereNowForChannelGroup(uniqueGroupName, withVerbosity: PNHereNowVerbosityLevel.UUID) { (result: PNPresenceChannelGroupHereNowResult!, status: PNErrorStatus!) -> Void in XCTAssertNil(status) XCTAssertEqual(result.operation, PNOperationType.HereNowForChannelGroupOperation, "Wrong operation") XCTAssertNotNil(result.data) XCTAssertEqual(result.statusCode, 200); XCTAssert(result.data.channels as NSDictionary == [:], "Result and expected channels are not equal.") testExpectation.fulfill() } waitForExpectationsWithTimeout(5, handler: { (error) -> Void in XCTAssertNil(error, "Encountered error with publish call") }) } func testWhereNowUDID() { let testExpectation = self.expectationWithDescription("network") let uuid = NSUUID().UUIDString self.client.whereNowUUID(uuid, withCompletion: { (result: PNPresenceWhereNowResult!, status: PNErrorStatus!) -> Void in XCTAssertNil(status) XCTAssertEqual(result.operation, PNOperationType.WhereNowOperation, "Wrong operation") XCTAssertNotNil(result.data) XCTAssertEqual(result.statusCode, 200); XCTAssert(result.data.channels as NSArray == [], "Result and expected channels are not equal.") testExpectation.fulfill() }) waitForExpectationsWithTimeout(5, handler: { (error) -> Void in XCTAssertNil(error, "Encountered error with publish call") }) } }
mit
a11bbf42e8adcd92b7a8acfdee323394
41.01108
193
0.582921
5.540738
false
true
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Flows/InitFlow/InitFlow.swift
1
2895
import Foundation final class InitFlow { let initFlowModel: InitFlowModel let maxRetry: Int = 3 var newCardId: String? var newAccountId: String? var currentRetry: Int = 1 private var status: PXFlowStatus = .ready private let finishInitCallback: ((PXCheckoutPreference, PXInitDTO) -> Void) private let errorInitCallback: ((InitFlowError) -> Void) init(flowProperties: InitFlowProperties, finishInitCallback: @escaping ((PXCheckoutPreference, PXInitDTO) -> Void), errorInitCallback: @escaping ((InitFlowError) -> Void)) { self.finishInitCallback = finishInitCallback self.errorInitCallback = errorInitCallback initFlowModel = InitFlowModel(flowProperties: flowProperties) PXTrackingStore.sharedInstance.cleanChoType() } func updateModel(paymentPlugin: PXSplitPaymentProcessor?, chargeRules: [PXPaymentTypeChargeRule]?) { initFlowModel.update(paymentPlugin: paymentPlugin, chargeRules: chargeRules) } deinit { #if DEBUG print("DEINIT FLOW - \(self)") #endif } } extension InitFlow: PXFlow { func start() { if status != .running { status = .running executeNextStep() } } func executeNextStep() { DispatchQueue.main.async { let nextStep = self.initFlowModel.nextStep() switch nextStep { case .SERVICE_GET_INIT: self.getInitSearch() case .FINISH: self.finishFlow() case .ERROR: self.cancelFlow() } } } func finishFlow() { status = .finished if let paymentMethodsSearch = initFlowModel.getPaymentMethodSearch() { setCheckoutTypeForTracking() // Return the preference we retrieved or the one the integrator created let preference = paymentMethodsSearch.preference ?? initFlowModel.properties.checkoutPreference finishInitCallback(preference, paymentMethodsSearch) } else { cancelFlow() } } func cancelFlow() { status = .finished errorInitCallback(initFlowModel.getError()) initFlowModel.resetError() } func exitCheckout() {} } // MARK: - Getters extension InitFlow { func setFlowRetry(step: InitFlowModel.Steps) { status = .ready initFlowModel.setPendingRetry(forStep: step) } func disposePendingRetry() { initFlowModel.removePendingRetry() } func getStatus() -> PXFlowStatus { return status } func restart() { if status != .running { status = .ready } } } // MARK: - Privates extension InitFlow { private func setCheckoutTypeForTracking() { PXTrackingStore.sharedInstance.setChoType(initFlowModel.properties.checkoutType) } }
mit
357e94c84f08175760e0f4b1a50cf0f1
27.106796
177
0.631434
4.580696
false
false
false
false
chuva-io/server-chuva
Sources/App/Models/Form.swift
1
1467
import FluentProvider final class Form: Model, JSONConvertible { let storage = Storage() let title: String let questions: [BaseQuestion] init(title: String, questions: [BaseQuestion]) { self.title = title self.questions = questions } convenience init(json: JSON) throws { let questionJson: [JSON] = try json.get("questions") self.init(title: try json.get("title"), questions: try questionJson.map { try Question.initialize(json: $0) }) } func makeJSON() throws -> JSON { var json = JSON() try json.set("id", id?.string) try json.set("title", title) try json.set("questions", questions.map { try $0.makeJSON() }) return json } init(row: Row) throws { title = try row.get("title") questions = try row.get("questions") } func makeRow() throws -> Row { var row = Row() try row.set("title", title) try row.set("questions", questions) return row } } extension Form: Timestampable { } extension Form: Preparation { static func prepare(_ database: Database) throws { try database.create(self) { user in user.id() user.string("title") user.custom("questions", type: "questions") } } static func revert(_ database: Database) throws { try database.delete(self) } }
mit
6552bc357652350271ba14aade82d3df
25.196429
88
0.565099
4.276968
false
false
false
false
TotemTraining/PracticaliOSAppSecurity
V3/Keymaster/Keymaster/AppDelegate.swift
1
5945
// // AppDelegate.swift // Keymaster // // Created by Chris Forant on 4/22/15. // Copyright (c) 2015 Totem. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { println(documentsDirectory) // Create app dirs NSFileManager.defaultManager().createDirectoryAtURL(documentsDirectory.URLByAppendingPathComponent("Entries", isDirectory: true), withIntermediateDirectories: true, attributes: nil, error: nil) return true } func applicationWillResignActive(application: UIApplication) { UIPasteboard.generalPasteboard().setValue("", forPasteboardType: UIPasteboardNameGeneral) } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.totem.Keymaster" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Keymaster", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Keymaster.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
d794bffa8160c1280dc3a9946b985da7
57.284314
290
0.713541
5.862919
false
false
false
false
zhixingxi/JJA_Swift
JJA_Swift/Pods/TimedSilver/Sources/UIKit/UIViewController+TSExtension.swift
1
3508
// // UIViewController+TSExtension.swift // TimedSilver // Source: https://github.com/hilen/TimedSilver // // Created by Hilen on 11/6/15. // Copyright © 2015 Hilen. All rights reserved. // import Foundation import UIKit public extension UIViewController { /** UIViewController init from a inb with same name of the class. - returns: UIViewController */ class func ts_initFromNib() -> UIViewController { let hasNib: Bool = Bundle.main.path(forResource: self.ts_className, ofType: "nib") != nil guard hasNib else { assert(!hasNib, "Invalid parameter") // here return UIViewController() } return self.init(nibName: self.ts_className, bundle: nil) } /** Back bar with go to previous action - parameter backImage: Your image. 20px * 20px is perfect */ func ts_leftBackToPrevious(_ backImage: UIImage) { self.ts_leftBackBarButton(backImage, action: {}) } /** Be sure of your viewController has a UINavigationController Left back bar. If your viewController is from push action, then handler will execute popViewControllerAnimated method. If your viewController is from present action, then handler will excute dismissViewControllerAnimated method. - parameter backImage: Your image. 20px * 20px is perfect - parameter action: Handler */ func ts_leftBackBarButton(_ backImage: UIImage, action: (Void) -> Void) { guard self.navigationController != nil else { assert(false, "Your target ViewController doesn't have a UINavigationController") return } let button: UIButton = UIButton(type: UIButtonType.custom) button.setImage(backImage, for: UIControlState()) button.frame = CGRect(x: 0, y: 0, width: 40, height: 30) button.imageView!.contentMode = .scaleAspectFit; button.contentHorizontalAlignment = .left button.ts_addEventHandler(forControlEvent: .touchUpInside, handler: {[weak self] in guard let strongSelf = self else { return } if let navigationController = strongSelf.navigationController { if navigationController.viewControllers.count > 1 { navigationController.popViewController(animated: true) } else if (strongSelf.presentingViewController != nil) { strongSelf.dismiss(animated: true, completion: nil) } } else { assert(false, "Your target ViewController doesn't have a UINavigationController") } }) let barButton = UIBarButtonItem(customView: button) let gapItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) gapItem.width = -7 //fix the space navigationItem.leftBarButtonItems = [gapItem, barButton] } /** Back to previous, pop or dismiss */ func ts_backToPrevious() { if let navigationController = self.navigationController { if navigationController.viewControllers.count > 1 { navigationController.popViewController(animated: true) } else if (self.presentingViewController != nil) { self.dismiss(animated: true, completion: nil) } } else { assert(false, "Your target ViewController doesn't have a UINavigationController") } } }
mit
e3a89c76c73db28d8f1d2c174c821cd8
36.308511
233
0.636441
5.104803
false
false
false
false
richardxyx/Forecast
Forecast/DetailWeatherViewController.swift
1
2311
// // DetailWeatherViewController.swift // Forecast // // Created by Richard Neitzke on 11/14/15. // Copyright © 2015 Richard Neitzke. All rights reserved. // import UIKit import BEMSimpleLineGraph class DetailWeatherViewController: UIViewController, BEMSimpleLineGraphDataSource { @IBOutlet weak var tempGraph: BEMSimpleLineGraphView! @IBAction func dismissPressed(sender: UIBarButtonItem) { dismissViewControllerAnimated(true, completion: nil) } var wCon:WeatherCondition? override func viewDidLoad() { setNeedsStatusBarAppearanceUpdate() //Makes Navigation Bar Transparent let bar:UINavigationBar! = self.navigationController?.navigationBar bar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) bar.shadowImage = UIImage() bar.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) bar.barStyle = .BlackTranslucent //Adds a GestureRecognizer for downward swipes that calls swipeDown() let swipeDownGestureRec = UISwipeGestureRecognizer(target: self, action: "swipeDown") swipeDownGestureRec.direction = .Down self.view.addGestureRecognizer(swipeDownGestureRec) } //Dismisses the ViewController func swipeDown() { dismissViewControllerAnimated(true, completion: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) //Sets title based on WeatherCondition let wConView = self.view as! WeatherConditionView wCon = wConView.weatherCondition self.title = "Weather on \(wCon!.fullDay)" tempGraph.colorBackgroundYaxis = UIColor.clearColor() } //Currently only showing 6 points because the graph looks too sloppy with more points func numberOfPointsInLineGraph(graph: BEMSimpleLineGraphView) -> Int { return 6 } //Puts the WeatherCondition data in the graph func lineGraph(graph: BEMSimpleLineGraphView, valueForPointAtIndex index: Int) -> CGFloat { if wCon!.temperatures[index*4] != Double.infinity {return CGFloat(wCon!.temperatures[index*4])} else { return CGFloat(wCon!.maxDegrees) } } }
mit
fe115b89ff2d50d41ecf4825dc5be772
32.478261
110
0.679654
5.15625
false
false
false
false
malcommac/SwiftDate
Sources/SwiftDate/TimePeriod/TimePeriod.swift
7
6778
// // SwiftDate // Parse, validate, manipulate, and display dates, time and timezones in Swift // // Created by Daniele Margutti // - Web: https://www.danielemargutti.com // - Twitter: https://twitter.com/danielemargutti // - Mail: [email protected] // // Copyright © 2019 Daniele Margutti. Licensed under MIT License. // import Foundation /// Time periods are represented by the TimePeriodProtocol protocol. /// Required variables and method impleementations are bound below. /// An inheritable implementation of the TimePeriodProtocol is available through the TimePeriod class. open class TimePeriod: TimePeriodProtocol { /// The start date for a TimePeriod representing the starting boundary of the time period public var start: DateInRegion? /// The end date for a TimePeriod representing the ending boundary of the time period public var end: DateInRegion? // MARK: - Initializers public init() { } /// Create a new time period with given date range. /// /// - Parameters: /// - start: start date /// - end: end date public init(start: DateInRegion?, end: DateInRegion?) { self.start = start self.end = end } /// Create a new time period with given start and a length specified in number of seconds. /// /// - Parameters: /// - start: start of the period /// - duration: duration of the period expressed in seconds public init(start: DateInRegion, duration: TimeInterval) { self.start = start self.end = DateInRegion(start.date.addingTimeInterval(duration), region: start.region) } /// Create a new time period which ends at given date and start date is back on time by given interval. /// /// - Parameters: /// - end: end date /// - duration: duration expressed in seconds (it will be subtracted from start date) public init(end: DateInRegion, duration: TimeInterval) { self.end = end self.start = end.addingTimeInterval(-duration) } /// Return a new instance of the TimePeriod that starts on the provided start date and is of the /// size provided. /// /// - Parameters: /// - start: start of the period /// - duration: length of the period (ie. `2.days` or `14.hours`...) public init(start: DateInRegion, duration: DateComponents) { self.start = start self.end = (start + duration) } /// Return a new instance of the TimePeriod that starts at end time minus given duration. /// /// - Parameters: /// - end: end date /// - duration: duration (it will be subtracted from end date in order to provide the start date) public init(end: DateInRegion, duration: DateComponents) { self.start = (end - duration) self.end = end } /// Returns a new instance of DTTimePeriod that represents the largest time period available. /// The start date is in the distant past and the end date is in the distant future. /// /// - Returns: a new time period public static func infinity() -> TimePeriod { return TimePeriod(start: DateInRegion.past(), end: DateInRegion.future()) } // MARK: - Shifted /// Shift the `TimePeriod` by a `TimeInterval` /// /// - Parameter timeInterval: The time interval to shift the period by /// - Returns: The new, shifted `TimePeriod` public func shifted(by timeInterval: TimeInterval) -> TimePeriod { let timePeriod = TimePeriod() timePeriod.start = start?.addingTimeInterval(timeInterval) timePeriod.end = end?.addingTimeInterval(timeInterval) return timePeriod } /// Shift the `TimePeriod` by the specified components value. /// ie. `let shifted = period.shifted(by: 3.days)` /// /// - Parameter components: components to shift /// - Returns: new period public func shifted(by components: DateComponents) -> TimePeriod { let timePeriod = TimePeriod() timePeriod.start = (hasStart ? (start! + components) : nil) timePeriod.end = (hasEnd ? (end! + components) : nil) return timePeriod } // MARK: - Lengthen / Shorten /// Lengthen the `TimePeriod` by a `TimeInterval` /// /// - Parameters: /// - timeInterval: The time interval to lengthen the period by /// - anchor: The anchor point from which to make the change /// - Returns: The new, lengthened `TimePeriod` public func lengthened(by timeInterval: TimeInterval, at anchor: TimePeriodAnchor) -> TimePeriod { let timePeriod = TimePeriod() switch anchor { case .beginning: timePeriod.start = start timePeriod.end = end?.addingTimeInterval(timeInterval) case .center: timePeriod.start = start?.addingTimeInterval(-timeInterval) timePeriod.end = end?.addingTimeInterval(timeInterval) case .end: timePeriod.start = start?.addingTimeInterval(-timeInterval) timePeriod.end = end } return timePeriod } /// Shorten the `TimePeriod` by a `TimeInterval` /// /// - Parameters: /// - timeInterval: The time interval to shorten the period by /// - anchor: The anchor point from which to make the change /// - Returns: The new, shortened `TimePeriod` public func shortened(by timeInterval: TimeInterval, at anchor: TimePeriodAnchor) -> TimePeriod { let timePeriod = TimePeriod() switch anchor { case .beginning: timePeriod.start = start timePeriod.end = end?.addingTimeInterval(-timeInterval) case .center: timePeriod.start = start?.addingTimeInterval(-timeInterval / 2) timePeriod.end = end?.addingTimeInterval(timeInterval / 2) case .end: timePeriod.start = start?.addingTimeInterval(timeInterval) timePeriod.end = end } return timePeriod } // MARK: - Operator Overloads /// Default anchor = beginning /// Operator overload for lengthening a `TimePeriod` by a `TimeInterval` public static func + (leftAddend: TimePeriod, rightAddend: TimeInterval) -> TimePeriod { return leftAddend.lengthened(by: rightAddend, at: .beginning) } /// Default anchor = beginning /// Operator overload for shortening a `TimePeriod` by a `TimeInterval` public static func - (minuend: TimePeriod, subtrahend: TimeInterval) -> TimePeriod { return minuend.shortened(by: subtrahend, at: .beginning) } /// Operator overload for checking if a `TimePeriod` is equal to a `TimePeriodProtocol` public static func == (left: TimePeriod, right: TimePeriodProtocol) -> Bool { return left.equals(right) } } public extension TimePeriod { /// The start date of the time period var startDate: Date? { return start?.date } /// The end date of the time period var endDate: Date? { return end?.date } /// Create a new time period with the given start date, end date and region (default is UTC) convenience init(startDate: Date, endDate: Date, region: Region = Region.UTC) { let start = DateInRegion(startDate, region: region) let end = DateInRegion(endDate, region: region) self.init(start: start, end: end) } }
mit
3f3f3666f5fc81254db1eb7d05d81a49
33.055276
104
0.705327
3.854949
false
false
false
false
the-hypermedia-project/Hyperdrive
Hyperdrive/HyperBlueprint.swift
1
17367
// // HyperBlueprint.swift // Hyperdrive // // Created by Kyle Fuller on 12/04/2015. // Copyright (c) 2015 Apiary. All rights reserved. // import Foundation import Representor import URITemplate import WebLinking import Result func absoluteURITemplate(baseURL:String, uriTemplate:String) -> String { switch (baseURL.hasSuffix("/"), uriTemplate.hasPrefix("/")) { case (true, true): return baseURL.substringToIndex(baseURL.endIndex.predecessor()) + uriTemplate case (true, false): fallthrough case (false, true): return baseURL + uriTemplate case (false, false): return baseURL + "/" + uriTemplate } } private typealias Element = [String: AnyObject] private func uriForAction(resource:Resource, action:Action) -> String { var uriTemplate = resource.uriTemplate // Empty action uriTemplate == no template if let uri = action.uriTemplate { if !uri.isEmpty { uriTemplate = uri } } return uriTemplate } private func decodeJSON(data:NSData) -> Result<AnyObject, NSError> { return Result(try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))) } private func decodeJSON<T>(data:NSData) -> Result<T, NSError> { return Result(try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))).flatMap { if let value = $0 as? T { return .Success(value) } let invaidJSONError = NSError(domain: Hyperdrive.errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Returned JSON object was not of expected type."]) return .Failure(invaidJSONError) } } extension Resource { var dataStructure:[String:AnyObject]? { return content.filter { element in (element["element"] as? String) == "dataStructure" }.first } func actionForMethod(method:String) -> Action? { return actions.filter { action in return action.method == method }.first } } public typealias HyperBlueprintResultSuccess = (Hyperdrive, Representor<HTTPTransition>) public typealias HyperBlueprintResult = Result<HyperBlueprintResultSuccess, NSError> /// A subclass of Hyperdrive which supports requests from an API Blueprint public class HyperBlueprint : Hyperdrive { let baseURL:NSURL let blueprint:Blueprint // MARK: Entering an API /// Enter an API from a blueprint hosted on Apiary using the given domain public class func enter(apiary apiary: String, baseURL:NSURL? = nil, completion: (HyperBlueprintResult -> Void)) { let url = "https://jsapi.apiary.io/apis/\(apiary).apib" self.enter(blueprintURL: url, baseURL: baseURL, completion: completion) } /// Enter an API from a blueprint URI public class func enter(blueprintURL blueprintURL: String, baseURL:NSURL? = nil, completion: (HyperBlueprintResult -> Void)) { if let URL = NSURL(string: blueprintURL) { let request = NSMutableURLRequest(URL: URL) request.setValue("text/vnd.apiblueprint+markdown; version=1A", forHTTPHeaderField: "Accept") let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) session.dataTaskWithRequest(request) { (body, response, error) in if let error = error { dispatch_async(dispatch_get_main_queue()) { completion(.Failure(error)) } } else if let body = body { self.enter(blueprint: body, baseURL: baseURL, completion: completion) } else { let error = NSError(domain: Hyperdrive.errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Response has no body."]) dispatch_async(dispatch_get_main_queue()) { completion(.Failure(error)) } } }.resume() } else { let error = NSError(domain: Hyperdrive.errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid URI for blueprint \(blueprintURL)"]) completion(.Failure(error)) } } class func enter(blueprint blueprint: NSData, baseURL:NSURL? = nil, completion: (HyperBlueprintResult -> Void)) { let parserURL = NSURL(string: "https://api.apiblueprint.org/parser")! let request = NSMutableURLRequest(URL: parserURL) request.HTTPMethod = "POST" request.HTTPBody = blueprint request.setValue("text/vnd.apiblueprint+markdown; version=1A", forHTTPHeaderField: "Content-Type") request.setValue("application/vnd.apiblueprint.parseresult+json; version=2.2", forHTTPHeaderField: "Accept") let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) session.dataTaskWithRequest(request) { (body, response, error) in if let error = error { dispatch_async(dispatch_get_main_queue()) { completion(.Failure(error)) } } else if let body = body { switch decodeJSON(body) { case .Success(let parseResult): if let ast = parseResult["ast"] as? [String:AnyObject] { let blueprint = Blueprint(ast: ast) self.enter(blueprint, baseURL: baseURL, completion: completion) } else { dispatch_async(dispatch_get_main_queue()) { completion(.Failure(error ?? NSError(domain: Hyperdrive.errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Server returned invalid API Blueprint AST."]))) } } case .Failure(let error): dispatch_async(dispatch_get_main_queue()) { completion(.Failure(error ?? NSError(domain: Hyperdrive.errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Server returned invalid API Blueprint AST."]))) } } } else { let error = NSError(domain: Hyperdrive.errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Response has no body."]) dispatch_async(dispatch_get_main_queue()) { completion(.Failure(error)) } } }.resume() } /// Enter an API with a blueprint private class func enter(blueprint:Blueprint, baseURL:NSURL? = nil, completion: (HyperBlueprintResult -> Void)) { if let baseURL = baseURL { let hyperdrive = self.init(blueprint: blueprint, baseURL: baseURL) let representor = hyperdrive.rootRepresentor() dispatch_async(dispatch_get_main_queue()) { completion(.Success((hyperdrive, representor))) } } else { let host = (blueprint.metadata).filter { metadata in metadata.name == "HOST" }.first if let host = host { if let baseURL = NSURL(string: host.value) { let hyperdrive = self.init(blueprint: blueprint, baseURL: baseURL) let representor = hyperdrive.rootRepresentor() dispatch_async(dispatch_get_main_queue()) { completion(.Success((hyperdrive, representor))) } return } } let error = NSError(domain: Hyperdrive.errorDomain, code: 0, userInfo: [ NSLocalizedDescriptionKey: "Entering an API Blueprint hyperdrive without a base URL.", ]) dispatch_async(dispatch_get_main_queue()) { completion(.Failure(error)) } } } public required init(blueprint:Blueprint, baseURL:NSURL) { self.blueprint = blueprint self.baseURL = baseURL } private var resources:[Resource] { let resources = blueprint.resourceGroups.map { $0.resources } return resources.reduce([], combine: +) } /// Returns a representor representing all available links public func rootRepresentor() -> Representor<HTTPTransition> { return Representor { builder in for resource in self.resources { let actions = resource.actions.filter { action in let hasAction = (action.relation != nil) && !action.relation!.isEmpty return hasAction && action.method == "GET" } for action in actions { let relativeURI = uriForAction(resource, action: action) let absoluteURI = absoluteURITemplate(self.baseURL.absoluteString, uriTemplate: relativeURI) let transition = HTTPTransition.from(resource: resource, action: action, URL: absoluteURI) builder.addTransition(action.relation!, transition) } } } } public override func constructRequest(uri: String, parameters: [String : AnyObject]?) -> RequestResult { return super.constructRequest(uri, parameters: parameters).map { request in request.setValue("application/json", forHTTPHeaderField: "Accept") return request } } public override func constructResponse(request: NSURLRequest, response: NSHTTPURLResponse, body: NSData?) -> Representor<HTTPTransition>? { if let resource = resourceForResponse(response) { return Representor { builder in var uriTemplate = resource.actionForMethod(request.HTTPMethod ?? "GET")?.uriTemplate if (uriTemplate == nil) || !uriTemplate!.isEmpty { uriTemplate = resource.uriTemplate } let template = URITemplate(template: absoluteURITemplate(self.baseURL.absoluteString, uriTemplate: uriTemplate!)) let parameters = template.extract(response.URL!.absoluteString) self.addResponse(resource, parameters: parameters, request: request, response: response, body: body, builder: builder) if response.URL != nil { var allowedMethods:[String]? = nil if let allow = response.allHeaderFields["Allow"] as? String { allowedMethods = allow.componentsSeparatedByString(",").map { $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } } self.addTransitions(resource, parameters: parameters, builder: builder, allowedMethods: allowedMethods) } for link in response.links { if let relation = link.relationType { builder.addTransition(relation, uri: link.uri) { builder in builder.method = "GET" if let type = link.type { builder.suggestedContentTypes = [type] } } } } if builder.transitions["self"] == nil { if let URL = response.URL?.absoluteString { builder.addTransition("self", uri: URL) { builder in builder.method = "GET" } } } } } return nil } public func resourceForResponse(response: NSHTTPURLResponse) -> Resource? { if let URL = response.URL?.absoluteString { return resources.filter { resource in let template = URITemplate(template: absoluteURITemplate(baseURL.absoluteString, uriTemplate: resource.uriTemplate)) let extract = template.extract(URL) return extract != nil }.first } return nil } public func actionForResource(resource:Resource, method:String) -> Action? { return resource.actions.filter { action in action.method == method }.first } func resource(named named:String) -> Resource? { return resources.filter { resource in resource.name == named }.first } // MARK: - func addResponse(resource:Resource, parameters:[String:AnyObject]?, request:NSURLRequest, response:NSHTTPURLResponse, body:NSData?, builder:RepresentorBuilder<HTTPTransition>) { if let body = body { if response.MIMEType == "application/json" { if let object = decodeJSON(body).value { addObjectResponse(resource, parameters: parameters, request: request, response: response, object: object, builder: builder) } } } } /// Returns any required URI Parameters for the given resource and attributes to determine the URI for the resource public func parameters(resource resource:Resource, attributes:[String:AnyObject]) -> [String:AnyObject]? { // By default, check if the attributes includes a URL we can use to extract the parameters if let url = attributes["url"] as? String { return resources.flatMap { URITemplate(template: $0.uriTemplate).extract(url) }.first } return nil } func addObjectResponse(resource:Resource, parameters:[String:AnyObject]?, request:NSURLRequest, response:NSHTTPURLResponse, object:AnyObject, builder:RepresentorBuilder<HTTPTransition>) { if let attributes = object as? [String:AnyObject] { addAttributes([:], resource:resource, request: request, response: response, attributes: attributes, builder: builder) } else if let objects = object as? [[String:AnyObject]] { // An array of other resources let resourceName = resource.dataStructure .flatMap(selectFirstContent) .flatMap(selectFirstContent) .flatMap { $0["element"] as? String } if let resourceName = resourceName, embeddedResource = self.resource(named: resourceName) { let relation = resource.actionForMethod(request.HTTPMethod ?? "GET")?.relation ?? "objects" for object in objects { builder.addRepresentor(relation) { builder in self.addObjectResponse(embeddedResource, parameters: parameters, request: request, response: response, object: object, builder: builder) } } } } } func addObjectResponseOfResource(relation:String, resource:Resource, request:NSURLRequest, response:NSHTTPURLResponse, object:AnyObject, builder:RepresentorBuilder<HTTPTransition>) { if let attributes = object as? [String:AnyObject] { builder.addRepresentor(relation) { builder in self.addAttributes([:], resource: resource, request: request, response: response, attributes: attributes, builder: builder) } } else if let objects = object as? [[String:AnyObject]] { for object in objects { addObjectResponseOfResource(relation, resource: resource, request: request, response: response, object: object, builder: builder) } } } func addAttributes(parameters:[String:AnyObject]?, resource:Resource, request:NSURLRequest, response:NSHTTPURLResponse, attributes:[String:AnyObject], builder:RepresentorBuilder<HTTPTransition>) { let action = actionForResource(resource, method: request.HTTPMethod!) // Find's the Resource structure for an attribute in the current resource response func resourceForAttribute(key: String) -> Resource? { // TODO: Rewrite this to use proper refract structures // Find the element value for the MSON object key return resource.dataStructure .flatMap(selectFirstContent) .flatMap(selectElementArrayContent) .flatMap(selectValueWithKey(key)) // finds the member's value for the member matching key .flatMap(selectFirstContent) .flatMap(selectElementValue) .flatMap { self.resource(named: $0) } } for (key, value) in attributes { if let resource = resourceForAttribute(key) { self.addObjectResponseOfResource(key, resource:resource, request: request, response: response, object: value, builder: builder) } else { builder.addAttribute(key, value: value) } } let params = (parameters ?? [:]) + (self.parameters(resource:resource, attributes:attributes) ?? [:]) addTransitions(resource, parameters:params, builder: builder) } func addTransitions(resource:Resource, parameters:[String:AnyObject]?, builder:RepresentorBuilder<HTTPTransition>, allowedMethods:[String]? = nil) { let resourceURI = absoluteURITemplate(self.baseURL.absoluteString, uriTemplate: URITemplate(template: resource.uriTemplate).expand(parameters ?? [:])) for action in resource.actions { var actionURI = resourceURI if action.uriTemplate != nil && !action.uriTemplate!.isEmpty { actionURI = absoluteURITemplate(self.baseURL.absoluteString, uriTemplate: URITemplate(template: action.uriTemplate!).expand(parameters ?? [:])) } if let relation = action.relation { let transition = HTTPTransition.from(resource:resource, action:action, URL:actionURI) if let allowedMethods = allowedMethods { if !allowedMethods.contains(transition.method) { continue } } builder.addTransition(relation, transition) } } } } // Merge two dictionaries together func +<K,V>(lhs:Dictionary<K,V>, rhs:Dictionary<K,V>) -> Dictionary<K,V> { var dictionary = [K:V]() for (key, value) in rhs { dictionary[key] = value } for (key, value) in lhs { dictionary[key] = value } return dictionary } // Refract Traversal private func selectContent(element: Element) -> AnyObject? { return element["content"] } private func selectElementArrayContent(element: Element) -> [Element]? { return selectContent(element) as? [Element] } private func selectFirstContent(element: Element) -> Element? { return selectElementArrayContent(element)?.first } /// Traverses a collection of member elements in search for the value for a key private func selectValueWithKey<T: Equatable>(key: T) -> [Element] -> Element? { return { element in return element.flatMap(selectContent) .filter { element in if let elementKey = element["key"] as? [String: AnyObject], keyContent = elementKey["content"] as? T { return keyContent == key } return false } .flatMap { $0["value"] as? Element } .first } } private func selectElementValue(element: Element) -> String? { return element["element"] as? String }
mit
32bfdb3340819a1c0af2d933a27af2de
38.029213
198
0.678643
4.535649
false
false
false
false
ljshj/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Dialogs List/Cells/AADialogSearchCell.swift
1
1694
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import UIKit public class AADialogSearchCell: AATableViewCell, AABindedSearchCell { public typealias BindData = ACSearchEntity public static func bindedCellHeight(item: BindData) -> CGFloat { return 76 } private let avatarView: AAAvatarView = AAAvatarView() private let titleView: UILabel = UILabel() public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier) titleView.font = UIFont.mediumSystemFontOfSize(19) titleView.textColor = ActorSDK.sharedActor().style.dialogTextColor contentView.addSubview(avatarView) contentView.addSubview(titleView) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func bind(item: ACSearchEntity, search: String?) { avatarView.bind(item.title, id: Int(item.peer.peerId), avatar: item.avatar) titleView.text = item.title } public override func prepareForReuse() { super.prepareForReuse() avatarView.unbind() } public override func layoutSubviews() { super.layoutSubviews() let width = self.contentView.frame.width let leftPadding = CGFloat(76) let padding = CGFloat(14) avatarView.frame = CGRectMake(padding, padding, 52, 52) titleView.frame = CGRectMake(leftPadding, 0, width - leftPadding - (padding + 50), contentView.bounds.size.height) } }
mit
7e6ddbbef506a097d3c4f5d8d8113254
30.37037
122
0.654073
4.895954
false
false
false
false
eduarenas80/MarvelClient
Source/MarvelClient.swift
2
4547
// // MarvelClient.swift // MarvelClient // // Copyright (c) 2016 Eduardo Arenas <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import Alamofire typealias MarvelAPIKeys = (privateKey: String, publicKey: String) public class MarvelClient { let keys: MarvelAPIKeys public init(privateKey: String, publicKey: String) { self.keys = (privateKey, publicKey) } public func requestCharacter(id: Int, completionHandler: Wrapper<Character> -> Void) { CharacterRequestBuilder(keys: self.keys).fetchResultById(id, completionHandler: completionHandler) } public func requestCharacter(characterSummary: CharacterSummary, completionHandler: Wrapper<Character> -> Void) { guard let entityId = characterSummary.id else { return } self.requestCharacter(entityId, completionHandler: completionHandler) } public func requestCharacters() -> CharacterRequestBuilder { return CharacterRequestBuilder(keys: self.keys) } public func requestComic(id: Int, completionHandler: Wrapper<Comic> -> Void) { ComicRequestBuilder(keys: self.keys).fetchResultById(id, completionHandler: completionHandler) } public func requestComic(comicSummary: ComicSummary, completionHandler: Wrapper<Comic> -> Void) { guard let entityId = comicSummary.id else { return } self.requestComic(entityId, completionHandler: completionHandler) } public func requestComics() -> ComicRequestBuilder { return ComicRequestBuilder(keys: self.keys) } public func requestCreator(id: Int, completionHandler: Wrapper<Creator> -> Void) { CreatorRequestBuilder(keys: self.keys).fetchResultById(id, completionHandler: completionHandler) } public func requestCreator(creatorSummary: CreatorSummary, completionHandler: Wrapper<Creator> -> Void) { guard let entityId = creatorSummary.id else { return } self.requestCreator(entityId, completionHandler: completionHandler) } public func requestCreators() -> CreatorRequestBuilder { return CreatorRequestBuilder(keys: self.keys) } public func requestEvent(id: Int, completionHandler: Wrapper<Event> -> Void) { EventRequestBuilder(keys: self.keys).fetchResultById(id, completionHandler: completionHandler) } public func requestEvent(eventSummary: EventSummary, completionHandler: Wrapper<Event> -> Void) { guard let entityId = eventSummary.id else { return } self.requestEvent(entityId, completionHandler: completionHandler) } public func requestEvents() -> EventRequestBuilder { return EventRequestBuilder(keys: self.keys) } public func requestSeries(id: Int, completionHandler: Wrapper<Series> -> Void) { SeriesRequestBuilder(keys: self.keys).fetchResultById(id, completionHandler: completionHandler) } public func requestSeries(seriesSummary: SeriesSummary, completionHandler: Wrapper<Series> -> Void) { guard let entityId = seriesSummary.id else { return } self.requestSeries(entityId, completionHandler: completionHandler) } public func requestSeries() -> SeriesRequestBuilder { return SeriesRequestBuilder(keys: self.keys) } public func requestStory(id: Int, completionHandler: Wrapper<Story> -> Void) { StoryRequestBuilder(keys: self.keys).fetchResultById(id, completionHandler: completionHandler) } public func requestStories() -> StoryRequestBuilder { return StoryRequestBuilder(keys: self.keys) } }
mit
43404d519d78b52b4dc54aeb82ce8e3b
36.578512
115
0.744667
4.620935
false
false
false
false
cliqz-oss/browser-ios
ReadingList/ReadingListUtils.swift
16
578
/* 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 public typealias ReadingListRecordId = Int64 public typealias ReadingListTimestamp = Int64 func ReadingListNow() -> ReadingListTimestamp { return ReadingListTimestamp(Date.timeIntervalSinceReferenceDate * 1000.0) } let ReadingListDefaultUnread: Bool = true let ReadingListDefaultFavorite: Bool = false let ReadingListDefaultArchived: Bool = false
mpl-2.0
ee43ea2dd764dc61f66f48cad9673f85
35.125
77
0.785467
4.515625
false
false
false
false
mominul/swiftup
Sources/SwiftupFramework/Utilities.swift
1
1011
/* swiftup The Swift toolchain installer Copyright (C) 2016-present swiftup Authors Authors: Muhammad Mominul Huque */ import Glibc import libNix import Spawn import Environment import StringPlus func unimplemented() { print("Not Implemented!") exit(1) } func getTempDir() -> String { return Env["TMPDIR"] ?? "/tmp" } @discardableResult func run(program: String, arguments: [String]) throws -> String { var output = "" do { _ = try Spawn(args: [program] + arguments) { output += $0 } } catch { throw SwiftupError.internalError(description: "\(error)") } return output } func moveItem(src: String, dest: String) throws { try run(program: "/bin/mv", arguments: ["\(src)", "\(dest)"]) } func getPlatformID() -> String { var version = "" _ = try? Spawn(args: ["/usr/bin/lsb_release", "-ds"]) { version = $0 } var regex = RegularExpression(pattern: "ubuntu[0-9]+\\.[0-9]+") return regex.getMatch(search: version.simplified().lowercased())! }
apache-2.0
3b0d7c080d8001005b04a7a97fb3a32b
17.722222
67
0.642928
3.486207
false
false
false
false
AZaps/Scribe-Swift
Scribe/Quest.swift
1
1926
// // Quest.swift // Scribe // // Created by Anthony Zaprzalka on 9/13/16. // Copyright © 2016 Anthony Zaprzalka. All rights reserved. // // Basic structure for a Quest(reminder) import Foundation import CoreData class Quest { /* Core Data Structure Quest forKey Values: title notes givenBy date */ // Quest Properties var title: String = "" var givenBy: String? var notes: String? var date: Date = Date() // Saves the newly created quest to CoreData func saveQuest(_ managedContext: NSManagedObjectContext, saveQuest: Quest) -> Bool { // Saves the quest to CoreData let entity = NSEntityDescription.entity(forEntityName: "Quest", in: managedContext) let quest = NSManagedObject(entity: entity!, insertInto: managedContext) quest.setValue(saveQuest.title, forKey: "title") quest.setValue(saveQuest.givenBy, forKey: "givenBy") quest.setValue(saveQuest.notes, forKey: "notes") quest.setValue(saveQuest.date, forKey: "date") if managedContext.hasChanges { do { try managedContext.save() } catch { let nserror = error as NSError print("ERROR: \(nserror), \(nserror.userInfo)") return false } return true } return false } // Edits an already created quest func editQuest() -> Bool { // Edits a specific part of the quest then saves to CoreData // Temp change later return false } func debugPrint(_ tmpQuest: Quest) { print("Title: \(tmpQuest.title)") print("Given By: \(tmpQuest.givenBy)") print("Date: \(tmpQuest.date)") print("Notes: \(tmpQuest.notes)") } }
mit
312256d8e477b56aed49c3dc15e6e257
25.013514
91
0.560519
4.706601
false
false
false
false
iOS-mamu/SS
P/Pods/PSOperations/PSOperations/LocationCondition.swift
1
5699
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file shows an example of implementing the OperationCondition protocol. */ #if !os(OSX) import CoreLocation /// A condition for verifying access to the user's location. @available(*, deprecated, message: "use Capability(Location...) instead") public struct LocationCondition: OperationCondition { /** Declare a new enum instead of using `CLAuthorizationStatus`, because that enum has more case values than are necessary for our purposes. */ public enum Usage { case whenInUse #if !os(tvOS) case always #endif } public static let name = "Location" static let locationServicesEnabledKey: NSString = "CLLocationServicesEnabled" static let authorizationStatusKey: NSString = "CLAuthorizationStatus" public static let isMutuallyExclusive = false let usage: Usage public init(usage: Usage) { self.usage = usage } public func dependencyForOperation(_ operation: Operation) -> Foundation.Operation? { return LocationPermissionOperation(usage: usage) } public func evaluateForOperation(_ operation: Operation, completion: @escaping (OperationConditionResult) -> Void) { let enabled = CLLocationManager.locationServicesEnabled() let actual = CLLocationManager.authorizationStatus() var error: NSError? // There are several factors to consider when evaluating this condition switch (enabled, usage, actual) { case (true, _, .authorizedAlways): // The service is enabled, and we have "Always" permission -> condition satisfied. break case (true, .whenInUse, .authorizedWhenInUse): /* The service is enabled, and we have and need "WhenInUse" permission -> condition satisfied. */ break default: /* Anything else is an error. Maybe location services are disabled, or maybe we need "Always" permission but only have "WhenInUse", or maybe access has been restricted or denied, or maybe access hasn't been request yet. The last case would happen if this condition were wrapped in a `SilentCondition`. */ error = NSError( code: .conditionFailed, userInfo: [ OperationConditionKey: type(of: self).name, type(of: self).locationServicesEnabledKey: enabled, type(of: self).authorizationStatusKey: Int(actual.rawValue) ] ) } if let error = error { completion(.failed(error)) } else { completion(.satisfied) } } } /** A private `Operation` that will request permission to access the user's location, if permission has not already been granted. */ class LocationPermissionOperation: Operation { let usage: LocationCondition.Usage var manager: CLLocationManager? init(usage: LocationCondition.Usage) { self.usage = usage super.init() /* This is an operation that potentially presents an alert so it should be mutually exclusive with anything else that presents an alert. */ addCondition(AlertPresentation()) } override func execute() { /* Not only do we need to handle the "Not Determined" case, but we also need to handle the "upgrade" (.WhenInUse -> .Always) case. */ #if os(tvOS) switch (CLLocationManager.authorizationStatus(), usage) { case (.notDetermined, _): DispatchQueue.main.async { self.requestPermission() } default: finish() } #else switch (CLLocationManager.authorizationStatus(), usage) { case (.notDetermined, _), (.authorizedWhenInUse, .always): DispatchQueue.main.async { self.requestPermission() } default: finish() } #endif } fileprivate func requestPermission() { manager = CLLocationManager() manager?.delegate = self let key: String #if os(tvOS) switch usage { case .whenInUse: key = "NSLocationWhenInUseUsageDescription" manager?.requestWhenInUseAuthorization() } #else switch usage { case .whenInUse: key = "NSLocationWhenInUseUsageDescription" manager?.requestWhenInUseAuthorization() case .always: key = "NSLocationAlwaysUsageDescription" manager?.requestAlwaysAuthorization() } #endif // This is helpful when developing the app. assert(Bundle.main.object(forInfoDictionaryKey: key) != nil, "Requesting location permission requires the \(key) key in your Info.plist") } } extension LocationPermissionOperation: CLLocationManagerDelegate { @objc func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if manager == self.manager && isExecuting && status != .notDetermined { finish() } } } #endif
mit
c97aa1f61dd820b7976c908407c48b4b
31.369318
145
0.585045
5.748739
false
false
false
false
Slowhand0309/OralWar
OralWar/System/ConvertUtil.swift
1
3663
// // ConvertUtil.swift // OralWar // // Created by MrSmall on 2015/10/08. // Copyright © 2015年 MrSmall. All rights reserved. // import Foundation // declare key for stage let STAGE_NO: String = "stage_no" let STAGE_NAME: String = "stage_name" let STAGE_DATA: String = "stage_data" // declare key for bacteria let ID: String = "id" let RATE: String = "rate" let CYCLE: String = "cycle" // declare key for stagelist let NAME: String = "name" let URI: String = "uri" let IMG_URI: String = "img_uri" class ConvertUtil { // convert json -> OralPieceMap class func toOralPieceMap(_ jsonData: NSDictionary?) -> OralPieceMap? { guard let data: NSDictionary = jsonData else { return nil } // get stage no guard let stageNo: Int = data[STAGE_NO] as? Int else { return nil } // get stage name guard let stageName: String = data[STAGE_NAME] as? String else { return nil } // get stage data guard let stageData: NSArray = data[STAGE_DATA] as? NSArray else { return nil } let stageMap: OralPieceMap = OralPieceMap() stageMap.setNo(stageNo) stageMap.setName(stageName) for h in 0 ..< HEIGHT { for w in 0 ..< WIDTH { let t: Int = stageData[h * HEIGHT + w] as! Int let value: UInt32 = UInt32(t) stageMap[w, h] = PieceStatus(_status: value) } } return stageMap } // convert json data -> Bacteria class func toBacteria(_ jsonData: NSDictionary?) -> Bacteria? { guard let data: NSDictionary = jsonData else { return nil } // get id guard let id: Int = data[ID] as? Int else { return nil } // get rate guard let rate: Float = data[RATE] as? Float else { return nil } // get cycle guard let cycle: Int = data[CYCLE] as? Int else { return nil } // TODO animType, expandType let bacteria: Bacteria = Bacteria() bacteria.setId(id) bacteria.setRate(rate) bacteria.setCycle(cycle) return bacteria } // convert json data -> Item class func toItem(_ jsonData: NSDictionary?) -> Item? { guard let data: NSDictionary = jsonData else { return nil } // get id guard let id: Int = data[ID] as? Int else { return nil } // get name guard let name: String = data[ID] as? String else { return nil } let item: Item = Item() item.setId(id) item.setName(name) return item } // get stage uri class func toStage(_ jsonData: NSDictionary?) -> Stage? { guard let data: NSDictionary = jsonData else { return nil } // get id guard let id: Int = data[ID] as? Int else { return nil } // get name guard let name: String = data[NAME] as! String! else { return nil } // get uri guard let uri: String = data[URI] as! String! else { return nil } // get image uri guard let img: String = data[IMG_URI] as! String! else { return nil } let stage: Stage = Stage() stage.setId(id) stage.setName(name) stage.setUri(uri) stage.setImageUri(img) return stage } }
mit
46f77b21e6bfdbe8dc7ee45500689712
25.142857
75
0.518579
4.116985
false
false
false
false
nathantannar4/NTComponents
NTComponents/Extensions/String.swift
1
6555
// // String.swift // NTComponents // // Copyright © 2017 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 2/12/17. // public extension String { func generateBarcodeImage() -> UIImage? { let data = self.data(using: String.Encoding.ascii) if let filter = CIFilter(name: "CICode128BarcodeGenerator") { filter.setDefaults() //Margin filter.setValue(7.00, forKey: "inputQuietSpace") filter.setValue(data, forKey: "inputMessage") //Scaling let transform = CGAffineTransform(scaleX: 3, y: 3) if let output = filter.outputImage?.transformed(by: transform) { let context:CIContext = CIContext.init(options: nil) let cgImage:CGImage = context.createCGImage(output, from: output.extent)! let rawImage:UIImage = UIImage.init(cgImage: cgImage) //Refinement code to allow conversion to NSData or share UIImage. Code here: //http://stackoverflow.com/questions/2240395/uiimage-created-from-cgimageref-fails-with-uiimagepngrepresentation let cgimage: CGImage = (rawImage.cgImage)! let cropZone = CGRect(x: 0, y: 0, width: Int(rawImage.size.width), height: Int(rawImage.size.height)) let cWidth: size_t = size_t(cropZone.size.width) let cHeight: size_t = size_t(cropZone.size.height) let bitsPerComponent: size_t = cgimage.bitsPerComponent //THE OPERATIONS ORDER COULD BE FLIPPED, ALTHOUGH, IT DOESN'T AFFECT THE RESULT let bytesPerRow = (cgimage.bytesPerRow) / (cgimage.width * cWidth) let context2: CGContext = CGContext(data: nil, width: cWidth, height: cHeight, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: cgimage.bitmapInfo.rawValue)! context2.draw(cgimage, in: cropZone) let result: CGImage = context2.makeImage()! let finalImage = UIImage(cgImage: result) return finalImage } } return nil } func generateQRCode() -> UIImage? { let data = self.data(using: String.Encoding.ascii) if let filter = CIFilter(name: "CIQRCodeGenerator") { filter.setValue(data, forKey: "inputMessage") let transform = CGAffineTransform(scaleX: 3, y: 3) if let output = filter.outputImage?.transformed(by: transform) { return UIImage(ciImage: output) } } return nil } static func random(ofLength length: Int) -> String { let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let len = UInt32(letters.length) var randomString = "" for _ in 0 ..< length { let rand = arc4random_uniform(len) var nextChar = letters.character(at: Int(rand)) randomString += NSString(characters: &nextChar, length: 1) as String } return randomString } var isValidEmail: Bool { get { let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat) return emailPredicate.evaluate(with: self) } } func parseAttributes() -> NSMutableAttributedString { var text = self let BOLD = "*" let ITALIC = "_" let attributedString = NSMutableAttributedString() var boldComponents = text.components(separatedBy: BOLD) while boldComponents.count > 1 { attributedString.append(boldComponents[0].parseAttributes()) attributedString.append(NSMutableAttributedString().bold(boldComponents[1])) text = String() if boldComponents.count > 2 { for index in 2...(boldComponents.count - 1) { text.append(boldComponents[index]) } } boldComponents = text.components(separatedBy: BOLD) } var italicComponents = text.components(separatedBy: ITALIC) while italicComponents.count > 1 && (boldComponents.count % 2 == 1) { attributedString.append(italicComponents[0].parseAttributes()) attributedString.append(NSMutableAttributedString().italic(italicComponents[1])) text = String() if italicComponents.count > 2 { for index in 2...(italicComponents.count - 1) { text.append(italicComponents[index]) } } italicComponents = text.components(separatedBy: ITALIC) } attributedString.append(NSMutableAttributedString(string: text)) return attributedString } func bold() -> NSMutableAttributedString { let boldText = NSMutableAttributedString(string: self) return boldText.bold(self) } func italic() -> NSMutableAttributedString { let italicText = NSMutableAttributedString(string: self) return italicText.italic(self) } }
mit
11b5c1d7137cce71c42ddcd4bee1372e
40.220126
236
0.608026
4.924117
false
false
false
false
sharplet/Regex
Tests/RegexTests/Assertions.swift
1
1544
// swiftlint:disable line_length import Regex import XCTest func XCTAssertMatches(_ regularExpression: Regex, _ stringMatch: String, _ file: StaticString = #file, line: UInt = #line) { XCTAssertTrue(regularExpression.matches(stringMatch), "expected <\(regularExpression)> to match <\(stringMatch)>", file: file, line: line) } func XCTAssertDoesNotMatch(_ regularExpression: Regex, _ stringMatch: String, _ file: StaticString = #file, line: UInt = #line) { XCTAssertFalse(regularExpression.matches(stringMatch), "expected <\(regularExpression)> not to match <\(stringMatch)>", file: file, line: line) } func XCTAssertCaptures(_ regularExpression: Regex, captures: String..., from string: String, _ file: StaticString = #file, line: UInt = #line) { for expected in captures { let match = regularExpression.firstMatch(in: string) XCTAssertNotNil(match, file: file, line: line) XCTAssertTrue(match!.captures.contains(where: { $0 == expected }), "expected <\(regularExpression)> to capture <\(captures)> from <\(string)> ", file: file, line: line) } } func XCTAssertDoesNotCapture(_ regularExpression: Regex, captures: String..., from string: String, _ file: StaticString = #file, line: UInt = #line) { for expected in captures { let match = regularExpression.firstMatch(in: string) XCTAssertNotNil(match, file: file, line: line) XCTAssertFalse(match!.captures.contains(where: { $0 == expected }), "expected <\(regularExpression)> to not capture <\(captures)> from <\(string)> ", file: file, line: line) } }
mit
5c2d54d66e6bc7b72eb19aa456f81d21
54.142857
177
0.716321
4.218579
false
false
false
false
WANGjieJacques/KissPaginate
Example/KissPaginate/WithPaginateViewController.swift
1
1656
// // ViewController.swift // KissPaginate // // Created by WANG Jie on 10/05/2016. // Copyright (c) 2016 WANG Jie. All rights reserved. // import UIKit import KissPaginate class WithPaginateViewController: PaginateViewController { @IBOutlet weak var noElementLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self refreshElements(sender: nil) } override var getElementsClosure: (_ page: Int, _ successHandler: @escaping GetElementsSuccessHandler, _ failureHandler: @escaping (Error) -> Void) -> Void { return getElementList } func getElementList(_ page: Int, successHandler: @escaping GetElementsSuccessHandler, failureHandler: (_ error: Error) -> Void) { let elements = (0...20).map { "page \(page), element index" + String($0) } delay(2) { successHandler(elements, true) } } override func displayNoElementIfNeeded(noElement: Bool) { noElementLabel.isHidden = !noElement } } extension WithPaginateViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return elements.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! let element = getElement(String.self, at: (indexPath as NSIndexPath).row) cell.textLabel?.text = element if elements.count == (indexPath as NSIndexPath).row + 1 { loadNextPage() } return cell } }
mit
9807548a91f196d2a8ca2dad1ac3eab0
30.846154
160
0.67029
4.536986
false
false
false
false
PGSSoft/ParallaxView
Sources/Views/ParallaxCollectionViewCell.swift
1
4710
// // ParallaxCollectionViewCell.swift // // Created by Łukasz Śliwiński on 20/04/16. // Copyright © 2016 Łukasz Śliwiński. All rights reserved. // import UIKit /// An object that provides default implementation of the parallax effect for the `UICollectionViewCell`. /// Most of the time you will subclass this class as you would with `UICollectionViewCell` to provide custom content. /// If you will override `init` method it is important to provide default setup for the unfocused state of the view /// e.g. `parallaxViewActions.setupUnfocusedState?(self)` open class ParallaxCollectionViewCell: UICollectionViewCell, ParallaxableView { // MARK: Properties open var parallaxEffectOptions = ParallaxEffectOptions() open var parallaxViewActions = ParallaxViewActions<ParallaxCollectionViewCell>() // MARK: Initialization public override init(frame: CGRect) { super.init(frame: frame) commonInit() parallaxViewActions.setupUnfocusedState?(self) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() parallaxViewActions.setupUnfocusedState?(self) } /// Override this method in your `ParallaxCollectionViewCell` subclass if you would like to provide custom /// setup for the `parallaxEffectOptions` and/or `parallaxViewActions` open func setupParallax() {} internal func commonInit() { layer.shadowOpacity = 0.0 layer.shadowColor = UIColor.black.cgColor layer.shadowOpacity = 0.35 layer.shouldRasterize = true if parallaxEffectOptions.glowContainerView == nil { parallaxEffectOptions.glowContainerView = contentView } if parallaxEffectOptions.parallaxSubviewsContainer == nil { parallaxEffectOptions.parallaxSubviewsContainer = contentView } parallaxViewActions.setupUnfocusedState = { [weak self] (view) in guard let _self = self else { return } view.transform = CGAffineTransform.identity view.layer.shadowOffset = CGSize(width: 0, height: _self.bounds.height*0.015) view.layer.shadowRadius = 5 } parallaxViewActions.setupFocusedState = { [weak self] (view) in guard let _self = self else { return } view.transform = CGAffineTransform(scaleX: 1.15, y: 1.15) view.layer.shadowOffset = CGSize(width: 0, height: _self.bounds.height*0.12) view.layer.shadowRadius = 15 } parallaxViewActions.beforeResignFocusAnimation = { $0.layer.zPosition = 0 } parallaxViewActions.beforeBecomeFocusedAnimation = { $0.layer.zPosition = 100 } setupParallax() } // MARK: UIView open override func layoutSubviews() { super.layoutSubviews() guard let glowEffectContainerView = parallaxEffectOptions.glowContainerView, let glowImageView = getGlowImageView() else { return } parallaxEffectOptions.glowPosition.layout(glowEffectContainerView, glowImageView) } // MARK: UIResponder // Generally, all responders which do custom touch handling should override all four of these methods. // If you want to customize animations for press events do not forget to call super. open override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) { parallaxViewActions.animatePressIn?(self, presses, event) super.pressesBegan(presses, with: event) } open override func pressesCancelled(_ presses: Set<UIPress>, with event: UIPressesEvent?) { parallaxViewActions.animatePressOut?(self, presses, event) super.pressesCancelled(presses, with: event) } open override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) { parallaxViewActions.animatePressOut?(self, presses, event) super.pressesEnded(presses, with: event) } open override func pressesChanged(_ presses: Set<UIPress>, with event: UIPressesEvent?) { super.pressesChanged(presses, with: event) } // MARK: UIFocusEnvironment open override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) { super.didUpdateFocus(in: context, with: coordinator) if self == context.nextFocusedView { // Add parallax effect to focused cell parallaxViewActions.becomeFocused?(self, context, coordinator) } else if self == context.previouslyFocusedView { // Remove parallax effect parallaxViewActions.resignFocus?(self, context, coordinator) } } }
mit
bf3b4b3110a0c3a6516f75e481f4e1da
35.457364
120
0.691261
4.838477
false
false
false
false
Allow2CEO/browser-ios
UITests/Global.swift
2
20363
/* 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 GCDWebServers import Storage import WebKit let LabelAddressAndSearch = "Address and Search" extension XCTestCase { func tester(file: String = __FILE__, _ line: Int = __LINE__) -> KIFUITestActor { return KIFUITestActor(inFile: file, atLine: line, delegate: self) } func system(file: String = __FILE__, _ line: Int = __LINE__) -> KIFSystemTestActor { return KIFSystemTestActor(inFile: file, atLine: line, delegate: self) } } extension KIFUITestActor { /// Looks for a view with the given accessibility hint. func tryFindingViewWithAccessibilityHint(hint: String) -> Bool { let element = UIApplication.sharedApplication().accessibilityElementMatchingBlock { element in return element.accessibilityHint == hint } return element != nil } func waitForViewWithAccessibilityHint(hint: String) -> UIView? { var view: UIView? = nil autoreleasepool { waitForAccessibilityElement(nil, view: &view, withElementMatchingPredicate: NSPredicate(format: "accessibilityHint = %@", hint), tappable: false) } return view } func viewExistsWithLabel(label: String) -> Bool { do { try self.tryFindingViewWithAccessibilityLabel(label) return true } catch { return false } } func viewExistsWithLabelPrefixedBy(prefix: String) -> Bool { let element = UIApplication.sharedApplication().accessibilityElementMatchingBlock { element in return element.accessibilityLabel?.hasPrefix(prefix) ?? false } return element != nil } /// Waits for and returns a view with the given accessibility value. func waitForViewWithAccessibilityValue(value: String) -> UIView { var element: UIAccessibilityElement! runBlock { _ in element = UIApplication.sharedApplication().accessibilityElementMatchingBlock { element in return element.accessibilityValue == value } return (element == nil) ? KIFTestStepResult.Wait : KIFTestStepResult.Success } return UIAccessibilityElement.viewContainingAccessibilityElement(element) } /// Wait for and returns a view with the given accessibility label as an /// attributed string. See the comment in ReadingListPanel.swift about /// using attributed strings as labels. (It lets us set the pitch) func waitForViewWithAttributedAccessibilityLabel(label: NSAttributedString) -> UIView { var element: UIAccessibilityElement! runBlock { _ in element = UIApplication.sharedApplication().accessibilityElementMatchingBlock { element in if let elementLabel = element.valueForKey("accessibilityLabel") as? NSAttributedString { return elementLabel.isEqualToAttributedString(label) } return false } return (element == nil) ? KIFTestStepResult.Wait : KIFTestStepResult.Success } return UIAccessibilityElement.viewContainingAccessibilityElement(element) } /// There appears to be a KIF bug where waitForViewWithAccessibilityLabel returns the parent /// UITableView instead of the UITableViewCell with the given label. /// As a workaround, retry until KIF gives us a cell. /// Open issue: https://github.com/kif-framework/KIF/issues/336 func waitForCellWithAccessibilityLabel(label: String) -> UITableViewCell { var cell: UITableViewCell! runBlock { _ in let view = self.waitForViewWithAccessibilityLabel(label) cell = view as? UITableViewCell return (cell == nil) ? KIFTestStepResult.Wait : KIFTestStepResult.Success } return cell } /** * Finding views by accessibility label doesn't currently work with WKWebView: * https://github.com/kif-framework/KIF/issues/460 * As a workaround, inject a KIFHelper class that iterates the document and finds * elements with the given textContent or title. */ func waitForWebViewElementWithAccessibilityLabel(text: String) { runBlock { error in if (self.hasWebViewElementWithAccessibilityLabel(text)) { return KIFTestStepResult.Success } return KIFTestStepResult.Wait } } /** * Sets the text for a WKWebView input element with the given name. */ func enterText(text: String, intoWebViewInputWithName inputName: String) { let webView = getWebViewWithKIFHelper() var stepResult = KIFTestStepResult.Wait let escaped = text.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") let success = webView.stringByEvaluatingJavaScriptFromString("KIFHelper.enterTextIntoInputWithName(\"\(escaped)\", \"\(inputName)\");") stepResult = (success == "true") ? KIFTestStepResult.Success : KIFTestStepResult.Failure runBlock { error in if stepResult == KIFTestStepResult.Failure { error.memory = NSError(domain: "KIFHelper", code: 0, userInfo: [NSLocalizedDescriptionKey: "Input element not found in webview: \(escaped)"]) } return stepResult } } /** * Clicks a WKWebView element with the given label. */ func tapWebViewElementWithAccessibilityLabel(text: String) { let webView = getWebViewWithKIFHelper() var stepResult = KIFTestStepResult.Wait let escaped = text.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") let success = webView.stringByEvaluatingJavaScriptFromString("KIFHelper.tapElementWithAccessibilityLabel(\"\(escaped)\")") stepResult = (success == "true") ? KIFTestStepResult.Success : KIFTestStepResult.Failure runBlock { error in if stepResult == KIFTestStepResult.Failure { error.memory = NSError(domain: "KIFHelper", code: 0, userInfo: [NSLocalizedDescriptionKey: "Accessibility label not found in webview: \(escaped)"]) } return stepResult } } /** * Determines whether an element in the page exists. */ func hasWebViewElementWithAccessibilityLabel(text: String) -> Bool { let webView = getWebViewWithKIFHelper() var stepResult = KIFTestStepResult.Wait var found = false let escaped = text.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") let success = webView.stringByEvaluatingJavaScriptFromString("KIFHelper.hasElementWithAccessibilityLabel(\"\(escaped)\")") stepResult = (success == "true") ? KIFTestStepResult.Success : KIFTestStepResult.Failure found = success == "true" runBlock { _ in return stepResult } return found } func hasWebViewTitleWithPrefix(text: String) -> Bool { let webView = getWebViewWithKIFHelper() var stepResult = KIFTestStepResult.Wait let title = webView.stringByEvaluatingJavaScriptFromString("document.title") stepResult = title?.startsWith(text) ?? false ? KIFTestStepResult.Success : KIFTestStepResult.Failure runBlock { _ in return stepResult } return stepResult == KIFTestStepResult.Success } private func getWebViewWithKIFHelper() -> UIWebView { let webView = waitForViewWithAccessibilityLabel("Web content") as! UIWebView // Wait for the web view to stop loading. runBlock { _ in return webView.loading ? KIFTestStepResult.Wait : KIFTestStepResult.Success } var stepResult = KIFTestStepResult.Wait let result = webView.stringByEvaluatingJavaScriptFromString("typeof KIFHelper") if result == "undefined" { let bundle = NSBundle(forClass: SessionRestoreTests.self) let path = bundle.pathForResource("KIFHelper", ofType: "js")! let source = try! NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) webView.stringByEvaluatingJavaScriptFromString(source as String) } stepResult = KIFTestStepResult.Success runBlock { _ in return stepResult } return webView } public func deleteCharacterFromFirstResponser() { enterTextIntoCurrentFirstResponder("\u{0008}") } } class BrowserUtils { /// Close all tabs to restore the browser to startup state. class func resetToAboutHome(tester: KIFUITestActor) { do { try tester.tryFindingTappableViewWithAccessibilityLabel("Cancel") tester.tapViewWithAccessibilityLabel("Cancel") } catch _ { } tester.tapViewWithAccessibilityLabel("Show Tabs") let tabsView = tester.waitForViewWithAccessibilityLabel("Tabs Tray").subviews.first as! UICollectionView // Clear all private tabs if we're running iOS 9 if #available(iOS 9, *) { // Switch to Private Mode if we're not in it already. do { try tester.tryFindingTappableViewWithAccessibilityLabel("Private Mode", value: "Off", traits: UIAccessibilityTraitButton) tester.tapViewWithAccessibilityLabel("Private Mode") } catch _ {} while tabsView.numberOfItemsInSection(0) > 0 { let cell = tabsView.cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0))! tester.swipeViewWithAccessibilityLabel(cell.accessibilityLabel, inDirection: KIFSwipeDirection.Left) tester.waitForAbsenceOfViewWithAccessibilityLabel(cell.accessibilityLabel) } tester.tapViewWithAccessibilityLabel("Private Mode") } while tabsView.numberOfItemsInSection(0) > 1 { let cell = tabsView.cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0))! tester.swipeViewWithAccessibilityLabel(cell.accessibilityLabel, inDirection: KIFSwipeDirection.Left) tester.waitForAbsenceOfViewWithAccessibilityLabel(cell.accessibilityLabel) } // When the last tab is closed, the tabs tray will automatically be closed // since a new about:home tab will be selected. if let cell = tabsView.cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) { tester.swipeViewWithAccessibilityLabel(cell.accessibilityLabel, inDirection: KIFSwipeDirection.Left) tester.waitForTappableViewWithAccessibilityLabel("Show Tabs") } } /// Injects a URL and title into the browser's history database. class func addHistoryEntry(title: String, url: NSURL) { let notificationCenter = NSNotificationCenter.defaultCenter() var info = [NSObject: AnyObject]() info["url"] = url info["title"] = title info["visitType"] = VisitType.Link.rawValue notificationCenter.postNotificationName("OnLocationChange", object: self, userInfo: info) } private class func clearHistoryItemAtIndex(index: NSIndexPath, tester: KIFUITestActor) { if let row = tester.waitForCellAtIndexPath(index, inTableViewWithAccessibilityIdentifier: "History List") { tester.swipeViewWithAccessibilityLabel(row.accessibilityLabel, value: row.accessibilityValue, inDirection: KIFSwipeDirection.Left) tester.tapViewWithAccessibilityLabel("Remove") } } class func clearHistoryItems(tester: KIFUITestActor, numberOfTests: Int = -1) { resetToAboutHome(tester) tester.tapViewWithAccessibilityLabel("History") let historyTable = tester.waitForViewWithAccessibilityIdentifier("History List") as! UITableView var index = 0 for _ in 0 ..< historyTable.numberOfSections { for _ in 0 ..< historyTable.numberOfRowsInSection(0) { clearHistoryItemAtIndex(NSIndexPath(forRow: 0, inSection: 0), tester: tester) if numberOfTests > -1 && ++index == numberOfTests { return } } } tester.tapViewWithAccessibilityLabel("Top sites") } class func ensureAutocompletionResult(tester: KIFUITestActor, textField: UITextField, prefix: String, completion: String) { // searches are async (and debounced), so we have to wait for the results to appear. tester.waitForViewWithAccessibilityValue(prefix + completion) var range = NSRange() var attribute: AnyObject? let textLength = textField.text!.characters.count attribute = textField.attributedText!.attribute(NSBackgroundColorAttributeName, atIndex: 0, effectiveRange: &range) if attribute != nil { // If the background attribute exists for the first character, the entire string is highlighted. XCTAssertEqual(prefix, "") XCTAssertEqual(completion, textField.text) return } let prefixLength = range.length attribute = textField.attributedText!.attribute(NSBackgroundColorAttributeName, atIndex: textLength - 1, effectiveRange: &range) if attribute == nil { // If the background attribute exists for the last character, the entire string is not highlighted. XCTAssertEqual(prefix, textField.text) XCTAssertEqual(completion, "") return } let completionStartIndex = textField.text!.startIndex.advancedBy(prefixLength) let actualPrefix = textField.text!.substringToIndex(completionStartIndex) let actualCompletion = textField.text!.substringFromIndex(completionStartIndex) XCTAssertEqual(prefix, actualPrefix, "Expected prefix matches actual prefix") XCTAssertEqual(completion, actualCompletion, "Expected completion matches actual completion") } } class SimplePageServer { class func getPageData(name: String, ext: String = "html") -> String { let pageDataPath = NSBundle(forClass: self).pathForResource(name, ofType: ext)! return (try! NSString(contentsOfFile: pageDataPath, encoding: NSUTF8StringEncoding)) as String } class func start() -> String { let webServer: GCDWebServer = GCDWebServer() webServer.addHandlerForMethod("GET", path: "/image.png", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in let img = UIImagePNGRepresentation(UIImage(named: "back")!) return GCDWebServerDataResponse(data: img, contentType: "image/png") } for page in ["findPage", "noTitle", "readablePage", "JSPrompt"] { webServer.addHandlerForMethod("GET", path: "/\(page).html", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in return GCDWebServerDataResponse(HTML: self.getPageData(page)) } } // we may create more than one of these but we need to give them uniquie accessibility ids in the tab manager so we'll pass in a page number webServer.addHandlerForMethod("GET", path: "/scrollablePage.html", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in var pageData = self.getPageData("scrollablePage") let page = Int((request.query["page"] as! String))! pageData = pageData.stringByReplacingOccurrencesOfString("{page}", withString: page.description) return GCDWebServerDataResponse(HTML: pageData as String) } webServer.addHandlerForMethod("GET", path: "/numberedPage.html", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in var pageData = self.getPageData("numberedPage") let page = Int((request.query["page"] as! String))! pageData = pageData.stringByReplacingOccurrencesOfString("{page}", withString: page.description) return GCDWebServerDataResponse(HTML: pageData as String) } webServer.addHandlerForMethod("GET", path: "/readerContent.html", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in return GCDWebServerDataResponse(HTML: self.getPageData("readerContent")) } webServer.addHandlerForMethod("GET", path: "/loginForm.html", requestClass: GCDWebServerRequest.self) { _ in return GCDWebServerDataResponse(HTML: self.getPageData("loginForm")) } webServer.addHandlerForMethod("GET", path: "/auth.html", requestClass: GCDWebServerRequest.self) { (request: GCDWebServerRequest!) in // "user:pass", Base64-encoded. let expectedAuth = "Basic dXNlcjpwYXNz" let response: GCDWebServerDataResponse if request.headers["Authorization"] as? String == expectedAuth && request.query["logout"] == nil { response = GCDWebServerDataResponse(HTML: "<html><body>logged in</body></html>") } else { // Request credentials if the user isn't logged in. response = GCDWebServerDataResponse(HTML: "<html><body>auth fail</body></html>") response.statusCode = 401 response.setValue("Basic realm=\"test\"", forAdditionalHeader: "WWW-Authenticate") } return response } if !webServer.startWithPort(0, bonjourName: nil) { XCTFail("Can't start the GCDWebServer") } // We use 127.0.0.1 explicitly here, rather than localhost, in order to avoid our // history exclusion code (Bug 1188626). let webRoot = "http://127.0.0.1:\(webServer.port)" return webRoot } } class SearchUtils { static func navigateToSearchSettings(tester: KIFUITestActor, engine: String = "Yahoo") { tester.tapViewWithAccessibilityLabel("Show Tabs") tester.waitForViewWithAccessibilityLabel("Tabs Tray") tester.tapViewWithAccessibilityLabel("Settings") tester.waitForViewWithAccessibilityLabel("Settings") tester.tapViewWithAccessibilityLabel("Search, \(engine)") tester.waitForViewWithAccessibilityIdentifier("Search") } static func navigateFromSearchSettings(tester: KIFUITestActor) { tester.tapViewWithAccessibilityLabel("Settings") tester.tapViewWithAccessibilityLabel("Done") tester.tapViewWithAccessibilityLabel("home") } // Given that we're at the Search Settings sheet, select the named search engine as the default. // Afterwards, we're still at the Search Settings sheet. static func selectDefaultSearchEngineName(tester: KIFUITestActor, engineName: String) { tester.tapViewWithAccessibilityLabel("Default Search Engine", traits: UIAccessibilityTraitButton) tester.waitForViewWithAccessibilityLabel("Default Search Engine") tester.tapViewWithAccessibilityLabel(engineName) tester.waitForViewWithAccessibilityLabel("Search") } // Given that we're at the Search Settings sheet, return the default search engine's name. static func getDefaultSearchEngineName(tester: KIFUITestActor) -> String { let view = tester.waitForCellWithAccessibilityLabel("Default Search Engine") return view.accessibilityValue! } } class DynamicFontUtils { // Need to leave time for the notification to propagate static func bumpDynamicFontSize(tester: KIFUITestActor) { let value = UIContentSizeCategoryAccessibilityExtraLarge UIApplication.sharedApplication().setValue(value, forKey: "preferredContentSizeCategory") tester.waitForTimeInterval(0.3) } static func lowerDynamicFontSize(tester: KIFUITestActor) { let value = UIContentSizeCategoryExtraSmall UIApplication.sharedApplication().setValue(value, forKey: "preferredContentSizeCategory") tester.waitForTimeInterval(0.3) } static func restoreDynamicFontSize(tester: KIFUITestActor) { let value = UIContentSizeCategoryMedium UIApplication.sharedApplication().setValue(value, forKey: "preferredContentSizeCategory") tester.waitForTimeInterval(0.3) } }
mpl-2.0
712028e6781b4fdb79b8592d1dba16fb
43.852423
163
0.678289
5.670565
false
true
false
false
d1brok/todo-apps
swift-Backend/Sources/TodoListAPI/TodoItem.swift
4
1280
/** * 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. **/ public struct TodoItem { /// ID public let documentID: String // Order public let order: Int /// Text to display public let title: String /// Whether completed or not public let completed: Bool public init(documentID: String, order: Int, title: String, completed: Bool) { self.documentID = documentID self.order = order self.title = title self.completed = completed } } extension TodoItem : Equatable { } public func == (lhs: TodoItem, rhs: TodoItem) -> Bool { return lhs.documentID == rhs.documentID && lhs.order == rhs.order && lhs.title == rhs.title && lhs.completed == rhs.completed }
apache-2.0
471807441d840e563cd36bd78f007afc
26.255319
81
0.679688
4.238411
false
false
false
false
cuzv/ExtensionKit
Sources/Extension/UIViewController+Extension.swift
1
14169
// // UIViewController+Extension.swift // Copyright (c) 2015-2016 Red Rain (http://mochxiao.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 UIKit // MARK: - AssociationKey private struct AssociationKey { fileprivate static var tag: String = "com.mochxiao.uialertaction.tag" fileprivate static var imagePickerCompletionHandlerWrapper = "com.mochxiao.uiimagepickercontroller.imagePickerCompletionHandlerWrapper" } // MARK: - Present UIAlertController public extension UIAlertAction { /// Default value is -1. public fileprivate(set) var tag: Int { get { if let value = associatedObject(forKey: &AssociationKey.tag) as? Int { return value } return -1 } set { associate(retainObject: newValue, forKey: &AssociationKey.tag) } } } public extension UIViewController { /// Present error. public func presentError(_ error: NSError) { if let message = error.userInfo[NSLocalizedDescriptionKey] as? String { presentAlert(message: message) } else if let message = error.userInfo[NSLocalizedFailureReasonErrorKey] as? String { presentAlert(message: message) } else { presentAlert(message: error.localizedDescription) } } /// Present message. public func presentAlert( title: String = "", message: String, cancelTitle: String = "好", cancelHandler: ((UIAlertAction) -> ())? = nil, otherTitles: [String]? = nil, othersHandler: ((UIAlertAction) -> ())? = nil) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler) alertController.addAction(cancelAction) if let otherTitles = otherTitles { for (index, title) in otherTitles.enumerated() { let action = UIAlertAction(title: title, style: .default, handler: othersHandler) action.tag = index alertController.addAction(action) } } present(alertController, animated: true, completion: nil) } /// Present ActionSheet. public func presentActionSheet( title: String = "", message: String, cancelTitle: String = "取消", cancelHandler: ((UIAlertAction) -> ())? = nil, actionTitles: [String], actionHandler: ((UIAlertAction) -> ())? = nil) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) for (index, title) in actionTitles.enumerated() { let action = UIAlertAction(title: title, style: .default, handler: actionHandler) action.tag = index alertController.addAction(action) } let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } } /// The convience version of `presentAlert(title:message:cancelTitle:cancelHandler:)`. /// Use this func carefully, it maybe iterate many times. public func doPresentAlert( title: String = "", message: String, cancelTitle: String = "好", cancelHandler: ((UIAlertAction) -> ())? = nil) { findLastPresentedViewController()?.presentAlert( title: title, message: message, cancelTitle: cancelTitle, cancelHandler: cancelHandler ) } public func doPresentAlert( title: String = "", message: String, cancelTitle: String = "好", cancelHandler: ((UIAlertAction) -> ())? = nil, actionTitles: [String], actionHandler: ((UIAlertAction) -> ())? = nil) { findLastPresentedViewController()?.presentAlert( title: title, message: message, cancelTitle: cancelTitle, cancelHandler: cancelHandler, otherTitles: actionTitles, othersHandler: actionHandler ) } /// The convience version of `presentError:`. /// Use this func carefully, it maybe iterate many times. public func doPresentError(_ error: NSError) { findLastPresentedViewController()?.presentError(error) } /// The convience version of `presentActionSheet(title:message:cancelTitle:cancelHandler:actionTitles:actionHandler:)`. /// Use this func carefully, it maybe iterate many times. public func doPresentActionSheet( title: String = "", message: String, cancelTitle: String = "取消", cancelHandler: ((UIAlertAction) -> ())? = nil, actionTitles:[String], actionHandler:((UIAlertAction) -> ())? = nil) { findLastPresentedViewController()?.presentActionSheet( title: title, message: message, cancelTitle: cancelTitle, cancelHandler: cancelHandler, actionTitles: actionTitles, actionHandler: actionHandler ) } // MARK: - Find last time presented view controller /// Returns the most recently presented UIViewController (visible). /// http://stackoverflow.com/questions/24825123/get-the-current-view-controller-from-the-app-delegate public func findLastPresentedViewController() -> UIViewController? { func findTopLevelViewController(_ viewController: UIViewController) -> UIViewController? { if let vc = viewController.presentedViewController { return findTopLevelViewController(vc) } else if let vc = viewController as? UISplitViewController { if let vc = vc.viewControllers.last { return findTopLevelViewController(vc) } return vc } else if let vc = viewController as? UINavigationController { if let vc = vc.topViewController { return findTopLevelViewController(vc) } return vc } else if let vc = viewController as? UITabBarController { if let vc = vc.selectedViewController { return findTopLevelViewController(vc) } return vc } else { return viewController } } if let rootViewController = UIApplication.shared.keyWindow?.rootViewController { return findTopLevelViewController(rootViewController) } return nil } // MARK: - Present UIImagePickerController private extension UIImagePickerController { var imagePickerCompletionHandlerWrapper: ClosureDecorator<(UIImagePickerController, UIImage?)> { get { return associatedObject(forKey: &AssociationKey.imagePickerCompletionHandlerWrapper) as! ClosureDecorator<(UIImagePickerController, UIImage?)> } set { associate(retainObject: newValue, forKey: &AssociationKey.imagePickerCompletionHandlerWrapper) } } } public extension UIViewController { /// Present UIImagePickerController. public func presentImagePicker(sourceType: UIImagePickerControllerSourceType = .photoLibrary, completionHandler: @escaping ((UIImagePickerController, UIImage?) -> ())) { let imagePicker = UIImagePickerController() imagePicker.sourceType = sourceType imagePicker.videoQuality = .typeLow imagePicker.delegate = self imagePicker.allowsEditing = true imagePicker.view.tintColor = UIApplication.shared.keyWindow?.tintColor imagePicker.imagePickerCompletionHandlerWrapper = ClosureDecorator(completionHandler) present(imagePicker, animated: true, completion: nil) } } extension UIViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate { public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.presentingViewController?.dismiss(animated: true, completion: nil) picker.imagePickerCompletionHandlerWrapper.invoke((picker, nil)) } public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { globalThreadAsync { () -> Void in if let image = info[UIImagePickerControllerEditedImage] as? UIImage { let newImage = image.orientation(to: .up) if let imageData = newImage.compress(toByte: 100 * 1024) { let resultImage = UIImage(data: imageData, scale: UIScreen.main.scale) mainThreadAsync { picker.presentingViewController?.dismiss(animated: true, completion: nil) picker.imagePickerCompletionHandlerWrapper.invoke((picker, resultImage)) } return } } } } public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { picker.presentingViewController?.dismiss(animated: true, completion: nil) picker.imagePickerCompletionHandlerWrapper.invoke((picker, image)) } } // MARK: - Navigation public extension UIViewController { public func show(_ viewController: UIViewController) { navigationController?.show(viewController, sender: self) } public func backToPrevious(animated: Bool = true) { if let presentingViewController = presentingViewController { presentingViewController.dismiss(animated: animated, completion: nil) } else { _ = navigationController?.popViewController(animated: animated) } } public func backToRoot(animated: Bool = true) { if let presentingViewController = presentingViewController { presentingViewController.dismiss(animated: animated, completion: nil) } else { _ = navigationController?.popToRootViewController(animated: animated) } } public func present(_ viewControllerToPresent: UIViewController, completion: @escaping (() -> ())) { present(viewControllerToPresent, animated: true, completion: completion) } public func present(_ viewControllerToPresent: UIViewController) { present(viewControllerToPresent, animated: true, completion: nil) } public func presentTranslucent(_ viewController: UIViewController, modalTransitionStyle: UIModalTransitionStyle = .coverVertical, animated flag: Bool = true, completion: (() -> ())? = nil) { viewController.modalPresentationStyle = .custom viewController.modalTransitionStyle = UIDevice.iOS8x ? modalTransitionStyle : .crossDissolve // Very important view.window?.rootViewController?.modalPresentationStyle = UIDevice.iOS8x ? .fullScreen : .currentContext present(viewController, animated: flag, completion: completion) } public func dismiss(completion: (() -> Void)? = nil) { presentingViewController?.dismiss(animated: true, completion: completion) } public func dismissToTop(animated: Bool = true, completion: (() -> Void)? = nil) { var presentedViewController = self while let presentingViewController = presentedViewController.presentingViewController { presentedViewController = presentingViewController } presentedViewController.dismiss(animated: animated, completion: completion) } public func addChild(_ viewController: UIViewController) { viewController.willMove(toParentViewController: self) addChildViewController(viewController) viewController.view.frame = view.frame view.addSubview(viewController.view) viewController.didMove(toParentViewController: self) } } public extension UIViewController { public func showRightBarButtonItem(withImage image: UIImage?, actionHandler: ((UIBarButtonItem) -> ())?) { navigationItem.rightBarButtonItem = UIBarButtonItem.make(image: image, actionHandler: actionHandler) } public func showRightBarButtonItem(withTitle title: String, actionHandler: ((UIBarButtonItem) -> ())?) { navigationItem.rightBarButtonItem = UIBarButtonItem.make(title: title, actionHandler: actionHandler) } public func showRightBarButtonItem(withSystemItem item: UIBarButtonSystemItem, actionHandler: ((UIBarButtonItem) -> ())?) { navigationItem.rightBarButtonItem = UIBarButtonItem.make(systemItem: item, actionHandler: actionHandler) } public func showLeftBarButtonItem(withImage image: UIImage?, actionHandler: ((UIBarButtonItem) -> ())?) { navigationItem.leftBarButtonItem = UIBarButtonItem.make(image: image, actionHandler: actionHandler) } public func showLeftBarButtonItem(withTitle title: String, actionHandler: ((UIBarButtonItem) -> ())?) { navigationItem.leftBarButtonItem = UIBarButtonItem.make(title: title, actionHandler: actionHandler) } public func showLeftBarButtonItem(withSystemItem item: UIBarButtonSystemItem, actionHandler: ((UIBarButtonItem) -> ())?) { navigationItem.leftBarButtonItem = UIBarButtonItem.make(systemItem: item, actionHandler: actionHandler) } }
mit
a3cd92b4d3aa187c2dba1d70c2170392
41.253731
194
0.686401
5.477941
false
false
false
false
wenghengcong/Coderpursue
BeeFun/BeeFun/Model/BeeFunModel/ObjTag.swift
1
1125
// // ObjTagModel.swift // BeeFun // // Created by WengHengcong on 2018/5/3. // Copyright © 2018年 JungleSong. All rights reserved. // import UIKit import ObjectMapper public class ObjTag: NSObject, Mappable, NSCopying { public func copy(with zone: NSZone? = nil) -> Any { let newCopy = ObjTag() newCopy.name = name newCopy.owner = owner newCopy.count = count newCopy.sort = sort newCopy.repos = repos newCopy.created_at = created_at newCopy.updated_at = updated_at return newCopy } var name: String? var owner: String? var count: Int? var sort: Int? var repos: String? var created_at: Int64? var updated_at: Int64? required public init?(map: Map) { } override init() { super.init() } public func mapping(map: Map) { name <- map["name"] owner <- map["owner"] count <- map["count"] sort <- map["sort"] repos <- map["repos"] created_at <- map["created_at"] updated_at <- map["updated_at"] } }
mit
45f65cfe8a7ba1ca0b4bb65214ffb77e
21
55
0.55615
3.80339
false
false
false
false
Evergreen-Labs/thyme-ios
Pods/Nuke/Sources/Scheduler.swift
3
6962
// The MIT License (MIT) // // Copyright (c) 2016 Alexander Grebenyuk (github.com/kean). import Foundation // MARK: Scheduler /// Schedules execution of synchronous work. public protocol Scheduler { func execute(token: CancellationToken?, closure: @escaping (Void) -> Void) } /// Schedules execution of asynchronous work which is considered /// finished when `finish` closure is called. public protocol AsyncScheduler { func execute(token: CancellationToken?, closure: @escaping (_ finish: @escaping (Void) -> Void) -> Void) } // MARK: - DispatchQueueScheduler public final class DispatchQueueScheduler: Scheduler { public let queue: DispatchQueue public init(queue: DispatchQueue) { self.queue = queue } public func execute(token: CancellationToken?, closure: @escaping (Void) -> Void) { if let token = token, token.isCancelling { return } let work = DispatchWorkItem(block: closure) queue.async(execute: work) token?.register { [weak work] in work?.cancel() } } } // MARK: - OperationQueueScheduler public final class OperationQueueScheduler: AsyncScheduler { public let queue: OperationQueue public convenience init(maxConcurrentOperationCount: Int) { let queue = OperationQueue() queue.maxConcurrentOperationCount = maxConcurrentOperationCount self.init(queue: queue) } public init(queue: OperationQueue) { self.queue = queue } public func execute(token: CancellationToken?, closure: @escaping (_ finish: @escaping (Void) -> Void) -> Void) { if let token = token, token.isCancelling { return } let operation = Operation(starter: closure) queue.addOperation(operation) token?.register { [weak operation] in operation?.cancel() } } } // MARK: Operation private final class Operation: Foundation.Operation { override var isExecuting: Bool { get { return _isExecuting } set { willChangeValue(forKey: "isExecuting") _isExecuting = newValue didChangeValue(forKey: "isExecuting") } } private var _isExecuting = false override var isFinished: Bool { get { return _isFinished } set { willChangeValue(forKey: "isFinished") _isFinished = newValue didChangeValue(forKey: "isFinished") } } var _isFinished = false let starter: (_ finish: @escaping (Void) -> Void) -> Void let queue = DispatchQueue(label: "com.github.kean.Nuke.Operation") init(starter: @escaping (_ fulfill: @escaping (Void) -> Void) -> Void) { self.starter = starter } override func start() { queue.sync { isExecuting = true DispatchQueue.global().async { self.starter() { [weak self] in self?.finish() } } } } func finish() { queue.sync { if !isFinished { isExecuting = false isFinished = true } } } } // MARK: RateLimiter /// Controls the rate at which the underlying scheduler executes work. Uses /// classic [token bucket](https://en.wikipedia.org/wiki/Token_bucket) algorithm. /// /// The main use case for rate limiter is to support large (infinite) collections /// of images by preventing trashing of underlying systems, primary URLSession. /// /// The implementation supports quick bursts of requests which can be executed /// without any delays when "the bucket is full". This is important to prevent /// rate limiter from affecting "normal" requests flow. public final class RateLimiter: AsyncScheduler { private let scheduler: AsyncScheduler // underlying scheduler private let burst: Double private let burstInterval: TimeInterval private var bucket: Double private var lastRefill: TimeInterval private var isExecutingPendingItems = false private var pendingItems = [Item]() private let queue = DispatchQueue(label: "com.github.kean.Nuke.RateLimiter") private struct Item { let token: CancellationToken? let closure: (@escaping (Void) -> Void) -> Void } /// Initializes the `RateLimiter` with the given scheduler and configuration. /// - parameter scheduler: Underlying scheduler which `RateLimiter` uses /// to execute items. /// - parameter rate: Maximum number of requests per second. 30 by default. /// - parameter burst: Maximum number of requests which can be executed without /// any delays when "bucket is full". 15 by default. public init(scheduler: AsyncScheduler, rate: Int = 30, burst: Int = 15) { self.scheduler = scheduler self.burst = Double(burst) self.burstInterval = Double(burst) / Double(rate) self.bucket = Double(burst) self.lastRefill = CFAbsoluteTimeGetCurrent() } public func execute(token: CancellationToken?, closure: @escaping (@escaping (Void) -> Void) -> Void) { // Quick pre-lock check if let token = token, token.isCancelling { return } queue.sync { if !pendingItems.isEmpty || !execute(token: token, closure: closure) { // `pending` is a queue: insert at 0; popLast() later pendingItems.insert(Item(token: token, closure: closure), at: 0) setNeedsExecutePendingItems() } } } private func execute(token: CancellationToken?, closure: @escaping (@escaping (Void) -> Void) -> Void) -> Bool { // Drop cancelled items without touching the bucket if let token = token, token.isCancelling { return true } // Refill the bucket let now = CFAbsoluteTimeGetCurrent() bucket += (now - lastRefill) * (burst / burstInterval) // passed time * rate lastRefill = now if bucket > burst { // Prevents bucket overflow bucket = burst } // Execute item if bucket is not empty if bucket > 1.0 { bucket -= 1.0 scheduler.execute(token: token, closure: closure) return true } return false } private func setNeedsExecutePendingItems() { if !isExecutingPendingItems { isExecutingPendingItems = true queue.asyncAfter(deadline: .now() + 0.05) { while let item = self.pendingItems.popLast() { if !self.execute(token: item.token, closure: item.closure) { self.pendingItems.append(item) // put item back break // stop trying to execute more items } } self.isExecutingPendingItems = false if !self.pendingItems.isEmpty { self.setNeedsExecutePendingItems() } } } } }
mit
743c04768e5ff1bac58f8f61aa293d8f
33.636816
117
0.618357
4.79807
false
false
false
false
Speicher210/wingu-sdk-ios-demoapp
Example/Pods/Nuke/Sources/Nuke.swift
2
3296
// The MIT License (MIT) // // Copyright (c) 2017 Alexander Grebenyuk (github.com/kean). import Foundation #if os(macOS) import AppKit.NSImage /// Alias for `NSImage`. public typealias Image = NSImage #else import UIKit.UIImage /// Alias for `UIImage`. public typealias Image = UIImage #endif /// Loads an image into the given target. /// /// For more info see `loadImage(with:into:)` method of `Manager`. public func loadImage(with url: URL, into target: Target) { Manager.shared.loadImage(with: url, into: target) } /// Loads an image into the given target. /// /// For more info see `loadImage(with:into:)` method of `Manager`. public func loadImage(with request: Request, into target: Target) { Manager.shared.loadImage(with: request, into: target) } /// Loads an image and calls the given `handler`. The method itself /// **doesn't do** anything when the image is loaded - you have full /// control over how to display it, etc. /// /// The handler only gets called if the request is still associated with the /// `target` by the time it's completed. The handler gets called immediately /// if the image was stored in the memory cache. /// /// See `loadImage(with:into:)` method for more info. public func loadImage(with url: URL, into target: AnyObject, handler: @escaping Manager.Handler) { Manager.shared.loadImage(with: url, into: target, handler: handler) } /// Loads an image and calls the given `handler`. The method itself /// **doesn't do** anything when the image is loaded - you have full /// control over how to display it, etc. /// /// The handler only gets called if the request is still associated with the /// `target` by the time it's completed. The handler gets called immediately /// if the image was stored in the memory cache. /// /// For more info see `loadImage(with:into:handler:)` method of `Manager`. public func loadImage(with request: Request, into target: AnyObject, handler: @escaping Manager.Handler) { Manager.shared.loadImage(with: request, into: target, handler: handler) } /// Cancels an outstanding request associated with the target. public func cancelRequest(for target: AnyObject) { Manager.shared.cancelRequest(for: target) } /// An enum representing either a success with a result value, or a failure. public enum Result<T> { case success(T), failure(Error) /// Returns a `value` if the result is success. public var value: T? { if case let .success(val) = self { return val } else { return nil } } /// Returns an `error` if the result is failure. public var error: Error? { if case let .failure(err) = self { return err } else { return nil } } } internal final class Lock { var mutex = UnsafeMutablePointer<pthread_mutex_t>.allocate(capacity: 1) init() { pthread_mutex_init(mutex, nil) } deinit { pthread_mutex_destroy(mutex) mutex.deinitialize() mutex.deallocate(capacity: 1) } /// In critical places it's better to use lock() and unlock() manually func sync<T>(_ closure: () -> T) -> T { pthread_mutex_lock(mutex) defer { pthread_mutex_unlock(mutex) } return closure() } func lock() { pthread_mutex_lock(mutex) } func unlock() { pthread_mutex_unlock(mutex) } }
apache-2.0
418447bee5bacab852ab09f9ee88d6f0
32.979381
106
0.683859
3.956783
false
false
false
false
bmichotte/HSTracker
HSTracker/Database/Cards.swift
1
5551
// // Cards.swift // HSTracker // // Created by Benjamin Michotte on 24/05/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation final class Cards { static let classes: [CardClass] = { return [.druid, .hunter, .mage, .paladin, .priest, .rogue, .shaman, .warlock, .warrior] .sorted { NSLocalizedString($0.rawValue, comment: "") < NSLocalizedString($1.rawValue, comment: "") } }() static var cards = [Card]() static func hero(byId cardId: String) -> Card? { if let card = cards.firstWhere({ $0.id == cardId && $0.type == .hero }) { return card.copy() as? Card } return nil } static func isHero(cardId: String?) -> Bool { guard !cardId.isBlank else { return false } return hero(byId: cardId!) != .none } static func by(cardId: String?) -> Card? { guard !cardId.isBlank else { return nil } if let card = cards.filter({ $0.type != .hero && $0.type != .hero_power }).firstWhere({ $0.id == cardId }) { return card.copy() as? Card } return nil } static func by(dbfId: Int?, collectible: Bool = true) -> Card? { guard let dbfId = dbfId else { return nil } if let card = (collectible ? self.collectible() : cards).first({ $0.dbfId == dbfId }) { return card.copy() as? Card } return nil } static func any(byId cardId: String) -> Card? { if cardId.isBlank { return nil } if let card = cards.firstWhere({ $0.id == cardId }) { return card.copy() as? Card } return nil } static func hero(byPlayerClass name: CardClass) -> Card? { switch name { case .druid: return hero(byId: CardIds.Collectible.Druid.MalfurionStormrage) case .hunter: return hero(byId: CardIds.Collectible.Hunter.Rexxar) case .mage: return hero(byId: CardIds.Collectible.Mage.JainaProudmoore) case .paladin: return hero(byId: CardIds.Collectible.Paladin.UtherLightbringer) case .priest: return hero(byId: CardIds.Collectible.Priest.AnduinWrynn) case .rogue: return hero(byId: CardIds.Collectible.Rogue.ValeeraSanguinar) case .shaman: return hero(byId: CardIds.Collectible.Shaman.Thrall) case .warlock: return hero(byId: CardIds.Collectible.Warlock.Guldan) case .warrior: return hero(byId: CardIds.Collectible.Warrior.GarroshHellscream) default: return nil } } static func by(name: String) -> Card? { if let card = collectible().firstWhere({ $0.name == name }) { return card.copy() as? Card } return nil } static func by(englishName name: String) -> Card? { if let card = collectible().firstWhere({ $0.enName == name || $0.name == name }) { return card.copy() as? Card } return nil } static func by(englishNameCaseInsensitive name: String) -> Card? { if let card = collectible().firstWhere({ $0.enName.caseInsensitiveCompare(name) == ComparisonResult.orderedSame || $0.name.caseInsensitiveCompare(name) == ComparisonResult.orderedSame }) { return card.copy() as? Card } return nil } static func collectible() -> [Card] { return cards.filter { $0.collectible && $0.type != .hero && $0.type != .hero_power } } static func search(className: CardClass?, sets: [CardSet] = [], term: String = "", cost: Int = -1, rarity: Rarity? = .none, standardOnly: Bool = false, damage: Int = -1, health: Int = -1, type: CardType = .invalid, race: Race?) -> [Card] { var cards = collectible() if term.isEmpty { cards = cards.filter { $0.playerClass == className } } else { cards = cards.filter { $0.playerClass == className || $0.playerClass == .neutral } .filter { $0.name.lowercased().contains(term.lowercased()) || $0.enName.lowercased().contains(term.lowercased()) || $0.text.lowercased().contains(term.lowercased()) || $0.rarity.rawValue.contains(term.lowercased()) || $0.type.rawString().lowercased().contains(term.lowercased()) || $0.race.rawValue.lowercased().contains(term.lowercased()) } } if type != .invalid { cards = cards.filter { $0.type == type } } if let race = race { cards = cards.filter { $0.race == race } } if health != -1 { cards = cards.filter { $0.health == health } } if damage != -1 { cards = cards.filter { $0.attack == damage } } if standardOnly { cards = cards.filter { $0.isStandard } } if let rarity = rarity { cards = cards.filter { $0.rarity == rarity } } if !sets.isEmpty { cards = cards.filter { $0.set != nil && sets.contains($0.set!) } } if cost != -1 { cards = cards.filter { if cost == 7 { return $0.cost >= 7 } return $0.cost == cost } } return cards.sortCardList() } }
mit
1e08ef6c19d2b3a1981779f787df8166
32.433735
95
0.531712
4.086892
false
false
false
false
Chaosspeeder/YourGoals
YourGoals/Business/Data Model/Extensions/TaskProgress+Date.swift
1
2765
// // TaskProgress+Date.swift // YourGoals // // Created by André Claaßen on 27.10.17. // Copyright © 2017 André Claaßen. All rights reserved. // import Foundation extension TaskProgress { /// retrieves the task progress as an DateInterval var dateInterval:DateInterval { let startDate = self.start ?? Date.minimalDate let endDate = self.end ?? Date.maximalDate return DateInterval(start: startDate, end: endDate) } /// returns true, if there is an intersection between the two intervals /// /// - Parameter withInterval: the interval to compare with the time progress /// - Returns: true, if there is an intersection func intersects(withInterval: DateInterval) -> Bool { return self.dateInterval.intersects(withInterval) } /// true, if the date lies between start and end of the current progress /// /// start >= date < end /// /// - Parameter date: check this date /// - Returns: true, if the date intersects the current progress func intersects(withDate date: Date) -> Bool { let startDate = self.start ?? Date.minimalDate let endDate = self.end ?? Date.maximalDate return (startDate.compare(date) == ComparisonResult.orderedSame || startDate.compare(date) == ComparisonResult.orderedAscending) && ( endDate.compare(date) == ComparisonResult.orderedDescending) } /// calculate the time interval for a progression til date /// /// - Parameter date: time interval func timeInterval(til date:Date) -> TimeInterval { let startDate = self.start ?? Date.minimalDate let endDate = self.end ?? date let interval = endDate.timeIntervalSince(startDate) return interval >= 0 ? interval : TimeInterval(0) } /// start date and time for the given date /// /// - Parameter day: the day /// - Returns: a datetime in the range of the day func startOfDay(day: Date) -> Date { return min(max(day.startOfDay, self.start ?? day.startOfDay ), day.endOfDay) } /// end date and time for the given date /// /// - Parameter day: the day /// - Returns: a datetime in the range of the day func endOfDay(day: Date) -> Date { return max(day.startOfDay, min(day.endOfDay, self.end ?? day)) } /// calculate the time interval worked on a given date /// /// - Parameter date: time interval func timeInterval(on date:Date) -> TimeInterval { let startDate = startOfDay(day: date) let endDate = endOfDay(day: date) let interval = endDate.timeIntervalSince(startDate) return interval >= 0 ? interval : TimeInterval(0) } }
lgpl-3.0
f1200aeca0ecd7c9d9eeb38255f03930
33.5
139
0.634783
4.615385
false
false
false
false
tutao/tutanota
app-ios/tutanota/Sources/CustomSchemeHandlers.swift
1
3855
import Foundation /** * intercepts and proxies all requests to api:// and apis:// URLs rom the webview */ class ApiSchemeHandler : NSObject, WKURLSchemeHandler { private let regex: NSRegularExpression private let urlSession: URLSession private var taskMap = [URLRequest : URLSessionDataTask]() override init() { // docs say that schemes are case insensitive self.regex = try! NSRegularExpression(pattern: "^api", options: .caseInsensitive) let configuration = URLSessionConfiguration.ephemeral configuration.timeoutIntervalForRequest = 20 self.urlSession = URLSession(configuration: configuration) super.init() } func rewriteRequest(_ oldRequest: URLRequest) -> URLRequest { let urlString = oldRequest.url!.absoluteString let range = NSMakeRange(0, urlString.count) let newUrlString = self.regex.stringByReplacingMatches(in: urlString, range: range, withTemplate: "http") let newUrl = URL(string: newUrlString)! var newRequest = oldRequest newRequest.url = newUrl return newRequest } func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) { let newRequest = self.rewriteRequest(urlSchemeTask.request) let task = self.urlSession.dataTask(with: newRequest) { data, response, err in defer {self.taskMap.removeValue(forKey: urlSchemeTask.request)} if let err = err { if (err as NSError).domain == NSURLErrorDomain && (err as NSError).code == NSURLErrorCancelled { return } urlSchemeTask.didFailWithError(err) return } urlSchemeTask.didReceive(response!) urlSchemeTask.didReceive(data!) urlSchemeTask.didFinish() } self.taskMap[urlSchemeTask.request] = task task.resume() } func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) { guard let task = self.taskMap[urlSchemeTask.request] else { return } if task.state == .running || task.state == .suspended { task.cancel() self.taskMap.removeValue(forKey: urlSchemeTask.request) } } } /** * intercepts asset:// requests and serves them from the asset directory */ class AssetSchemeHandler : NSObject, WKURLSchemeHandler { private let folderPath : String init( folderPath: String ) { self.folderPath = (folderPath as NSString).standardizingPath TUTSLog("folderPath: \(self.folderPath)") super.init() } func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) { let newFilePath = urlSchemeTask.request.url!.path let appendedPath : NSString = (self.folderPath as NSString).appendingPathComponent(newFilePath) as NSString let requestedFilePath = appendedPath.standardizingPath if(!requestedFilePath.starts(with: self.folderPath)){ let err = NSError(domain: NSURLErrorDomain, code: NSURLErrorFileDoesNotExist) urlSchemeTask.didFailWithError(err) } else { let fileContent: Data do { fileContent = try Data(contentsOf: URL(fileURLWithPath: requestedFilePath)) } catch { TUTSLog("failed to load asset URL \(requestedFilePath), got error \(error)") let err = NSError(domain: NSURLErrorDomain, code: NSURLErrorFileDoesNotExist) urlSchemeTask.didFailWithError(err) return } let mimeType = getFileMIMETypeWithDefault(path: requestedFilePath) urlSchemeTask.didReceive(URLResponse( url: urlSchemeTask.request.url!, mimeType: mimeType, expectedContentLength: fileContent.count, textEncodingName: "UTF-8") ) urlSchemeTask.didReceive(fileContent) urlSchemeTask.didFinish() } } func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) { // we're doing the asset load synchronously, so we won't get a chance to cancel. } }
gpl-3.0
da18dbe2ec7bf57d9adb37d6d57767e4
34.045455
111
0.701946
4.849057
false
false
false
false
CherishSmile/ZYBase
ZYBase/BaseSet/RootManager.swift
1
2724
// // RootManager.swift // ZywxBase // // Created by Mzywx on 2016/12/21. // Copyright © 2016年 Mzywx. All rights reserved. // open class RootManager: NSObject { public static let shareManager = RootManager() private override init(){ } /** * 创建TabBar * - window: window * - controllers: tabBarVC的viewControllers * - titles: tabBarItem的title * - images: tabBarItem的image * - selectImages: tabBarItem的selectimage */ open func creatRootVC(_ window:UIWindow,_ controllers:Array<AnyClass>,_ titles:Array<String>?,_ images:Array<UIImage>?,_ selectImages:Array<UIImage>?) { NotificationCenter.default.removeObserver(self) window.rootViewController = nil var navArr:Array<UIViewController> = [] for i in 0..<controllers.count { let vcCls = controllers[i] as! UIViewController.Type let vc = vcCls.init() if let titlesArr = titles { if i<titlesArr.count{ vc.title = titlesArr[i] } } if let imageArr = images { if i<imageArr.count { vc.tabBarItem.image = imageArr[i].withRenderingMode(.alwaysOriginal) } } if let selectImagesArr = selectImages { if i<selectImagesArr.count { vc.tabBarItem.selectedImage = selectImagesArr[i].withRenderingMode(.alwaysOriginal) } } let nav = UINavigationController(rootViewController: vc) navArr.append(nav) } let tabvc = UITabBarController() tabvc.viewControllers = navArr window.rootViewController = tabvc window.makeKeyAndVisible() } /** * 创建登录页 * - window: window * - controller: controller */ open func creatLoginVC(_ window:UIWindow,_ controller:AnyClass) { NotificationCenter.default.removeObserver(self) window.rootViewController = nil let loginCls = controller as! UIViewController.Type let loginVC = loginCls.init() let nav = UINavigationController(rootViewController: loginVC) window.rootViewController = nav window.makeKeyAndVisible() } /** * 创建启动页 * - window: window * - controller: controller */ open func creatIntroVC(_ window:UIWindow,_ controller:AnyClass) { let introCls = controller as! UIViewController.Type let introVC = introCls.init() window.rootViewController = introVC window.makeKeyAndVisible() } }
mit
6adca49bf5a74f77ad2b929e6acc9984
29.556818
156
0.584604
4.784698
false
false
false
false
younata/RSSClient
TethysKit/Use Cases/ImportUseCase.swift
1
4956
import Muon import Lepton import Result import CBGPromise import FutureHTTP public enum ImportUseCaseItem: Equatable { case none(URL) case webPage(URL, [URL]) case feed(URL, Int) case opml(URL, Int) } public protocol ImportUseCase { func scanForImportable(_ url: URL) -> Future<ImportUseCaseItem> func importItem(_ url: URL) -> Future<Result<Void, TethysError>> } public final class DefaultImportUseCase: ImportUseCase { private let httpClient: HTTPClient private let feedCoordinator: FeedCoordinator private let opmlService: OPMLService private let fileManager: FileManager private let mainQueue: OperationQueue fileprivate enum ImportType { case feed case opml } fileprivate var knownUrls: [URL: ImportType] = [:] public init(httpClient: HTTPClient, feedCoordinator: FeedCoordinator, opmlService: OPMLService, fileManager: FileManager, mainQueue: OperationQueue) { self.httpClient = httpClient self.feedCoordinator = feedCoordinator self.opmlService = opmlService self.fileManager = fileManager self.mainQueue = mainQueue } public func scanForImportable(_ url: URL) -> Future<ImportUseCaseItem> { let promise = Promise<ImportUseCaseItem>() if url.isFileURL { guard !url.absoluteString.contains("default.realm"), let data = try? Data(contentsOf: url) else { promise.resolve(.none(url)) return promise.future } promise.resolve(self.scanDataForItem(data, url: url)) } else { self.httpClient.request(URLRequest(url: url)).map { result in switch result { case .success(let response): self.mainQueue.addOperation { promise.resolve(self.scanDataForItem(response.body, url: url)) } case .failure: self.mainQueue.addOperation { promise.resolve(.none(url)) } } } } return promise.future } public func importItem(_ url: URL) -> Future<Result<Void, TethysError>> { let promise = Promise<Result<Void, TethysError>>() guard let importType = self.knownUrls[url] else { promise.resolve(.failure(.unknown)) return promise.future } switch importType { case .feed: let url = self.canonicalURLForFeedAtURL(url) self.feedCoordinator.subscribe(to: url).then { result in self.mainQueue.addOperation { promise.resolve(result.map { _ in Void() }) } } case .opml: self.opmlService.importOPML(url).then { result in self.mainQueue.addOperation { promise.resolve(result.map { _ in Void() }) } } } return promise.future } private func scanDataForItem(_ data: Data, url: URL) -> ImportUseCaseItem { guard let string = String(data: data, encoding: String.Encoding.utf8) else { return .none(url) } if let feedCount = self.isDataAFeed(string) { self.knownUrls[url] = .feed return .feed(url, feedCount) } else if let opmlCount = self.isDataAnOPML(string) { self.knownUrls[url] = .opml return .opml(url, opmlCount) } else { let feedUrls = self.feedsInWebPage(url, webPage: string) feedUrls.forEach { self.knownUrls[$0] = .feed } return .webPage(url, feedUrls) } } private func isDataAFeed(_ data: String) -> Int? { var ret: Int? let feedParser = FeedParser(string: data) _ = feedParser.success { ret = $0.articles.count } feedParser.start() return ret } private func canonicalURLForFeedAtURL(_ url: URL) -> URL { guard url.isFileURL else { return url } let string = (try? String(contentsOf: url)) ?? "" var ret: URL! = nil FeedParser(string: string).success { ret = $0.link }.start() return ret } private func isDataAnOPML(_ data: String) -> Int? { var ret: Int? let opmlParser = Parser(text: data) _ = opmlParser.success { ret = $0.count } opmlParser.start() return ret } private func feedsInWebPage(_ url: URL, webPage: String) -> [URL] { var ret: [URL] = [] let webPageParser = WebPageParser(string: webPage) { ret = $0.map { URL(string: $0.absoluteString, relativeTo: url)?.absoluteURL ?? $0 as URL } } webPageParser.searchType = .feeds webPageParser.start() return ret } }
mit
82e557a3992825d62316e070d0313b7a
32.261745
109
0.569209
4.513661
false
false
false
false
lvsti/Ilion
Ilion/Translation.swift
1
2658
// // Translation.swift // Ilion // // Created by Tamas Lustyik on 2018. 10. 10.. // Copyright © 2018. Tamas Lustyik. All rights reserved. // import Foundation enum Translation { case `static`(String) case `dynamic`(LocalizedFormat) func toString() -> String { switch self { case .static(let text): return text case .dynamic(let format): let config = format.toStringsDictEntry() let nsFormat = format.baseFormat as NSString let locFormat = nsFormat.perform(NSSelectorFromString("_copyFormatStringWithConfiguration:"), with: config) .takeUnretainedValue() return locFormat as! String } } } extension Translation { func addingStartEndMarkers() -> Translation { switch self { case .static(let text): return .static("[\(text)]") case .dynamic(let format): return .dynamic(format.prepending("[").appending("]")) } } func applyingPseudoLocalization() -> Translation { switch self { case .static(let text): return .static(text.applyingPseudoLanguageTransformation()) case .dynamic(let format): let transformedFormat = format.applyingTransform { slices in slices.map { $0.applyingPseudoLanguageTransformation() } } return .dynamic(transformedFormat) } } func simulatingExpansion(by factor: Double) -> Translation { func paddingText(forLength length: Int) -> String { let growth = Int(floor(Double(length) * factor)) - length let pattern = "lorem ipsum dolor sit amet consectetur adipiscing elit " let paddingSource = String(repeating: pattern, count: (growth / pattern.count) + 1) let padding = paddingSource[paddingSource.startIndex ..< paddingSource.index(paddingSource.startIndex, offsetBy: growth)] return "{\(padding)}" } switch self { case .static(let text): let padding = paddingText(forLength: text.count) return .static(text.appending(padding)) case .dynamic(let format): let transformedFormat = format.applyingTransform { slices in let charCount = slices.map { $0.count }.reduce(0, +) let padding = paddingText(forLength: charCount) var slices = slices slices[slices.count - 1] = slices.last!.appending(padding) return slices } return .dynamic(transformedFormat) } } }
mit
490ccf4a58b11ba9aac8c19613aaaa33
34.426667
133
0.591645
4.92037
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieCore/ApplePlatform/Metal.swift
1
1920
// // Metal.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. 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. // #if canImport(Metal) extension MTLDevice { public func makeBuffer<T>(_ buffer: MappedBuffer<T>, options: MTLResourceOptions = []) -> MTLBuffer? { var box = MappedBuffer<T>._Box(ref: buffer.base) let length = (buffer.count * MemoryLayout<T>.stride).align(Int(getpagesize())) guard length != 0 else { return nil } return self.makeBuffer(bytesNoCopy: buffer.base.address, length: length, options: options, deallocator: { _, _ in box.ref = nil }) } } extension MTLComputeCommandEncoder { public func setBuffer<T>(_ buffer: MappedBuffer<T>, offset: Int, index: Int) { self.setBuffer(self.device.makeBuffer(buffer), offset: offset, index: index) } } #endif
mit
baffaade420fd8472dd6992950fc7e85
41.666667
138
0.714063
4.146868
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGPU/GPContext/CGPathProcessorKernel.swift
1
3025
// // CGPathProcessorKernel.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. 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. // #if canImport(CoreImage) final class CGPathProcessorKernel: CIImageProcessorKernel { enum Error: Swift.Error { case unknown case unsupportedFormat } private struct Info { let path: CGPath let rule: CGPathFillRule let shouldAntialias: Bool } class func apply(withExtent extent: CGRect, path: CGPath, rule: CGPathFillRule, shouldAntialias: Bool) throws -> CIImage { let image = try self.apply(withExtent: extent, inputs: nil, arguments: ["info": Info(path: path, rule: rule, shouldAntialias: shouldAntialias)]) return image.maximumComponent() } override class var outputFormat: CIFormat { return .R8 } override class func process(with inputs: [CIImageProcessorInput]?, arguments: [String: Any]?, output: CIImageProcessorOutput) throws { guard let info = arguments?["info"] as? Info else { throw Error.unknown } let width = Int(output.region.width) let height = Int(output.region.height) let baseAddress = output.baseAddress let bytesPerRow = output.bytesPerRow memset(baseAddress, 0, bytesPerRow * height) guard let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.alphaOnly.rawValue) else { throw Error.unknown } context.translateBy(x: -output.region.minX, y: -output.region.minY) context.setBlendMode(.copy) context.setShouldAntialias(info.shouldAntialias) context.addPath(info.path) context.fillPath(using: info.rule) } } #endif
mit
fe2199b511eeaa0bdc6169dd12d8d0b2
37.291139
250
0.683306
4.66821
false
false
false
false
USAssignmentWarehouse/EnglishNow
EnglishNow/Services/FirebaseClient.swift
1
13256
// // FirebaseClient.swift // EnglishNow // // Created by GeniusDoan on 6/29/17. // Copyright © 2017 IceTeaViet. All rights reserved. // import Foundation import Firebase class FirebaseClient { static var shared: FirebaseClient! var dataReference: DatabaseReference! class func configure() { FirebaseApp.configure() shared = FirebaseClient() } init() { dataReference = Database.database().reference() } func saveUserData() { let data = NSKeyedArchiver.archivedData(withRootObject: User.current) let stringData = data.base64EncodedString() DataUtils.saveUser() dataReference.child("data/\(User.current.uid!)").setValue(stringData) } func loadUserData(completion: @escaping (Bool) -> Void) { dataReference.child("data/\(User.current.uid!)").observeSingleEvent(of: .value, with: {(snapshot) in if let dataString = snapshot.value as? String, let data = NSData(base64Encoded: dataString, options: []) { User.current = NSKeyedUnarchiver.unarchiveObject(with: data as Data) as! User completion(true) } else { completion(false) } }) } func loadUserSpeaker(completion: @escaping (Bool) -> Void) { loadUserData(completion: {(exist) in if !exist { completion(false) } else { self.dataReference.child("user_profile/\(User.current.uid!)").observeSingleEvent(of: .value, with: {(snapshot) in if let dictionary = snapshot.value as? NSDictionary { User.current.name = dictionary["username"] as! String User.current.profilePhoto = dictionary["profile_pic"] as! String print(User.current.profilePhoto) completion(true) } }) } }) } func signIn(completion: @escaping (Firebase.User?, Error?) -> Void) { //TODO: Support anonymously sign in Auth.auth().signInAnonymously(completion: { (user, error) in if let user = user { self.dataReference.child("learners/\(user.uid)").observeSingleEvent(of: .value, with: { snapshot in if let value = snapshot.value as? NSObject, value is NSNull { self.dataReference.child("learners/\(user.uid)").updateChildValues(["name": User.current.name]) } }) } completion(user, error) }) } func signIn(email: String, password: String, completion: @escaping (Firebase.User?, Error?) -> Void) { Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in if let user = user { User.current.uid = user.uid User.current.type = UserType.learner //TODO: Change to multi-role User.current.email = email User.current.password = password self.loadUserSpeaker(completion: { (exist) in if !exist { self.saveUserData() } }) completion(user, error) } else { completion(user, error) } }) } func signUp(email: String, password: String, userName: String, skills: [Skill], completion: @escaping (Firebase.User?, Error?) -> Void) { Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in if let user = user { let userRef = Database.database().reference().child("user_profile").child((user.uid)) userRef.child("username").setValue(userName) userRef.child("email").setValue(email) userRef.child("password").setValue(password) userRef.child("profile_pic").setValue("") //save stats numbers userRef.child("drinks").setValue(0) userRef.child("conversations").setValue(0) for item in skills { userRef.child("skill").child(item.name).child("rate_value").setValue(0) } print("Success!") } completion(user, error) }) } func onMatch(completion: @escaping (_ session: String, _ token: String) -> Void) { dataReference.child("available/learners").observeSingleEvent(of: .value, with: {snapshot in if snapshot.hasChildren() { self.onSpeakerMatch(completion: completion) } else { self.onLearnerMatch(completion: completion) } }) } func onSpeakerMatch(completion: @escaping (_ session: String, _ token: String) -> Void) { print("on speaker match") handleLearnerAvailable(completion: completion) } func onLearnerMatch(completion: @escaping (_ session: String, _ token: String) -> Void) { let learnerInfo = ["uid": User.current.uid, "name": User.current.name, "photo": User.current.profilePhoto, "rating": User.current.learnerAverageRating(), "matched": false] as [String : Any] dataReference.child("available/learners/\(User.current.uid!)").updateChildValues(learnerInfo) handleSpeakerAvailable(completion: completion) } func handleSpeakerAvailable(completion: @escaping (_ session: String, _ token: String) -> Void) { dataReference.child("available/learners").child(User.current.uid).observeSingleEvent(of: .childChanged, with: { (snapshot) in if let sessionId = snapshot.value as? String { self.dataReference.child("sessions/\(sessionId)").observeSingleEvent(of: .value, with: { (snapshot) in if let dictionary = snapshot.value as? NSDictionary { Singleton.sharedInstance.partner.uid = dictionary["speakerUid"] as! String Singleton.sharedInstance.partner.name = dictionary["speakerName"] as! String Singleton.sharedInstance.partner.rating = dictionary["speakerRating"] as! Double Singleton.sharedInstance.partner.profilePhoto = dictionary["speakerPhoto"] as! String Singleton.sharedInstance.partner.type = UserType.speaker Singleton.sharedInstance.tokBoxSessionId = sessionId /* HerokuappClient.shared.getSession{(dictionary, error) in if let newDictionary = dictionary { let newSessionId = newDictionary["sessionId"]! if sessionId == newSessionId { let token = newDictionary["token"]! completion(sessionId, token) } } } print("invalid token") */ completion(sessionId, dictionary["learner_token"]! as! String) } }) self.dataReference.child("available/learners/\(User.current.uid!)").setValue(nil) } }) } func handleLearnerAvailable(completion: @escaping (_ session: String, _ token: String) -> Void) { print("in handle") dataReference.child("available/learners").observeSingleEvent(of: .value, with: {snapshot in if let learners = snapshot.value as? NSDictionary { print(learners) if let learnerInfo = learners[learners.allKeys[0]] as? NSDictionary { Singleton.sharedInstance.partner.name = learnerInfo["name"] as! String Singleton.sharedInstance.partner.rating = learnerInfo["rating"] as! Double Singleton.sharedInstance.partner.uid = learnerInfo["uid"] as! String Singleton.sharedInstance.partner.profilePhoto = learnerInfo["photo"] as! String Singleton.sharedInstance.partner.type = UserType.learner self.createSession(completion: completion) } } else { self.handleLearnerAvailable(completion: completion) } }) } func removeHandleSpeakerAvailable() { dataReference.child("available/learners").child(User.current.uid).removeAllObservers() dataReference.child("available/learners").child(User.current.uid).setValue(nil) } func removeHandleLearnerAvailable() { dataReference.child("available/learners").removeAllObservers() } func createSession(completion: @escaping (_ session: String, _ token: String) -> Void) { dataReference.child("user_profile/\(Singleton.sharedInstance.partner.uid!)/username").observeSingleEvent(of: .value, with: {snapshot in Singleton.sharedInstance.partner.name = snapshot.value as! String }) var roomName : String = Singleton.sharedInstance.partner.uid + User.current.uid HerokuappClient.shared.getSession(roomName: roomName){ (dictionary, error) in if let dictionary = dictionary { Singleton.sharedInstance.tokBoxApiKey = dictionary["apiKey"]! let sessionId = dictionary["sessionId"]! let speakerToken = dictionary["token"]! let learnerToken = dictionary["learner_token"]! Singleton.sharedInstance.tokBoxSessionId = sessionId let dictionary = ["session_id" : sessionId, "speaker_token": speakerToken, "learner_token": learnerToken, "learnerUid": Singleton.sharedInstance.partner.uid, "learnerName": Singleton.sharedInstance.partner.name, "learnerRating": Singleton.sharedInstance.partner.rating, "speakerUid": User.current.uid, "speakerName": User.current.name, "speakerRating": User.current.speakerAverageRatings(), "speakerPhoto": User.current.profilePhoto] as [String : Any] self.dataReference.child("sessions/\(sessionId)").updateChildValues(dictionary) self.dataReference.child("available/learners/\(Singleton.sharedInstance.partner.uid!)").updateChildValues(["matched": sessionId]) completion(sessionId, speakerToken) } } } func commitReview(review: Review) { let dictionaryReview = review.dictionary() dataReference.child("rating/\(Singleton.sharedInstance.partner.uid!)/\(Singleton.sharedInstance.tokBoxSessionId!)").setValue(dictionaryReview) } func loadReviews(completion: @escaping (_ reviews: [Review]?) -> Void) { dataReference.child("rating/\(User.current.uid!)").observeSingleEvent(of: .value, with: {snapshot in print(User.current.uid) self.dataReference.child("rating/\(User.current.uid!)").setValue(nil) if let reviewsDictionary = snapshot.value as? NSDictionary { var reviews = [Review]() for index in 0 ..< reviewsDictionary.count { let review = Review(dictionary: reviewsDictionary[reviewsDictionary.allKeys[index]] as! NSDictionary) reviews.append(review) } completion(reviews) self.saveUserData() } else { completion(nil) } }) } func handleReviews() { dataReference.child("rating/\(User.current.uid!)").observe(.value, with: {(snapshot) in print(snapshot.value) if snapshot.value is NSNull { return } self.dataReference.child("rating/\(User.current.uid!)").setValue(nil) if let reviewsDictionary = snapshot.value as? NSDictionary { // var reviews = [Review]() for index in 0 ..< reviewsDictionary.count { let review = Review(dictionary: reviewsDictionary[reviewsDictionary.allKeys[index]] as! NSDictionary) User.current.reviews.insert(review, at: 0) User.current.conversations = User.current.conversations + 1 } // completion(reviews) MessageBox.show(body: "You have new review.") self.saveUserData() } else { // completion(nil) } }) } }
apache-2.0
63d3a3fb6caf9106e102af071f29b02d
45.346154
151
0.549981
5.175713
false
false
false
false
lucosi/RSBarcodes_Swift
Source/RSCodeReaderViewController.swift
2
11395
// // RSCodeReaderViewController.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/12/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit import AVFoundation public class RSCodeReaderViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { public lazy var device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) public lazy var output = AVCaptureMetadataOutput() public lazy var session = AVCaptureSession() var videoPreviewLayer: AVCaptureVideoPreviewLayer? public lazy var focusMarkLayer = RSFocusMarkLayer() public lazy var cornersLayer = RSCornersLayer() public var tapHandler: ((CGPoint) -> Void)? public var barcodesHandler: ((Array<AVMetadataMachineReadableCodeObject>) -> Void)? var ticker: NSTimer? public var isCrazyMode = false var isCrazyModeStarted = false var lensPosition: Float = 0 // MARK: Public methods public func hasFlash() -> Bool { if let device = self.device { return device.hasFlash } return false } public func hasTorch() -> Bool { if let device = self.device { return device.hasTorch } return false } public func toggleTorch() -> Bool { if self.hasTorch() { self.session.beginConfiguration() self.device.lockForConfiguration(nil) if self.device.torchMode == .Off { self.device.torchMode = .On } else if self.device.torchMode == .On { self.device.torchMode = .Off } self.device.unlockForConfiguration() self.session.commitConfiguration() return self.device.torchMode == .On } return false } // MARK: Private methods class func interfaceOrientationToVideoOrientation(orientation : UIInterfaceOrientation) -> AVCaptureVideoOrientation { switch (orientation) { case .Unknown: fallthrough case .Portrait: return AVCaptureVideoOrientation.Portrait case .PortraitUpsideDown: return AVCaptureVideoOrientation.PortraitUpsideDown case .LandscapeLeft: return AVCaptureVideoOrientation.LandscapeLeft case .LandscapeRight: return AVCaptureVideoOrientation.LandscapeRight } } func autoUpdateLensPosition() { self.lensPosition += 0.01 if self.lensPosition > 1 { self.lensPosition = 0 } if device.lockForConfiguration(nil) { self.device.setFocusModeLockedWithLensPosition(self.lensPosition, completionHandler: nil) device.unlockForConfiguration() } if session.running { let when = dispatch_time(DISPATCH_TIME_NOW, Int64(10 * Double(USEC_PER_SEC))) dispatch_after(when, dispatch_get_main_queue(), { self.autoUpdateLensPosition() }) } } func onTick() { if let ticker = self.ticker { ticker.invalidate() } self.cornersLayer.cornersArray = [] } func onTap(gesture: UITapGestureRecognizer) { let tapPoint = gesture.locationInView(self.view) let focusPoint = CGPointMake( tapPoint.x / self.view.bounds.size.width, tapPoint.y / self.view.bounds.size.height) if let device = self.device { if device.lockForConfiguration(nil) { if device.focusPointOfInterestSupported { device.focusPointOfInterest = focusPoint } else { println("Focus point of interest not supported.") } if self.isCrazyMode { if device.isFocusModeSupported(.Locked) { device.focusMode = .Locked } else { println("Locked focus not supported.") } if !self.isCrazyModeStarted { self.isCrazyModeStarted = true dispatch_async(dispatch_get_main_queue(), { () -> Void in self.autoUpdateLensPosition() }) } } else { if device.isFocusModeSupported(.ContinuousAutoFocus) { device.focusMode = .ContinuousAutoFocus } else if device.isFocusModeSupported(.AutoFocus) { device.focusMode = .AutoFocus } else { println("Auto focus not supported.") } } if device.autoFocusRangeRestrictionSupported { device.autoFocusRangeRestriction = .None } else { println("Auto focus range restriction not supported.") } device.unlockForConfiguration() self.focusMarkLayer.point = tapPoint } } if let tapHandler = self.tapHandler { tapHandler(tapPoint) } } func onApplicationWillEnterForeground() { self.session.startRunning() } func onApplicationDidEnterBackground() { self.session.stopRunning() } // MARK: Deinitialization deinit { println("RSCodeReaderViewController deinit") } // MARK: View lifecycle override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let videoPreviewLayer = self.videoPreviewLayer { let videoOrientation = RSCodeReaderViewController.interfaceOrientationToVideoOrientation(UIApplication.sharedApplication().statusBarOrientation) if videoPreviewLayer.connection.supportsVideoOrientation && videoPreviewLayer.connection.videoOrientation != videoOrientation { videoPreviewLayer.connection.videoOrientation = videoOrientation } } } override public func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) let frame = CGRectMake(0, 0, size.width, size.height) if let videoPreviewLayer = self.videoPreviewLayer { videoPreviewLayer.frame = frame } if let focusMarkLayer = self.focusMarkLayer { focusMarkLayer.frame = frame } if let cornersLayer = self.cornersLayer { cornersLayer.frame = frame } } override public func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.clearColor() var error : NSError? let input = AVCaptureDeviceInput(device: self.device, error: &error) if let error = error { println(error.description) return } if let device = self.device { if device.lockForConfiguration(nil) { if self.device.isFocusModeSupported(.ContinuousAutoFocus) { self.device.focusMode = .ContinuousAutoFocus } if self.device.autoFocusRangeRestrictionSupported { self.device.autoFocusRangeRestriction = .Near } self.device.unlockForConfiguration() } } if self.session.canAddInput(input) { self.session.addInput(input) } self.videoPreviewLayer = AVCaptureVideoPreviewLayer(session: session) if let videoPreviewLayer = self.videoPreviewLayer { videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill videoPreviewLayer.frame = self.view.bounds self.view.layer.addSublayer(videoPreviewLayer) } let queue = dispatch_queue_create("com.pdq.rsbarcodes.metadata", DISPATCH_QUEUE_CONCURRENT) self.output.setMetadataObjectsDelegate(self, queue: queue) if self.session.canAddOutput(self.output) { self.session.addOutput(self.output) self.output.metadataObjectTypes = self.output.availableMetadataObjectTypes } let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "onTap:") self.view.addGestureRecognizer(tapGestureRecognizer) self.focusMarkLayer.frame = self.view.bounds self.view.layer.addSublayer(self.focusMarkLayer) self.cornersLayer.frame = self.view.bounds self.view.layer.addSublayer(self.cornersLayer) } override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "onApplicationWillEnterForeground", name:UIApplicationWillEnterForegroundNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "onApplicationDidEnterBackground", name: UIApplicationDidEnterBackgroundNotification, object: nil) self.session.startRunning() } override public func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillEnterForegroundNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidEnterBackgroundNotification, object: nil) self.session.stopRunning() } // MARK: AVCaptureMetadataOutputObjectsDelegate public func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { var barcodeObjects : Array<AVMetadataMachineReadableCodeObject> = [] var cornersArray : Array<[AnyObject]> = [] for metadataObject : AnyObject in metadataObjects { if let videoPreviewLayer = self.videoPreviewLayer { let transformedMetadataObject = videoPreviewLayer.transformedMetadataObjectForMetadataObject(metadataObject as! AVMetadataObject) if transformedMetadataObject.isKindOfClass(AVMetadataMachineReadableCodeObject.self) { let barcodeObject = transformedMetadataObject as! AVMetadataMachineReadableCodeObject barcodeObjects.append(barcodeObject) cornersArray.append(barcodeObject.corners) } } } self.cornersLayer.cornersArray = cornersArray if barcodeObjects.count > 0 { if let barcodesHandler = self.barcodesHandler { barcodesHandler(barcodeObjects) } } dispatch_async(dispatch_get_main_queue(), { () -> Void in if let ticker = self.ticker { ticker.invalidate() } self.ticker = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "onTick", userInfo: nil, repeats: true) }) } }
mit
b2073bf32b70c0c0180d2bc95c83036e
36.983333
172
0.611321
5.981627
false
false
false
false
RevenueCat/purchases-ios
Sources/Purchasing/ProductsManager.swift
1
5959
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // ProductsManager.swift // // Created by Andrés Boedo on 7/14/20. // import Foundation import StoreKit /// Protocol for a type that can fetch and cache ``StoreProduct``s. /// The basic interface only has a completion-blocked based API, but default `async` overloads are provided. protocol ProductsManagerType: Sendable { typealias Completion = (Result<Set<StoreProduct>, PurchasesError>) -> Void @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) typealias SK2Completion = (Result<Set<SK2StoreProduct>, PurchasesError>) -> Void /// Fetches the ``StoreProduct``s with the given identifiers /// The returned products will be SK1 or SK2 backed depending on the implementation and configuration. func products(withIdentifiers identifiers: Set<String>, completion: @escaping Completion) /// Fetches the `SK2StoreProduct`s with the given identifiers. @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) func sk2Products(withIdentifiers identifiers: Set<String>, completion: @escaping SK2Completion) /// Adds the products to the internal cache /// If the type implementing this protocol doesn't have a caching mechanism then this method does nothing. func cache(_ product: StoreProductType) /// Removes all elements from its internal cache /// If the type implementing this protocol doesn't have a caching mechanism then this method does nothing. func clearCache() var requestTimeout: TimeInterval { get } } // MARK: - /// Basic implemenation of a `ProductsManagerType` class ProductsManager: NSObject, ProductsManagerType { private let productsFetcherSK1: ProductsFetcherSK1 private let systemInfo: SystemInfo #if swift(>=5.7) private let _productsFetcherSK2: (any Sendable)? #else private let _productsFetcherSK2: Any? #endif @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) private var productsFetcherSK2: ProductsFetcherSK2 { // swiftlint:disable:next force_cast return self._productsFetcherSK2! as! ProductsFetcherSK2 } init( productsRequestFactory: ProductsRequestFactory = ProductsRequestFactory(), systemInfo: SystemInfo, requestTimeout: TimeInterval ) { self.productsFetcherSK1 = ProductsFetcherSK1(productsRequestFactory: productsRequestFactory, requestTimeout: requestTimeout) self.systemInfo = systemInfo if #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) { self._productsFetcherSK2 = ProductsFetcherSK2() } else { self._productsFetcherSK2 = nil } } func products(withIdentifiers identifiers: Set<String>, completion: @escaping Completion) { if #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *), self.systemInfo.storeKit2Setting == .enabledForCompatibleDevices { self.sk2Products(withIdentifiers: identifiers) { result in completion(result.map { Set($0.map(StoreProduct.from(product:))) }) } } else { self.sk1Products(withIdentifiers: identifiers) { result in completion(result.map { Set($0.map(StoreProduct.init(sk1Product:))) }) } } } @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) func sk2Products(withIdentifiers identifiers: Set<String>, completion: @escaping SK2Completion) { Async.call(with: completion) { do { let products = try await self.productsFetcherSK2.products(identifiers: identifiers) Logger.debug(Strings.storeKit.store_product_request_finished) return Set(products) } catch { Logger.debug(Strings.storeKit.store_products_request_failed(error: error)) throw ErrorUtils.storeProblemError(error: error) } } } // This class does not implement caching. // See `CachingProductsManager`. func cache(_ product: StoreProductType) {} func clearCache() { self.productsFetcherSK1.clearCache() } var requestTimeout: TimeInterval { return self.productsFetcherSK1.requestTimeout } } // MARK: - private private extension ProductsManager { func sk1Products(withIdentifiers identifiers: Set<String>, completion: @escaping (Result<Set<SK1Product>, PurchasesError>) -> Void) { return self.productsFetcherSK1.sk1Products(withIdentifiers: identifiers, completion: completion) } } // MARK: - ProductsManagerType async extension ProductsManagerType { /// `async` overload for `products(withIdentifiers:)` @available(iOS 13.0, tvOS 13.0, watchOS 6.2, macOS 10.15, *) func products(withIdentifiers identifiers: Set<String>) async throws -> Set<StoreProduct> { return try await Async.call { completion in self.products(withIdentifiers: identifiers, completion: completion) } } /// `async` overload for `sk2Products(withIdentifiers:)` @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) func sk2Products(withIdentifiers identifiers: Set<String>) async throws -> Set<SK2StoreProduct> { return try await Async.call { completion in self.sk2Products(withIdentifiers: identifiers, completion: completion) } } } // MARK: - // @unchecked because: // - Class is not `final` (it's mocked). This implicitly makes subclasses `Sendable` even if they're not thread-safe. // However it contains no mutable state, and its members are all `Sendable`. extension ProductsManager: @unchecked Sendable {}
mit
d962aa5dc4c311062c5d4248a5537e68
35.777778
117
0.677409
4.374449
false
false
false
false
february29/Learning
swift/Fch_Contact/Pods/RxSwift/RxSwift/Observables/Range.swift
30
2572
// // Range.swift // RxSwift // // Created by Krunoslav Zaher on 9/13/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType where E : RxAbstractInteger { /** Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages. - seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html) - parameter start: The value of the first integer in the sequence. - parameter count: The number of sequential integers to generate. - parameter scheduler: Scheduler to run the generator loop on. - returns: An observable sequence that contains a range of sequential integral numbers. */ public static func range(start: E, count: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> { return RangeProducer<E>(start: start, count: count, scheduler: scheduler) } } final fileprivate class RangeProducer<E: RxAbstractInteger> : Producer<E> { fileprivate let _start: E fileprivate let _count: E fileprivate let _scheduler: ImmediateSchedulerType init(start: E, count: E, scheduler: ImmediateSchedulerType) { if count < 0 { rxFatalError("count can't be negative") } if start &+ (count - 1) < start { rxFatalError("overflow of count") } _start = start _count = count _scheduler = scheduler } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { let sink = RangeSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } } final fileprivate class RangeSink<O: ObserverType> : Sink<O> where O.E: RxAbstractInteger { typealias Parent = RangeProducer<O.E> private let _parent: Parent init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { return _parent._scheduler.scheduleRecursive(0 as O.E) { i, recurse in if i < self._parent._count { self.forwardOn(.next(self._parent._start + i)) recurse(i + 1) } else { self.forwardOn(.completed) self.dispose() } } } }
mit
4cd802ba1a2e83ae8afff1e305335eb2
34.219178
157
0.638662
4.558511
false
false
false
false
iosliutingxin/DYVeideoVideo
DYZB/PageContentView.swift
1
3721
// // PageContentView.swift // DYZB // // Created by 北京时代华擎 on 17/5/7. // Copyright © 2017年 iOS _Liu. All rights reserved. // import UIKit private let contentCellID = "contentCellID" typealias ContentCurrentPage = (_ index : Int) -> Void class PageContentView: UIView { //2、定义属性 fileprivate var chilVcs : [UIViewController] fileprivate weak var parentViewController : UIViewController? var ContentCurrentPage : ContentCurrentPage? //懒加载属性(弱引用) fileprivate lazy var collectionView : UICollectionView = {[weak self] in //1,创建layout let layout = UICollectionViewFlowLayout() layout.itemSize=(self?.bounds.size)! layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 layout.scrollDirection = .horizontal //2、创建uicollectionview let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contentCellID) return collectionView }() //1、构造函数 init(frame: CGRect,chilVcs : [UIViewController],parentViewController : UIViewController?) { self.chilVcs=chilVcs self.parentViewController=parentViewController super.init(frame : frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //设置UI布局 extension PageContentView { fileprivate func setupUI(){ //1、将子控制器添加到父控制器中 for chilVcv in chilVcs { parentViewController?.addChildViewController(chilVcv) } // 2、添加UIcollectionview,用于在cell中存放控制器view addSubview(collectionView) collectionView.frame = bounds } } //对外暴露的方法 extension PageContentView{ func setCurrentIndex(_ currentIndex:Int){ let offsetx = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x: offsetx, y: 0), animated: false) } } //遵守UICollectionViewDataSource extension PageContentView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return chilVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //创建cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellID, for: indexPath) //給cell设置内容 for view in cell.contentView.subviews { view.removeFromSuperview() } let chidVC = chilVcs[indexPath.item] chidVC.view.frame = cell.contentView.bounds cell.contentView.addSubview(chidVC.view) return cell } } //遵守UICollectionDelegate extension PageContentView : UICollectionViewDelegate{ //滚动开始 func scrollViewDidScroll(_ scrollView: UIScrollView) { let currentPage = floor((scrollView.contentOffset.x - screenW / 2) / screenW) + 1 print("scrollView---\(currentPage)") ContentCurrentPage?(Int(currentPage)) } }
mit
301a2dd0b6892acf7c8a8d29791f3c69
25.125
121
0.654939
5.279346
false
false
false
false
OHeroJ/twicebook
Sources/App/Models/Feedback.swift
1
1371
// // Feedback.swift // App // // Created by laijihua on 08/10/2017. // import Foundation import Vapor import FluentProvider final class Feedback: Model { var userId: Int var content: String let storage: Storage = Storage() struct Key { static let content = "content" static let userId = "user_id" } init(content: String, userId: Int) { self.content = content self.userId = userId } init(row: Row) throws { content = try row.get(Key.content) userId = try row.get(Key.userId) } func makeRow() throws -> Row { var row = Row() try row.set(Key.content, content) try row.set(Key.userId, userId) return row } } extension Feedback: JSONRepresentable { func makeJSON() throws -> JSON { let creater = try User.find(userId) var json = JSON() try json.set(Key.content, content) try json.set("user", creater) return json } } extension Feedback: Preparation { static func prepare(_ database: Database) throws { try database.create(self, closure: { (builder) in builder.id() builder.string(Key.content, length: 500) builder.int(Key.userId) }) } static func revert(_ database: Database) throws { try database.delete(self) } }
mit
016d57279339c745747c00138b77a11b
21.112903
57
0.588621
3.962428
false
false
false
false
DeepLearningKit/DeepLearningKit
iOSDeepLearningKitApp/iOSDeepLearningKitApp/iOSDeepLearningKitApp/ConvolutionLayer.swift
3
10732
// // ConvolutionLayer.swift // MemkiteMetal // // Created by Amund Tveit on 25/11/15. // Copyright © 2015 memkite. All rights reserved. // import Foundation import Metal func getDataFromBlob(blob: NSDictionary) -> ([Float], [Float]) { let shape = blob["shape"] as! NSDictionary let data = blob["data"] as! [Float] var FloatData = createFloatNumbersArray(data.count) for i in 0 ..< data.count { FloatData[i] = data[i] } return (shape["dim"] as! [Float], FloatData) } func createConvolutionLayerCached(layer: NSDictionary, inputBuffer: MTLBuffer, inputShape: [Float], metalCommandQueue: MTLCommandQueue, metalDefaultLibrary:MTLLibrary, metalDevice:MTLDevice, inout layer_data_caches: [Dictionary<String,MTLBuffer>], inout blob_cache: [Dictionary<String,([Float],[Float])>], layer_number: Int, layer_string: String, caching_mode:Bool) -> (MTLBuffer, MTLCommandBuffer, [Float]) { _ = NSDate() // let metalCommandBuffer = metalCommandQueue.commandBuffer() let metalCommandBuffer = metalCommandQueue.commandBufferWithUnretainedReferences() var convolution_params_dict:NSDictionary = NSDictionary() var pad:Float = 0.0 var kernel_size:Float = 1.0 var stride:Float = 1.0 var blobs:[NSDictionary] = [] var weights:[Float] = [] var weight_shape:[Float] = [] var bias_data:[Float] = [] var h:Float = 0.0 var w:Float = 0.0 var result_shape:[Float] = [] var outputCount:Int = 0 var input_dimensions:MetalTensorDimensions = MetalTensorDimensions(n: 0, channels: 0, width: 0, height:0) var weight_dimensions:MetalTensorDimensions = MetalTensorDimensions(n: 0, channels: 0, width: 0, height:0) var result_dimensions:MetalTensorDimensions = MetalTensorDimensions(n: 0, channels: 0, width: 0, height:0) var tensor_dimensions:[MetalTensorDimensions] = [] var col_dimensions:MetalTensorDimensions = MetalTensorDimensions(n: 0, channels: 0, width: 0, height:0) var col_output:[Float] = [] var convolution_params:MetalConvolutionParameters = MetalConvolutionParameters(pad:0, kernel_size: 0, stride: 0) if(!caching_mode) { print("NOTCACHINGMODE") convolution_params_dict = layer["convolution_param"] as! NSDictionary pad = 0.0 kernel_size = 1.0 stride = 1.0 if let val = convolution_params_dict["pad"] as? Float { pad = val } if let val = convolution_params_dict["kernel_size"] as? Float { kernel_size = val } _ = NSDate() if let tmpval = blob_cache[layer_number]["0"] { (weight_shape, weights) = tmpval } else { blobs = layer["blobs"] as! [NSDictionary] (weight_shape, weights) = getDataFromBlob(blobs[0]) blob_cache[layer_number]["0"] = (weight_shape, weights) } blobs = layer["blobs"] as! [NSDictionary] (_, bias_data) = getDataFromBlob(blobs[1]) h = (inputShape[2] + 2 * pad - kernel_size) / stride + 1 w = (inputShape[3] + 2 * pad - kernel_size) / stride + 1 result_shape = [inputShape[0], weight_shape[0], h, w] outputCount = Int(result_shape.reduce(1, combine: *)) // Create input and output vectors, and corresponding metal buffer input_dimensions = MetalTensorDimensions(n: inputShape[0], channels: inputShape[1], width: inputShape[2], height: inputShape[3]) weight_dimensions = MetalTensorDimensions(n: weight_shape[0], channels: weight_shape[1], width: weight_shape[2], height: weight_shape[3]) col_dimensions = MetalTensorDimensions(n: inputShape[0], channels: inputShape[1] * weight_shape[2] * weight_shape[3], width: inputShape[2], height: inputShape[3]) result_dimensions = MetalTensorDimensions(n: result_shape[0], channels: result_shape[1], width: result_shape[2], height: result_shape[3]) tensor_dimensions = [input_dimensions, weight_dimensions, col_dimensions, result_dimensions] col_output = createFloatNumbersArray(Int(col_dimensions.n * col_dimensions.channels * col_dimensions.height * col_dimensions.width)) convolution_params = MetalConvolutionParameters(pad: pad, kernel_size: kernel_size, stride: stride) } let resultBuffer = addConvolutionCommandToCommandBufferCached(metalCommandBuffer, inputBuffer: inputBuffer, im2ColCount: col_output.count, weights: weights, outputCount: outputCount, convolution_params: convolution_params, tensor_dimensions: tensor_dimensions, bias: bias_data, metalDefaultLibrary: metalDefaultLibrary, metalDevice:metalDevice, layer_data_caches: &layer_data_caches, layer_number: layer_number,layer_string: layer_string, caching_mode: caching_mode) //metalCommandBuffer.commit() return (resultBuffer, metalCommandBuffer, result_shape) } func addConvolutionCommandToCommandBufferCached(commandBuffer: MTLCommandBuffer, inputBuffer: MTLBuffer, im2ColCount: Int, weights: [Float], outputCount: Int, convolution_params: MetalConvolutionParameters, tensor_dimensions: [MetalTensorDimensions], bias: [Float], metalDefaultLibrary:MTLLibrary, metalDevice:MTLDevice, inout layer_data_caches: [Dictionary<String,MTLBuffer>], layer_number: Int, layer_string: String, caching_mode:Bool) -> MTLBuffer { _ = NSDate() print("before output and col_output") var output:[Float] = [] var col_output:[Float] = [] if(!caching_mode) { output = createFloatNumbersArray(outputCount) col_output = createFloatNumbersArray(im2ColCount) } print("before setupshaderinpipeline") let (_, im2colComputePipelineState, _) = setupShaderInMetalPipeline("im2col", metalDefaultLibrary: metalDefaultLibrary, metalDevice: metalDevice) let resultMetalBuffer = createOrReuseFloatMetalBuffer("resultMetalBuffer", data: output, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) print("after resultmetalbuffer") let weightMetalBuffer = createOrReuseFloatMetalBuffer("weightMetalBuffer", data: weights, cache: &layer_data_caches, layer_number:layer_number, metalDevice: metalDevice) let convolutionParamsMetalBuffer = createOrReuseConvolutionParametersMetalBuffer("convolutionParamsMetalBuffer", data: convolution_params, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) let tensorDimensionsMetalBuffer = createOrReuseTensorDimensionsVectorMetalBuffer("tensorDimensionsMetalBuffer", data: tensor_dimensions, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) let colOutputMetalBuffer = createOrReuseFloatMetalBuffer("colOutputMetalBuffer", data: col_output, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) let biasMetalBuffer = createOrReuseFloatMetalBuffer("bias", data: bias, cache: &layer_data_caches, layer_number:layer_number, metalDevice: metalDevice) // Create Metal compute command encoder for im2col var metalComputeCommandEncoder = commandBuffer.computeCommandEncoder() metalComputeCommandEncoder.setBuffer(inputBuffer, offset: 0, atIndex: 0) metalComputeCommandEncoder.setBuffer(tensorDimensionsMetalBuffer, offset: 0, atIndex: 1) metalComputeCommandEncoder.setBuffer(convolutionParamsMetalBuffer, offset: 0, atIndex: 2) metalComputeCommandEncoder.setBuffer(colOutputMetalBuffer, offset: 0, atIndex: 3) //metalComputeCommandEncoder.setComputePipelineState(im2colComputePipelineState) // Set the shader function that Metal will use metalComputeCommandEncoder.setComputePipelineState(im2colComputePipelineState) // Set up thread groups on GPU // TODO: check out http://metalbyexample.com/introduction-to-compute/ var threadsPerGroup = MTLSize(width:im2colComputePipelineState.threadExecutionWidth,height:1,depth:1) // ensure at least 1 threadgroup print("before mtlsize 2") var numThreadgroups = MTLSize(width:(col_output.count-1)/im2colComputePipelineState.threadExecutionWidth + 1, height:1, depth:1) metalComputeCommandEncoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerGroup) print("after dispatch") // Finalize configuration metalComputeCommandEncoder.endEncoding() let (_, convolutionComputePipelineState, _) = setupShaderInMetalPipeline("convolution_layer", metalDefaultLibrary: metalDefaultLibrary, metalDevice: metalDevice) metalComputeCommandEncoder = commandBuffer.computeCommandEncoder() // Create Metal Compute Command Encoder and add input and output buffers to it metalComputeCommandEncoder.setBuffer(resultMetalBuffer, offset: 0, atIndex: 0) metalComputeCommandEncoder.setBuffer(weightMetalBuffer, offset: 0, atIndex: 1) metalComputeCommandEncoder.setBuffer(tensorDimensionsMetalBuffer, offset: 0, atIndex: 2) metalComputeCommandEncoder.setBuffer(colOutputMetalBuffer, offset: 0, atIndex: 3) metalComputeCommandEncoder.setBuffer(biasMetalBuffer, offset: 0, atIndex: 4) // Set the shader function that Metal will use metalComputeCommandEncoder.setComputePipelineState(convolutionComputePipelineState) // Set up thread groups on GPU // TODO: check out http://metalbyexample.com/introduction-to-compute/ threadsPerGroup = MTLSize(width:convolutionComputePipelineState.threadExecutionWidth,height:1,depth:1) // ensure at least 1 threadgroup numThreadgroups = MTLSize(width:(outputCount-1)/convolutionComputePipelineState.threadExecutionWidth + 1, height:1, depth:1) metalComputeCommandEncoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerGroup) // Finalize configuration metalComputeCommandEncoder.endEncoding() return resultMetalBuffer }
apache-2.0
6de17a9f418b9f1170483c21e0a1ef70
47.121076
474
0.67114
5.088193
false
false
false
false