repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 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
Antondomashnev/Sourcery
SourceryTests/Stub/Performance-Code/Kiosk/App/Views/RegisterFlowView.swift
2
3882
import UIKit import ORStackView import RxSwift class RegisterFlowView: ORStackView { let highlightedIndex = Variable(0) lazy var appSetup: AppSetup = .sharedState var details: BidDetails? { didSet { update() } } override func awakeFromNib() { super.awakeFromNib() backgroundColor = .white bottomMarginHeight = CGFloat(NSNotFound) updateConstraints() } fileprivate struct SubViewParams { let title: String let getters: Array<(NewUser) -> String?> } fileprivate lazy var subViewParams: Array<SubViewParams> = { return [ [SubViewParams(title: "Mobile", getters: [ { $0.phoneNumber.value }])], [SubViewParams(title: "Email", getters: [ { $0.email.value }])], [SubViewParams(title: "Postal/Zip", getters: [ { $0.zipCode.value }])].filter { _ in self.appSetup.needsZipCode }, [SubViewParams(title: "Credit Card", getters: [ { $0.creditCardName.value }, { $0.creditCardType.value }])] ].flatMap {$0} }() func update() { let user = details!.newUser removeAllSubviews() for (i, subViewParam) in subViewParams.enumerated() { let itemView = ItemView(frame: bounds) itemView.createTitleViewWithTitle(subViewParam.title) addSubview(itemView, withTopMargin: "10", sideMargin: "0") if let value = (subViewParam.getters.flatMap { $0(user) }.first) { itemView.createInfoLabel(value) let button = itemView.createJumpToButtonAtIndex(i) button.addTarget(self, action: #selector(pressed(_:)), for: .touchUpInside) itemView.constrainHeight("44") } else { itemView.constrainHeight("20") } if i == highlightedIndex.value { itemView.highlight() } } let spacer = UIView(frame: bounds) spacer.setContentHuggingPriority(12, for: .horizontal) addSubview(spacer, withTopMargin: "0", sideMargin: "0") bottomMarginHeight = 0 } func pressed(_ sender: UIButton!) { highlightedIndex.value = sender.tag } class ItemView: UIView { var titleLabel: UILabel? func highlight() { titleLabel?.textColor = .artsyPurpleRegular() } func createTitleViewWithTitle(_ title: String) { let label = UILabel(frame: bounds) label.font = UIFont.sansSerifFont(withSize: 16) label.text = title.uppercased() titleLabel = label addSubview(label) label.constrainWidth(to: self, predicate: "0") label.alignLeadingEdge(with: self, predicate: "0") label.alignTopEdge(with: self, predicate: "0") } func createInfoLabel(_ info: String) { let label = UILabel(frame: bounds) label.font = UIFont.serifFont(withSize: 16) label.text = info addSubview(label) label.constrainWidth(to: self, predicate: "-52") label.alignLeadingEdge(with: self, predicate: "0") label.constrainTopSpace(to: titleLabel!, predicate: "8") } func createJumpToButtonAtIndex(_ index: NSInteger) -> UIButton { let button = UIButton(type: .custom) button.tag = index button.setImage(UIImage(named: "edit_button"), for: .normal) button.isUserInteractionEnabled = true button.isEnabled = true addSubview(button) button.alignTopEdge(with: self, predicate: "0") button.alignTrailingEdge(with: self, predicate: "0") button.constrainWidth("36") button.constrainHeight("36") return button } } }
mit
62f05a2d340533b1f5486723603d91a6
30.306452
126
0.581144
4.757353
false
false
false
false
LearningSwift2/LearningApps
SimpleTableViewKeyboard/SimpleTableView/MovieTableViewController.swift
1
1676
// // MovieTableViewController.swift // SimpleTableView // // Created by Phil Wright on 1/1/16. // Copyright © 2016 Touchopia, LLC. All rights reserved. // import UIKit class MovieTableViewController: UITableViewController, UITextFieldDelegate { override func viewDidLoad() { super.viewDidLoad() let center = NSNotificationCenter.defaultCenter() center.addObserver(self, selector: #selector(MovieTableViewController.keyboardWillShow(_:)), name:UIKeyboardWillShowNotification, object: nil) center.addObserver(self, selector: #selector(MovieTableViewController.keyboardWillHide(_:)), name:UIKeyboardWillHideNotification, object: nil) // Adjust for status bar self.tableView.contentInset = UIEdgeInsets(top: 44, left: 0, bottom: 0, right: 0) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 3 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 9 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("MovieCell", forIndexPath: indexPath) as! MovieTableViewCell cell.configureCell("Enter Text",viewController: self) return cell } func keyboardWillShow(sender: NSNotification) { self.view.frame.origin.y = -150 } func keyboardWillHide(sender: NSNotification) { self.view.frame.origin.y = 0 } }
apache-2.0
858a7a4b52c693342e53b3e23c67a22b
31.211538
150
0.679403
5.385852
false
false
false
false
GeekerHua/GHSwiftTest
01-员工管理SQlite/01-员工管理/SQLite.swift
1
4048
// // SQLite.swift // 01-员工管理 // // Created by GeekerHua on 15/12/24. // Copyright © 2015年 GeekerHua. All rights reserved. // import Foundation // 数据库操作 /** 1. 打开数据库 2. 如果没有数据表,先创表 3.数据操作 */ class SQLite { private static let instance = SQLite() class var sharedSQLite: SQLite { return instance } var db : COpaquePointer = nil func openDataBase(dbname: String) -> Bool { let path = dbname.documentPath() print(path) if sqlite3_open(path, &db) == SQLITE_OK { print("打开数据库成功") if createTable() { print("创建数据表成功") // 测试查询数据 // let sql = "SELECT id, DepartmentNo, Name FROM T_Department" // recordSet(sql) } else { print("创建数据表失败") } } else { print("打开数据库失败") } return false } func createTable() -> Bool { // 准备所有数据表的SQL let sql = "CREATE TABLE \n" + "IF NOT EXISTS T_Department (\n" + "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" + "DepartmentNo CHAR(10) NOT NULL DEFAULT '',\n" + "Name CHAR(50) NOT NULL DEFAULT '' \n" + "); \n" + "CREATE TABLE IF NOT EXISTS T_Employee ( \n" + "'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, \n" + "'name' TEXT NOT NULL, \n" + "'age' INTEGER NOT NULL, \n" + "'department_id' INTEGER, \n" + "CONSTRAINT 'FK_DEP_ID' FOREIGN KEY ('department_id') REFERENCES 'T_Department' ('id') \n" + ");" return execSQL(sql) } // 执行没有返回值的SQL语句 func execSQL(sql:String) -> Bool{ return sqlite3_exec(db, sql.cStringUsingEncoding(NSUTF8StringEncoding)!, nil, nil, nil) == SQLITE_OK } // 执行SQL,返回一个结果集(OC对象数组) func recordSet(sql: String) -> [AnyObject]?{ // 1.准备语句 var stmt: COpaquePointer = nil var recordList : [AnyObject]? if sqlite3_prepare_v2(db, sql.cStringUsingEncoding(NSUTF8StringEncoding)!, -1, &stmt, nil) == SQLITE_OK { // 查询结果的数组 recordList = [AnyObject]() // 单步获取SQL执行结果 while sqlite3_step(stmt) == SQLITE_ROW { // 获取每一条记录的返回值 recordList!.append(recordData(stmt)) } } // 释放语句 sqlite3_finalize(stmt) return recordList } // 获取每一条数据的记录 func recordData(stmt: COpaquePointer) -> AnyObject{ // 获取到记录 let count = sqlite3_column_count(stmt) // print("获取到记录,共有多少列\(count)") // 利用一个数组所有数据 var data = [AnyObject]() for i in 0..<count { let type = sqlite3_column_type(stmt, i) switch type { case SQLITE_INTEGER: data.append(Int(sqlite3_column_int64(stmt, i))) // print("整数 \(sqlite3_column_int64(stmt, i))") case SQLITE_FLOAT: data.append(sqlite3_column_double(stmt, i)) // print("小树 \(sqlite3_column_double(stmt, i))") case SQLITE_NULL: data.append(NSNull()) // print("空\(NSNull())") case SQLITE_TEXT: let chars = UnsafePointer<CChar>(sqlite3_column_text(stmt, i)) let str = String(CString: chars, encoding: NSUTF8StringEncoding) data.append(str!) // print("字符串\(str!)") case let type: print("不支持的类型\(type)") } // print(sqlite3_column_type(stmt, i)) } return data } }
mit
affcc6d63673ab5ffda775a7a8ea0015
29.221311
113
0.507187
3.964516
false
false
false
false
shyn/cs193p
Caculator/CacultorBrain.swift
1
4445
// // CacultorBrain.swift // Caculator // // Created by deepwind on 4/16/17. // Copyright © 2017 deepwind. All rights reserved. // import Foundation class caculatorBrain { // acess control strategy private enum Op: CustomStringConvertible { case Operand(Double) case BinaryOperation(String, (Double, Double)->Double) case UnaryOperation(String, (Double)->Double) case ZeroOperation(String, Double) // add read only computed property var description: String { get { switch self { case .Operand(let operand): return "\(operand)" case .BinaryOperation(let symbol, _): return symbol case .UnaryOperation(let symbol, _): return symbol case .ZeroOperation(let symbol, _): return symbol } } } } // emum can have accoiated values and contains only computed property private var opStack = [Op]() private var knownOps = [String:Op]() init() { func learnOp(op: Op) { knownOps[op.description] = op } learnOp(op: Op.BinaryOperation("*", *)) // 这样既利用了 __str__ 也使的这里的注册代码不再需要输入2次运算符! Brilliant knownOps["÷"] = Op.BinaryOperation("÷") { $1 / $0 } knownOps["+"] = Op.BinaryOperation("+", +) knownOps["−"] = Op.BinaryOperation("−") { $1 - $0 } knownOps["√"] = Op.UnaryOperation("√", sqrt) knownOps["sin"] = Op.UnaryOperation("sin", sin) knownOps["cos"] = Op.UnaryOperation("cos", cos) knownOps["π"] = Op.ZeroOperation("π", Double.pi) } // // typealias PropertyList = AnyObject // // var program: PropertyList { // get { // return opStack.map { $0.description } // This goes wrong with swift 3.1 :( // } // set { // if let symbolList = newValue as? Array<String> { // var newOpStack = [Op]() // for symbol in symbolList { // if let myOp = knownOps[symbol] { // newOpStack.append(myOp) // }else{ // if let newNum = NumberFormatter().number(from: symbol)?.doubleValue{ // opStack.append(.Operand(newNum)) // } // } // } // opStack = newOpStack // } // } // } // func evaluate() -> Double? { let (result, remainder) = evaluate(ops: opStack) print("\(opStack) = \(String(describing: result)) and \(remainder)") return result } // array and dictionary in swift are structs which passed by value private func evaluate( ops: [Op]) -> (result: Double?, remainingOps: [Op]) { if !ops.isEmpty { var remainingOps = ops let op = remainingOps.removeLast() switch op { case .Operand(let operand): return (operand, remainingOps) case .UnaryOperation(_, let operation): let operandEvaluation = evaluate(ops: remainingOps) if let operand = operandEvaluation.result { return (operation(operand), operandEvaluation.remainingOps) } case .BinaryOperation(_, let operation): let op1Evaluation = evaluate(ops: remainingOps) if let operand1 = op1Evaluation.result { let op2Evaluation = evaluate(ops: op1Evaluation.remainingOps) if let operand2 = op2Evaluation.result { return (operation(operand1, operand2), op2Evaluation.remainingOps) } } case .ZeroOperation(_, let value): return (value, remainingOps) } } return (nil, ops) } func pushOperand(operand: Double) -> Double? { opStack.append(Op.Operand(operand)) return evaluate() } func performOperation(symbol: String) -> Double? { if let operation = knownOps[symbol] { opStack.append(operation) } return evaluate() } func clearOpStack() { opStack.removeAll() } }
mit
7f65bf573dc1004a07bbe3e26bbf56bb
32.937984
98
0.514847
4.560417
false
false
false
false
LQJJ/demo
86-DZMeBookRead-master/DZMeBookRead/DZMeBookRead/view/DZMReadViewCell.swift
1
1705
// // DZMReadViewCell.swift // DZMeBookRead // // Created by 邓泽淼 on 2017/5/15. // Copyright © 2017年 DZM. All rights reserved. // import UIKit class DZMReadViewCell: UITableViewCell { /// 阅读View 显示使用 private(set) var readView:DZMReadView! /// 当前的显示的内容 var content:String! { didSet{ if !content.isEmpty { // 有值 readView.content = content } } } class func cellWithTableView(_ tableView:UITableView) ->DZMReadViewCell { let ID = "DZMReadViewCell" var cell = tableView.dequeueReusableCell(withIdentifier: ID) as? DZMReadViewCell if (cell == nil) { cell = DZMReadViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: ID) } return cell! } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none backgroundColor = UIColor.clear addSubViews() } func addSubViews() { // 阅读View readView = DZMReadView() readView.backgroundColor = UIColor.clear contentView.addSubview(readView) } override func layoutSubviews() { super.layoutSubviews() // 布局 readView.frame = GetReadViewFrame() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
663fc677efb7d3f1c817d550a3e6b3e0
21.08
93
0.541667
4.899408
false
false
false
false
Harshvk/T20Exibition
T20Exibition/T20Exibition/FavouritesVC.swift
1
1719
import UIKit class FavouritesVC: UIViewController { var favData = [ImageInfo]() @IBOutlet weak var favouriteCollection: UICollectionView! override func viewDidLoad() { super.viewDidLoad() self.favouriteCollection.delegate = self self.favouriteCollection.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } class FavouriteCell : UICollectionViewCell { @IBOutlet weak var favPics: UIImageView! } extension FavouritesVC : UICollectionViewDataSource ,UICollectionViewDelegate ,UICollectionViewDelegateFlowLayout{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return favData.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FavouriteCell", for: indexPath) as! FavouriteCell return cell } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath){ guard let favCell = cell as? FavouriteCell else { return } let picURL = URL(string : favData[indexPath.row].previewURL) favCell.favPics.af_setImage(withURL: picURL!) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{ return CGSize(width: 108, height: 129) } }
mit
b105fc76259662bdee43275bf8c9b159
27.65
159
0.681792
6.117438
false
false
false
false
stripe/stripe-ios
StripeCore/StripeCore/Source/Coder/StripeCodable.swift
1
5501
// // StripeCodable.swift // StripeCore // // Created by David Estes on 7/20/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // // This contains ~most of our custom encoding/decoding logic for handling unknown fields. // // It isn't intended for public use, but exposing objects with this protocol // requires that we make the protocol itself public. // import Foundation /// A Decodable object that retains unknown fields. /// :nodoc: public protocol UnknownFieldsDecodable: Decodable { /// This should not be used directly. /// Use the `allResponseFields` accessor instead. /// :nodoc: var _allResponseFieldsStorage: NonEncodableParameters? { get set } } /// An Encodable object that allows unknown fields to be set. /// :nodoc: public protocol UnknownFieldsEncodable: Encodable { /// This should not be used directly. /// Use the `additionalParameters` accessor instead. /// :nodoc: var _additionalParametersStorage: NonEncodableParameters? { get set } } /// A Codable enum that sets an "unparsable" case /// instead of failing on values that are unknown to the SDK. /// :nodoc: public protocol SafeEnumCodable: Codable { /// If the value is unparsable, the result will be available in /// the `allResponseFields` of the parent object. static var unparsable: Self { get } // It'd be nice to include the value of the unparsable enum // as an associated value, but Swift can't auto-generate the Codable // keys if we do that. } extension UnknownFieldsDecodable { /// A dictionary containing all response fields from the original JSON, /// including unknown fields. public internal(set) var allResponseFields: [String: Any] { get { self._allResponseFieldsStorage?.storage ?? [:] } set { if self._allResponseFieldsStorage == nil { self._allResponseFieldsStorage = NonEncodableParameters() } self._allResponseFieldsStorage!.storage = newValue } } static func decodedObject(jsonData: Data) throws -> Self { return try StripeJSONDecoder.decode(jsonData: jsonData) } } extension UnknownFieldsEncodable { /// You can use this property to add additional fields to an API request that /// are not explicitly defined by the object's interface. /// /// This can be useful when using beta features that haven't been added to the Stripe SDK yet. /// For example, if the /v1/tokens API began to accept a beta field called "test_field", /// you might do the following: /// /// ```swift /// var cardParams = PaymentMethodParams.Card() /// // add card values /// cardParams.additionalParameters = ["test_field": "example_value"] /// PaymentsAPI.shared.createToken(withParameters: cardParams completion:...) /// ``` public var additionalParameters: [String: Any] { get { self._additionalParametersStorage?.storage ?? [:] } set { if self._additionalParametersStorage == nil { self._additionalParametersStorage = NonEncodableParameters() } self._additionalParametersStorage!.storage = newValue } } } extension Encodable { func encodeJSONDictionary(includingUnknownFields: Bool = true) throws -> [String: Any] { let encoder = StripeJSONEncoder() return try encoder.encodeJSONDictionary( self, includingUnknownFields: includingUnknownFields ) } } @_spi(STP) public enum UnknownFieldsCodableFloats: String { case PositiveInfinity = "Inf" case NegativeInfinity = "-Inf" case NaN = "nan" } /// A protocol that conforms to both UnknownFieldsEncodable and UnknownFieldsDecodable. /// :nodoc: public protocol UnknownFieldsCodable: UnknownFieldsEncodable, UnknownFieldsDecodable {} /// This should not be used directly. /// Use the `additionalParameters` and `allResponseFields` accessors instead. /// :nodoc: public struct NonEncodableParameters { @_spi(STP) public internal(set) var storage: [String: Any] = [:] } extension NonEncodableParameters: Decodable { /// :nodoc: public init( from decoder: Decoder ) throws { // no-op } } extension NonEncodableParameters: Encodable { /// :nodoc: public func encode(to encoder: Encoder) throws { // no-op } } extension NonEncodableParameters: Equatable { /// :nodoc: public static func == (lhs: NonEncodableParameters, rhs: NonEncodableParameters) -> Bool { return NSDictionary(dictionary: lhs.storage).isEqual(to: rhs.storage) } } // The default debugging behavior for structs is to print *everything*, // which is undesirable as it could contain card numbers or other PII. // For now, override it to just give an overview of the struct. extension NonEncodableParameters: CustomStringConvertible, CustomDebugStringConvertible, CustomLeafReflectable { /// :nodoc: public var customMirror: Mirror { return Mirror(reflecting: self.description) } /// :nodoc: public var debugDescription: String { return description } /// :nodoc: public var description: String { return "\(storage.count) fields" } } extension StripeJSONDecoder { static func decode<T: Decodable>(jsonData: Data) throws -> T { let decoder = StripeJSONDecoder() return try decoder.decode(T.self, from: jsonData) } }
mit
116e9575b3a43b20ec7088a30614d36c
30.976744
98
0.674545
4.737295
false
false
false
false
azimin/Rainbow
Rainbow/Color.swift
1
4637
// // ColorBase.swift // Rainbow // // Created by Alex Zimin on 18/01/16. // Copyright © 2016 Alex Zimin. All rights reserved. // import UIKit enum RGB: String { case Red case Blue case Green } struct ColorCollection { var baseColor: UIColor var rule: (() -> ())? } public struct Color { var RGBVector: Vector3D var alpha: Float = 1.0 init() { RGBVector = Vector3D(x: 1.0, y: 1.0, z: 1.0) } init(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat = 1.0) { RGBVector = Vector3D(x: red.toFloat(), y: green.toFloat(), z: blue.toFloat()) self.alpha = alpha.toFloat() } init(red: Double, green: Double, blue: Double, alpha: Double = 1.0) { RGBVector = Vector3D(x: red.toFloat(), y: green.toFloat(), z: blue.toFloat()) self.alpha = alpha.toFloat() } init(red: Float, green: Float, blue: Float, alpha: Float = 1.0) { RGBVector = Vector3D(x: red, y: green, z: blue) self.alpha = alpha } init(color: UIColor) { let cgColor = color.CGColor let numberOfComponents = CGColorGetNumberOfComponents(cgColor) let components = CGColorGetComponents(cgColor) let red, green, blue, alpha: CGFloat if numberOfComponents == 4 { red = components[0] green = components[1] blue = components[2] alpha = components[3] } else { red = components[0] green = components[0] blue = components[0] alpha = components[1] } self.init(red: red, green: green, blue: blue, alpha: alpha) } init?(color: UIColor?) { guard let color = color else { return nil } self.init(color: color) } init(hexString: String) { var hex = hexString if hex.hasPrefix("#") { hex = hex.substringFromIndex(hex.startIndex.advancedBy(1)) } if Color.isHexString(hex) { if hex.characters.count == 3 { let redHex = hex.substringToIndex(hex.startIndex.advancedBy(1)) let greenHex = hex.substringWithRange(Range<String.Index>(hex.startIndex.advancedBy(1)..<hex.startIndex.advancedBy(2))) let blueHex = hex.substringFromIndex(hex.startIndex.advancedBy(2)) hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex } let redHex = hex.substringToIndex(hex.startIndex.advancedBy(2)) let greenHex = hex.substringWithRange(Range<String.Index>(hex.startIndex.advancedBy(2)..<hex.startIndex.advancedBy(4))) let blueHex = hex.substringWithRange(Range<String.Index>(hex.startIndex.advancedBy(4)..<hex.startIndex.advancedBy(6))) var redInt: CUnsignedInt = 0 var greenInt: CUnsignedInt = 0 var blueInt: CUnsignedInt = 0 NSScanner(string: redHex).scanHexInt(&redInt) NSScanner(string: greenHex).scanHexInt(&greenInt) NSScanner(string: blueHex).scanHexInt(&blueInt) self.init(red: CGFloat(redInt) / 255.0, green: CGFloat(greenInt) / 255.0, blue: CGFloat(blueInt) / 255.0, alpha: 1.0) } else { self.init() } } static func isHexString(hexString: String) -> Bool { var hex = hexString if hex.hasPrefix("#") { hex = hex.substringFromIndex(hex.startIndex.advancedBy(1)) } return (hex.rangeOfString("(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)", options: .RegularExpressionSearch) != nil) } func colorWithAlphaComponent(alpha: Float) -> Color { return Color(red: self.red(), green: self.green(), blue: self.blue(), alpha: alpha) } var name: String { return ColorNamesCollection.getColorName(self) } var hexString: String { let r: Float = self.red() let g: Float = self.green() let b: Float = self.blue() return String(format: "%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255)) } var UIColorValue: UIColor { return UIColor(red: red(), green: green(), blue: blue(), alpha: alpha.toCGFloat()) } var CGColorValue: CGColor { return CGColorCreate(CGColorSpaceCreateDeviceRGB(), [self.red(), self.green(), self.blue(), self.alpha.toCGFloat()])! } var RGBClass: RGB { var result: RGB = .Red var minimalValue = ColorCompare(firstColor: self, secondColor: Color.redColor()).CIE76 let greenValue = ColorCompare(firstColor: self, secondColor: Color.greenColor()).CIE76 if greenValue < minimalValue { minimalValue = greenValue result = .Green } let blueValue = ColorCompare(firstColor: self, secondColor: Color.blueColor()).CIE76 if blueValue < minimalValue { minimalValue = greenValue result = .Blue } return result } }
mit
1784e300fb725791de7bdcc470474821
27.98125
127
0.631363
3.793781
false
false
false
false
austinzheng/swift-compiler-crashes
crashes-duplicates/08813-llvm-errs.swift
11
2316
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing typealias F = 1 struct c<T where g.d: String { var d { struct d<T : String { var d { func c>() { let c = f.c = F>() { enum S<T : e typealias F = c(x: A.b(x: I.d<T : String { func b class C<d { st func b: String { let c = F>: I.d: I.b<T where g.e = F> class A {} let c = F> enum S<T : I.e where I.e = 1 var d : e class A { import CoreData func c <d { for b in c } class A { } func c<T where H.e where I.b<T where I.d<c class func c(x: String { class C<T where g: e, g.e where I.b> { class A { struct S<c<T where H.h == 1 typealias F = 1 func c st class A { } enum S<T where S<f : Range<d : e func b<d { struct S.h == f.c { func b struct c<T where I.h> U) { class func c<T where I.d: e func b<T : e = f.h == f: T> struct S.d: Any) -> Self struct c func c<T : e enum S<d : NSObject { <T where S<d {} struct S<T : I.e = c>(") struct d.h> { import CoreData class A { class func b([Void{ protocol B : I.e where g: e, g: String { typealias F = c<T : String { protocol B : NSObject { protocol B : T>: C { struct d: A.d.b: a {} struct S<T where S<d { if true { func b> U) { class A { let c = f: e, g.e where I.b> { struct S.d.e = 1 struct c<T where S<T where H.h : Any) { typealias f = f.h> { enum S<T where I.e = c>: NSObject { } var d { typealias F = b class A { typealias f : e class A { var f = b: a { } var d { for b in c<d { st st } typealias F = 0 func c(([Void{ func c> import CoreData class func b() { enum S.h == c<T where g: e where g: I.h> U) { protocol B : NSObject { (([Void{ let c { protocol B : e where I.d: A.d<T where I.c = b> U) { class C<T where S<d { func b<d : I.d.h> U) { if true { enum S<d { func c>: T>(") protocol B : C { func c>([Void{} struct c typealias f = F>() -> U) { class func c<T : T>: NSObject { func c<T where I.d.h == f.e = c() -> Self var f = F> for b in c<T where S<T where S<T where I.e where I.e = 1 func b struct S<T where I.e where g: Any) -> Self (((x: e, g.d.e = f.b(x: String { func b([Void{ <f : e, g.h == c<T where g.e = 1 enum S.h == f.d<d {} import CoreData let c = e class C<f = e enum S<T where H.h == f: e let c { var f : String { if true { (() -> Self } typealias f : I.d: f.e where g.e = f: NSObject
mit
5a5dda30d0e962d1a3a972c2c4b822e2
17.829268
87
0.592832
2.34413
false
false
false
false
iCodeForever/ifanr
ifanr/ifanr/Views/HomeView/HomeLatestDataCell.swift
1
5647
// // HomeLatestDataCell.swift // ifanr // // Created by 梁亦明 on 16/7/7. // Copyright © 2016年 ifanrOrg. All rights reserved. // import Foundation // 数读 class HomeLatestDataCell: UITableViewCell, Reusable { class func cellWithTableView(_ tableView: UITableView) -> HomeLatestDataCell { var cell = tableView.dequeueReusableCell() as HomeLatestDataCell? if cell == nil { cell = HomeLatestDataCell(style: .default, reuseIdentifier: HomeLatestDataCell.reuseIdentifier) } return cell! } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none self.contentView.addSubview(authorImageView) self.contentView.addSubview(dateLabel) self.contentView.addSubview(likeLabel) self.contentView.addSubview(likeImageView) self.contentView.addSubview(numberLabel) self.contentView.addSubview(titleLabel) self.contentView.addSubview(introduceLabel) self.contentView.layer.addSublayer(cellBottomLine) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var popularLayout: HomePopularLayout! { didSet { // 设置图片位置 authorImageView.frame = popularLayout.kHomeCellAuthorImgRect // 设置分类和时间 let dateAttributeText = NSMutableAttributedString(string: "\(popularLayout.model.category) | \(Date.getCommonExpressionOfDate(popularLayout.model.pubDate))") dateAttributeText.addAttribute(NSForegroundColorAttributeName, value: UIConstant.UI_COLOR_RedTheme, range: NSRange(location: 0, length: 2)) dateLabel.attributedText = dateAttributeText dateLabel.frame = popularLayout.kHomeCellDateRect // 喜欢数 likeLabel.text = "\(popularLayout.model.like)" likeLabel.frame = popularLayout.kHomeCellLikeRect likeImageView.frame = popularLayout.kHomeCellLikeImgRect // 数字 let numberAttributeText = NSMutableAttributedString(string: "\(popularLayout.model.number) \(popularLayout.model.subfix)") numberAttributeText.addAttribute(NSFontAttributeName, value: UIFont.customFont_FZLTZCHJW(fontSize: 40), range: NSRange(location: 0, length: popularLayout.model.number.length)) numberLabel.attributedText = numberAttributeText numberLabel.frame = popularLayout.kHomeCellNumberRect // 标题 self.titleLabel.attributedText = NSMutableAttributedString.attribute(popularLayout.model.title) self.titleLabel.frame = popularLayout.kHomeCellTitleRect // 引文 introduceLabel.attributedText = NSMutableAttributedString.attribute(popularLayout.model.content.replacingOccurrences(of: "<p>", with: "").replacingOccurrences(of: "</p>", with: "")) introduceLabel.frame = popularLayout.kHomeCellTextRect // 底部横线 cellBottomLine.frame = CGRect(x: UIConstant.UI_MARGIN_20, y: popularLayout.cellHeight-1, width: self.width-2*UIConstant.UI_MARGIN_20, height: 1) } } //MARK: --------------------------- Getter and Setter -------------------------- /// 作者图片 fileprivate lazy var authorImageView: UIImageView = { var authorImageView = UIImageView() authorImageView.image = UIImage(named: "ic_shudu") authorImageView.contentMode = .scaleAspectFit return authorImageView }() /// 分类 和 时间 fileprivate lazy var dateLabel: UILabel = { var dateLabel = UILabel() dateLabel.textColor = UIConstant.UI_COLOR_GrayTheme dateLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: 12) return dateLabel }() /// 喜欢数 fileprivate lazy var likeLabel: UILabel = { var likeLabel = UILabel() likeLabel.textColor = UIConstant.UI_COLOR_GrayTheme likeLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: 12) return likeLabel }() fileprivate lazy var likeImageView: UIImageView = { var likeImage = UIImageView(image: UIImage(named: "heart_selected_false")) likeImage.contentMode = .scaleAspectFit return likeImage }() /// 数字 fileprivate lazy var numberLabel: UILabel = { var numberLabel = UILabel() numberLabel.textColor = UIColor.black numberLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: 18) return numberLabel }() /// 标题 fileprivate lazy var titleLabel: UILabel = { var titleLabel = UILabel() titleLabel.numberOfLines = 0 titleLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: 16) titleLabel.textColor = UIConstant.UI_COLOR_RedTheme return titleLabel }() /// 引文 fileprivate lazy var introduceLabel: UILabel = { var introduceLabel = UILabel() introduceLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: 12) introduceLabel.numberOfLines = 0 introduceLabel.textColor = UIConstant.UI_COLOR_GrayTheme return introduceLabel }() /// 底部分割线 fileprivate lazy var cellBottomLine: CALayer = { var cellBottomLine = CALayer() cellBottomLine.backgroundColor = UIConstant.UI_COLOR_GrayTheme.cgColor return cellBottomLine }() }
mit
c7420218a8524141492839d458746043
38.262411
193
0.65336
5.074244
false
false
false
false
BenziAhamed/Nevergrid
NeverGrid/Source/ThemeManager.swift
1
5528
// // ThemeManager.swift // MrGreen // // Created by Benzi on 29/08/14. // Copyright (c) 2014 Benzi Ahamed. All rights reserved. // import Foundation import UIKit import SpriteKit class ThemeSettings { var enableShadows:Bool = false var textureExtension:String = "" var blendMode:SKBlendMode = SKBlendMode.Screen var backgroundTexture:String = "" // TODO: remove var mainmenuImage:String = "" var gameplayImage:String = "" var cellSpacing:CGFloat = 0.0 var cellExtends:CGFloat = 0.125 // in % of total size var cellColorBlendFactor:CGFloat = 1.0 var colorizeCells:Bool = true var cellColors:[UIColor]! var wallColor:UIColor! var titleColor:UIColor = UIColor.whiteColor() var ignoreBlocks:Bool = false init() { } } class ThemeManager { var settings:ThemeSettings init(_ settings:ThemeSettings) { // var settings = ThemeSettings() // // settings.mainmenuImage = "background_darkblue" // settings.gameplayImage = "background_darkblue" // // settings.wallColor = UIColor(red: 74, green: 74, blue: 74) // // settings.cellColors = [ // UIColor.whiteColor() // ,UIColor.whiteColor().colorWithShadow(0.05) // ] // // settings.blendMode = SKBlendMode.Alpha // settings.textureExtension = "_noextends" // // settings.cellSpacing = factor(forPhone: -0.5, forPad: -1.0) // // settings.enableShadows = false self.settings = settings } func getCellColor(column column:Int, row:Int) -> UIColor { return settings.cellColors[(column+row)%settings.cellColors.count] } func getBlockColor(column column:Int, row:Int) -> UIColor { return getCellColor(column: column+1, row: row) } func getWallColor() -> UIColor { return settings.wallColor } func getTextureName(texture:String) -> String { return texture + settings.textureExtension } func getBackgroundTexture() -> String { return settings.backgroundTexture } class func trueblue() -> ThemeManager { let settings = ThemeSettings() settings.mainmenuImage = "background_darkblue" //let time = any(["morning","midday","evening","twilight","night"]) settings.gameplayImage = "background_midday_sky" settings.wallColor = UIColor(red: 74, green: 74, blue: 74) settings.cellColors = [ UIColor.whiteColor() ,UIColor.whiteColor().colorWithShadow(0.05) ] settings.blendMode = SKBlendMode.Alpha settings.textureExtension = "_noextends" settings.cellSpacing = factor(forPhone: -0.5, forPad: -1.0) settings.enableShadows = false return ThemeManager(settings) } class func defaultTheme() -> ThemeManager { //let themes:[()->ThemeManager] = [ThemeManager.trueblue,ThemeManager.lightBlue,ThemeManager.nightSky,ThemeManager.brownSky] //return any(themes)() return trueblue() } } // class func lightBlue() -> ThemeManager { // var settings = ThemeSettings() // // settings.mainmenuImage = "background_darkblue" // //let time = any(["morning","midday","evening","twilight","night"]) // settings.gameplayImage = "background_morning_sky" // // settings.wallColor = UIColor(red: 74, green: 74, blue: 74) // // settings.cellColors = [ // UIColor.whiteColor() // ,UIColor.whiteColor().colorWithShadow(0.05) // ] // // // settings.blendMode = SKBlendMode.Alpha // settings.textureExtension = "_noextends" // // settings.cellSpacing = factor(forPhone: -0.5, forPad: -1.0) // // settings.enableShadows = false // // return ThemeManager(settings) // } // // class func nightSky() -> ThemeManager { // var settings = ThemeSettings() // // settings.mainmenuImage = "background_darkblue" // //let time = any(["morning","midday","evening","twilight","night"]) // settings.gameplayImage = "background_night_sky" // // settings.wallColor = UIColor(red: 74, green: 74, blue: 74) // // settings.cellColors = [ // UIColor.whiteColor() // ,UIColor.whiteColor().colorWithShadow(0.05) // ] // // settings.blendMode = SKBlendMode.Alpha // settings.textureExtension = "_noextends" // // settings.cellSpacing = factor(forPhone: -0.5, forPad: -1.0) // // settings.enableShadows = false // // return ThemeManager(settings) // } // // class func brownSky() -> ThemeManager { // var settings = ThemeSettings() // // settings.mainmenuImage = "background_darkblue" // //let time = any(["morning","midday","evening","twilight","night"]) // settings.gameplayImage = "background_brown_sky" // // settings.wallColor = UIColor(red: 74, green: 74, blue: 74) // // settings.cellColors = [ // UIColor.whiteColor() // ,UIColor.whiteColor().colorWithShadow(0.05) // ] // // // settings.blendMode = SKBlendMode.Alpha // settings.textureExtension = "_noextends" // // settings.cellSpacing = factor(forPhone: -0.5, forPad: -1.0) // // settings.enableShadows = false // // return ThemeManager(settings) // }
isc
c61192b5cbc0e9e3522f2145a857021b
27.942408
132
0.595695
3.928927
false
false
false
false
jaksatomovic/Snapgram
Snapgram/Sources/FSAlbumView.swift
1
19784
// // FSAlbumView.swift // Fusuma // // Created by Yuta Akizuki on 2015/11/14. // Copyright © 2015年 ytakzk. All rights reserved. // import UIKit import Photos @objc public protocol FSAlbumViewDelegate: class { func albumViewCameraRollUnauthorized() } final class FSAlbumView: UIView, UICollectionViewDataSource, UICollectionViewDelegate, PHPhotoLibraryChangeObserver, UIGestureRecognizerDelegate { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var imageCropView: FSImageCropView! @IBOutlet weak var imageCropViewContainer: UIView! @IBOutlet weak var collectionViewConstraintHeight: NSLayoutConstraint! @IBOutlet weak var imageCropViewConstraintTop: NSLayoutConstraint! weak var delegate: FSAlbumViewDelegate? = nil var images: PHFetchResult<PHAsset>! var imageManager: PHCachingImageManager? var previousPreheatRect: CGRect = .zero let cellSize = CGSize(width: 100, height: 100) var phAsset: PHAsset! // Variables for calculating the position enum Direction { case scroll case stop case up case down } let imageCropViewOriginalConstraintTop: CGFloat = 50 let imageCropViewMinimalVisibleHeight: CGFloat = 100 var dragDirection = Direction.up var imaginaryCollectionViewOffsetStartPosY: CGFloat = 0.0 var cropBottomY: CGFloat = 0.0 var dragStartPos: CGPoint = CGPoint.zero let dragDiff: CGFloat = 20.0 static func instance() -> FSAlbumView { return UINib(nibName: "FSAlbumView", bundle: Bundle(for: self.classForCoder())).instantiate(withOwner: self, options: nil)[0] as! FSAlbumView } func initialize() { if images != nil { return } self.isHidden = false let panGesture = UIPanGestureRecognizer(target: self, action: #selector(FSAlbumView.panned(_:))) panGesture.delegate = self self.addGestureRecognizer(panGesture) collectionViewConstraintHeight.constant = self.frame.height - imageCropView.frame.height - imageCropViewOriginalConstraintTop imageCropViewConstraintTop.constant = 50 dragDirection = Direction.up imageCropViewContainer.layer.shadowColor = UIColor.black.cgColor imageCropViewContainer.layer.shadowRadius = 30.0 imageCropViewContainer.layer.shadowOpacity = 0.9 imageCropViewContainer.layer.shadowOffset = CGSize.zero collectionView.register(UINib(nibName: "FSAlbumViewCell", bundle: Bundle(for: self.classForCoder)), forCellWithReuseIdentifier: "FSAlbumViewCell") collectionView.backgroundColor = fusumaBackgroundColor // Never load photos Unless the user allows to access to photo album checkPhotoAuth() // Sorting condition let options = PHFetchOptions() options.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: false) ] images = PHAsset.fetchAssets(with: .image, options: options) if images.count > 0 { changeImage(images[0]) collectionView.reloadData() collectionView.selectItem(at: IndexPath(row: 0, section: 0), animated: false, scrollPosition: UICollectionViewScrollPosition()) } PHPhotoLibrary.shared().register(self) } deinit { if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized { PHPhotoLibrary.shared().unregisterChangeObserver(self) } } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func panned(_ sender: UITapGestureRecognizer) { if sender.state == UIGestureRecognizerState.began { let view = sender.view let loc = sender.location(in: view) let subview = view?.hitTest(loc, with: nil) if subview == imageCropView && imageCropViewConstraintTop.constant == imageCropViewOriginalConstraintTop { return } dragStartPos = sender.location(in: self) cropBottomY = self.imageCropViewContainer.frame.origin.y + self.imageCropViewContainer.frame.height // Move if dragDirection == Direction.stop { dragDirection = (imageCropViewConstraintTop.constant == imageCropViewOriginalConstraintTop) ? Direction.up : Direction.down } // Scroll event of CollectionView is preferred. if (dragDirection == Direction.up && dragStartPos.y < cropBottomY + dragDiff) || (dragDirection == Direction.down && dragStartPos.y > cropBottomY) { dragDirection = Direction.stop imageCropView.changeScrollable(false) } else { imageCropView.changeScrollable(true) } } else if sender.state == UIGestureRecognizerState.changed { let currentPos = sender.location(in: self) if dragDirection == Direction.up && currentPos.y < cropBottomY - dragDiff { imageCropViewConstraintTop.constant = max(imageCropViewMinimalVisibleHeight - self.imageCropViewContainer.frame.height, currentPos.y + dragDiff - imageCropViewContainer.frame.height) collectionViewConstraintHeight.constant = min(self.frame.height - imageCropViewMinimalVisibleHeight, self.frame.height - imageCropViewConstraintTop.constant - imageCropViewContainer.frame.height) } else if dragDirection == Direction.down && currentPos.y > cropBottomY { imageCropViewConstraintTop.constant = min(imageCropViewOriginalConstraintTop, currentPos.y - imageCropViewContainer.frame.height) collectionViewConstraintHeight.constant = max(self.frame.height - imageCropViewOriginalConstraintTop - imageCropViewContainer.frame.height, self.frame.height - imageCropViewConstraintTop.constant - imageCropViewContainer.frame.height) } else if dragDirection == Direction.stop && collectionView.contentOffset.y < 0 { dragDirection = Direction.scroll imaginaryCollectionViewOffsetStartPosY = currentPos.y } else if dragDirection == Direction.scroll { imageCropViewConstraintTop.constant = imageCropViewMinimalVisibleHeight - self.imageCropViewContainer.frame.height + currentPos.y - imaginaryCollectionViewOffsetStartPosY collectionViewConstraintHeight.constant = max(self.frame.height - imageCropViewOriginalConstraintTop - imageCropViewContainer.frame.height, self.frame.height - imageCropViewConstraintTop.constant - imageCropViewContainer.frame.height) } } else { imaginaryCollectionViewOffsetStartPosY = 0.0 if sender.state == UIGestureRecognizerState.ended && dragDirection == Direction.stop { imageCropView.changeScrollable(true) return } let currentPos = sender.location(in: self) if currentPos.y < cropBottomY - dragDiff && imageCropViewConstraintTop.constant != imageCropViewOriginalConstraintTop { // The largest movement imageCropView.changeScrollable(false) imageCropViewConstraintTop.constant = imageCropViewMinimalVisibleHeight - self.imageCropViewContainer.frame.height collectionViewConstraintHeight.constant = self.frame.height - imageCropViewMinimalVisibleHeight UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.layoutIfNeeded() }, completion: nil) dragDirection = Direction.down } else { // Get back to the original position imageCropView.changeScrollable(true) imageCropViewConstraintTop.constant = imageCropViewOriginalConstraintTop collectionViewConstraintHeight.constant = self.frame.height - imageCropViewOriginalConstraintTop - imageCropViewContainer.frame.height UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.layoutIfNeeded() }, completion: nil) dragDirection = Direction.up } } } // MARK: - UICollectionViewDelegate Protocol func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FSAlbumViewCell", for: indexPath) as! FSAlbumViewCell let currentTag = cell.tag + 1 cell.tag = currentTag let asset = self.images[(indexPath as NSIndexPath).item] self.imageManager?.requestImage(for: asset, targetSize: cellSize, contentMode: .aspectFill, options: nil) { result, info in if cell.tag == currentTag { cell.image = result } } return cell } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images == nil ? 0 : images.count } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { let width = (collectionView.frame.width - 3) / 4 return CGSize(width: width, height: width) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { changeImage(images[(indexPath as NSIndexPath).row]) imageCropView.changeScrollable(true) imageCropViewConstraintTop.constant = imageCropViewOriginalConstraintTop collectionViewConstraintHeight.constant = self.frame.height - imageCropViewOriginalConstraintTop - imageCropViewContainer.frame.height UIView.animate(withDuration: 0.2, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.layoutIfNeeded() }, completion: nil) dragDirection = Direction.up collectionView.scrollToItem(at: indexPath, at: .top, animated: true) } // MARK: - ScrollViewDelegate func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == collectionView { self.updateCachedAssets() } } //MARK: - PHPhotoLibraryChangeObserver func photoLibraryDidChange(_ changeInstance: PHChange) { DispatchQueue.main.async { let collectionChanges = changeInstance.changeDetails(for: self.images) if collectionChanges != nil { self.images = collectionChanges!.fetchResultAfterChanges let collectionView = self.collectionView! if !collectionChanges!.hasIncrementalChanges || collectionChanges!.hasMoves { collectionView.reloadData() } else { collectionView.performBatchUpdates({ let removedIndexes = collectionChanges!.removedIndexes if (removedIndexes?.count ?? 0) != 0 { collectionView.deleteItems(at: removedIndexes!.aapl_indexPathsFromIndexesWithSection(0)) } let insertedIndexes = collectionChanges!.insertedIndexes if (insertedIndexes?.count ?? 0) != 0 { collectionView.insertItems(at: insertedIndexes!.aapl_indexPathsFromIndexesWithSection(0)) } let changedIndexes = collectionChanges!.changedIndexes if (changedIndexes?.count ?? 0) != 0 { collectionView.reloadItems(at: changedIndexes!.aapl_indexPathsFromIndexesWithSection(0)) } }, completion: nil) } self.resetCachedAssets() } } } } internal extension UICollectionView { func aapl_indexPathsForElementsInRect(_ rect: CGRect) -> [IndexPath] { let allLayoutAttributes = self.collectionViewLayout.layoutAttributesForElements(in: rect) if (allLayoutAttributes?.count ?? 0) == 0 {return []} var indexPaths: [IndexPath] = [] indexPaths.reserveCapacity(allLayoutAttributes!.count) for layoutAttributes in allLayoutAttributes! { let indexPath = layoutAttributes.indexPath indexPaths.append(indexPath) } return indexPaths } } internal extension IndexSet { func aapl_indexPathsFromIndexesWithSection(_ section: Int) -> [IndexPath] { var indexPaths: [IndexPath] = [] indexPaths.reserveCapacity(self.count) (self as NSIndexSet).enumerate({idx, stop in indexPaths.append(IndexPath(item: idx, section: section)) }) return indexPaths } } private extension FSAlbumView { func changeImage(_ asset: PHAsset) { self.imageCropView.image = nil self.phAsset = asset DispatchQueue.global(qos: .default).async(execute: { let options = PHImageRequestOptions() options.isNetworkAccessAllowed = true self.imageManager?.requestImage(for: asset, targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight), contentMode: .aspectFill, options: options) { result, info in DispatchQueue.main.async(execute: { self.imageCropView.imageSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight) self.imageCropView.image = result }) } }) } // Check the status of authorization for PHPhotoLibrary func checkPhotoAuth() { PHPhotoLibrary.requestAuthorization { (status) -> Void in switch status { case .authorized: self.imageManager = PHCachingImageManager() if self.images != nil && self.images.count > 0 { self.changeImage(self.images[0]) } case .restricted, .denied: DispatchQueue.main.async(execute: { () -> Void in self.delegate?.albumViewCameraRollUnauthorized() }) default: break } } } // MARK: - Asset Caching func resetCachedAssets() { imageManager?.stopCachingImagesForAllAssets() previousPreheatRect = CGRect.zero } func updateCachedAssets() { var preheatRect = self.collectionView!.bounds preheatRect = preheatRect.insetBy(dx: 0.0, dy: -0.5 * preheatRect.height) let delta = abs(preheatRect.midY - self.previousPreheatRect.midY) if delta > self.collectionView!.bounds.height / 3.0 { var addedIndexPaths: [IndexPath] = [] var removedIndexPaths: [IndexPath] = [] self.computeDifferenceBetweenRect(self.previousPreheatRect, andRect: preheatRect, removedHandler: {removedRect in let indexPaths = self.collectionView.aapl_indexPathsForElementsInRect(removedRect) removedIndexPaths += indexPaths }, addedHandler: {addedRect in let indexPaths = self.collectionView.aapl_indexPathsForElementsInRect(addedRect) addedIndexPaths += indexPaths }) let assetsToStartCaching = self.assetsAtIndexPaths(addedIndexPaths) let assetsToStopCaching = self.assetsAtIndexPaths(removedIndexPaths) self.imageManager?.startCachingImages(for: assetsToStartCaching, targetSize: cellSize, contentMode: .aspectFill, options: nil) self.imageManager?.stopCachingImages(for: assetsToStopCaching, targetSize: cellSize, contentMode: .aspectFill, options: nil) self.previousPreheatRect = preheatRect } } func computeDifferenceBetweenRect(_ oldRect: CGRect, andRect newRect: CGRect, removedHandler: (CGRect)->Void, addedHandler: (CGRect)->Void) { if newRect.intersects(oldRect) { let oldMaxY = oldRect.maxY let oldMinY = oldRect.minY let newMaxY = newRect.maxY let newMinY = newRect.minY if newMaxY > oldMaxY { let rectToAdd = CGRect(x: newRect.origin.x, y: oldMaxY, width: newRect.size.width, height: (newMaxY - oldMaxY)) addedHandler(rectToAdd) } if oldMinY > newMinY { let rectToAdd = CGRect(x: newRect.origin.x, y: newMinY, width: newRect.size.width, height: (oldMinY - newMinY)) addedHandler(rectToAdd) } if newMaxY < oldMaxY { let rectToRemove = CGRect(x: newRect.origin.x, y: newMaxY, width: newRect.size.width, height: (oldMaxY - newMaxY)) removedHandler(rectToRemove) } if oldMinY < newMinY { let rectToRemove = CGRect(x: newRect.origin.x, y: oldMinY, width: newRect.size.width, height: (newMinY - oldMinY)) removedHandler(rectToRemove) } } else { addedHandler(newRect) removedHandler(oldRect) } } func assetsAtIndexPaths(_ indexPaths: [IndexPath]) -> [PHAsset] { if indexPaths.count == 0 { return [] } var assets: [PHAsset] = [] assets.reserveCapacity(indexPaths.count) for indexPath in indexPaths { let asset = self.images[(indexPath as NSIndexPath).item] assets.append(asset) } return assets } }
mit
acf0c8c160fde3382f1998fb8bd6c10e
38.483034
250
0.588241
6.36045
false
false
false
false
leonardo-ferreira07/OnTheMap
OnTheMap/OnTheMap/API/Clients/SessionClient.swift
1
1789
// // SessionClient.swift // OnTheMap // // Created by Leonardo Vinicius Kaminski Ferreira on 10/10/17. // Copyright © 2017 Leonardo Ferreira. All rights reserved. // import Foundation struct SessionClient { static fileprivate let url = APIClient.buildURL(withHost: Constants.apiHostUdacity, withPathExtension: Constants.apiPathUdacitySession) static func postSession(withEmail email: String, password: String, completion: @escaping (_ error: Error?) -> Void) { let jsonBody = ["udacity": ["username": email, "password": password]] as [String: AnyObject] _ = APIClient.performRequestReturnsData(url, method: .POST, jsonBody: jsonBody, ignore5First: true, completion: { (data, error) in guard let data = data else { completion(error) return } if let decoded = try? JSONDecoder().decode(Session.self, from: data) { MemoryStorage.shared.session = decoded completion(nil) } }) { } } static func deleteSession(_ completion: @escaping (_ success: Bool) -> Void) { var headers: [String: String] = [:] if let cookies = HTTPCookieStorage.shared.cookies { for cookie in cookies where cookie.name == "XSRF-TOKEN" { headers["X-XSRF-TOKEN"] = cookie.value } } _ = APIClient.performRequestReturnsData(url, method: .DELETE, ignore5First: true, completion: { (data, error) in guard data != nil else { completion(false) return } completion(true) }) { } } }
mit
a831a108b1d3918de3c80c88b2619173
30.368421
139
0.553691
4.845528
false
false
false
false
brave/browser-ios
Client/Frontend/Settings/AppSettingsOptions.swift
1
9880
/* 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 Shared import SwiftKeychainWrapper import LocalAuthentication // This file contains all of the settings available in the main settings screen of the app. private var ShowDebugSettings: Bool = false private var DebugSettingsClickCount: Int = 0 // For great debugging! class HiddenSetting: Setting { let settings: SettingsTableViewController init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var hidden: Bool { return !ShowDebugSettings } } class DeleteExportedDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSAttributedStringKey.foregroundColor: UIConstants.TableViewRowTextColor]) } override func onClick(_ navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let fileManager = FileManager.default do { let files = try fileManager.contentsOfDirectory(atPath: documentsPath) for file in files { if file.startsWith("browser.") || file.startsWith("logins.") { try fileManager.removeItemInDirectory(documentsPath, named: file) } } } catch { print("Couldn't delete exported data: \(error).") } } } class ExportBrowserDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSAttributedStringKey.foregroundColor: UIConstants.TableViewRowTextColor]) } override func onClick(_ navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] do { let log = Logger.syncLogger try self.settings.profile.files.copyMatching(fromRelativeDirectory: "", toAbsoluteDirectory: documentsPath) { file in log.debug("Matcher: \(file)") return file.startsWith("browser.") || file.startsWith("logins.") } } catch { print("Couldn't export browser data: \(error).") } } } // Opens the the license page in a new tab class LicenseAndAcknowledgementsSetting: Setting { override var url: URL? { return URL(string: WebServer.sharedInstance.URLForResource("license", module: "about")) } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the on-boarding screen again class ShowIntroductionSetting: Setting { let profile: Profile init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.ShowTour, attributes: [NSAttributedStringKey.foregroundColor: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.dismiss(animated: true, completion: { if let appDelegate = UIApplication.shared.delegate as? AppDelegate { appDelegate.browserViewController.presentIntroViewController(true) } }) } } // Opens the search settings pane class SearchSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var style: UITableViewCellStyle { return .value1 } override var accessibilityIdentifier: String? { return "Search" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.DefaultSearchEngine, attributes: [NSAttributedStringKey.foregroundColor: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = SearchSettingsTableViewController() viewController.model = profile.searchEngines navigationController?.pushViewController(viewController, animated: true) } } class LoginsSetting: Setting { let profile: Profile weak var navigationController: UINavigationController? override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "Logins" } init(settings: SettingsTableViewController, delegate: SettingsDelegate?) { self.profile = settings.profile self.navigationController = settings.navigationController let loginsTitle = Strings.Logins super.init(title: NSAttributedString(string: loginsTitle, attributes: [NSAttributedStringKey.foregroundColor: UIConstants.TableViewRowTextColor]), delegate: delegate) } fileprivate func navigateToLoginsList() { let viewController = LoginListViewController(profile: profile) viewController.settingsDelegate = delegate navigationController?.pushViewController(viewController, animated: true) } } class SyncDevicesSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "Sync" } init(settings: SettingsTableViewController) { self.profile = settings.profile let clearTitle = Strings.Sync super.init(title: NSAttributedString(string: clearTitle, attributes: [NSAttributedStringKey.foregroundColor: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { if Sync.shared.isInSyncGroup { let syncSettingsVC = SyncSettingsTableViewController(style: .grouped) syncSettingsVC.dismissHandler = { navigationController?.popToRootViewController(animated: true) } navigationController?.pushViewController(syncSettingsVC, animated: true) } else { let view = SyncWelcomeViewController() view.dismissHandler = { view.navigationController?.popToRootViewController(animated: true) } navigationController?.pushViewController(view, animated: true) } } } class SyncDeviceSetting: Setting { let profile: Profile var onTap: (()->Void)? internal var device: Device internal var displayTitle: String { return device.name ?? "" } override var accessoryType: UITableViewCellAccessoryType { return .none } override var accessibilityIdentifier: String? { return "SyncDevice" } init(profile: Profile, device: Device) { self.profile = profile self.device = device super.init(title: NSAttributedString(string: device.name ?? "", attributes: [NSAttributedStringKey.foregroundColor: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { onTap?() } } class ClearPrivateDataSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "ClearPrivateData" } init(settings: SettingsTableViewController) { self.profile = settings.profile let clearTitle = Strings.ClearPrivateData super.init(title: NSAttributedString(string: clearTitle, attributes: [NSAttributedStringKey.foregroundColor: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = ClearPrivateDataTableViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class PrivacyPolicySetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: Strings.Privacy_Policy, attributes: [NSAttributedStringKey.foregroundColor: UIConstants.TableViewRowTextColor]) } override var url: URL? { return URL(string: "https://www.brave.com/ios_privacy.html") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } class ChangePinSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "ChangePin" } init(settings: SettingsTableViewController) { self.profile = settings.profile let clearTitle = Strings.Change_Pin super.init(title: NSAttributedString(string: clearTitle, attributes: [NSAttributedStringKey.foregroundColor: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { if profile.prefs.boolForKey(kPrefKeyBrowserLock) == true { getApp().requirePinIfNeeded(profile: profile) getApp().securityViewController?.auth() } let view = PinViewController() navigationController?.pushViewController(view, animated: true) } }
mpl-2.0
1ed1f2b9dc9af3d1634167e2bcb1c7b9
36.424242
171
0.707085
5.926815
false
false
false
false
zambelz48/swift-sample-dependency-injection
SampleDI/Core/FlowControllers/LoginFlowController.swift
1
1770
// // LoginFlowController.swift // SampleDI // // Created by Nanda Julianda Akbar on 8/23/17. // Copyright © 2017 Nanda Julianda Akbar. All rights reserved. // import Foundation import UIKit final class LoginFlowController: FlowController { // MARK: `FlowController` properties enum Screen { case loginPage } var navigationController: UINavigationController // MARK: Private properties private var mainFlowController: MainFlowController? init(navigationController: UINavigationController) { self.navigationController = navigationController } // MARK: `FlowController` methods func setInitialScreen(animated: Bool = false) { set(screen: .loginPage, animated: animated) } func viewControllerFor(screen: Screen) -> UIViewController { switch screen { case .loginPage: return createLoginViewController() } } // MARK: Private methods private func createLoginViewController() -> UIViewController { let userDefaults = UserDefaults.standard let userStorage = UserStorageProvider(userDefaults: userDefaults) let userModel = UserModel(userStorageProvider: userStorage) let userService = UserService() let loginViewModel = LoginViewModel(userService: userService, userModel: userModel) let loginViewController = LoginViewController(viewModel: loginViewModel) loginViewController.onNavigationEvent = { [weak self] (event: LoginViewController.NavigationEvent) in switch event { case .homePage: self?.configureMainFlowController() } } return loginViewController } private func configureMainFlowController() { mainFlowController = MainFlowController(navigationController: navigationController) mainFlowController?.setInitialScreen(animated: true) } }
mit
07d770519e70c30e8b55e92a296d2fa5
22.586667
103
0.754664
4.535897
false
false
false
false
aperritano/SimpleMQTTClient
SimpleMQTTClient/Common/SimpleMQTTClient (Anthony’s MacBook Pro's conflicted copy 2016-06-23).swift
1
11275
// // SimpleMQTTClient.swift // Test // // Created by Gianluca Venturini on 10/01/15. // Copyright (c) 2015 Gianluca Venturini. All rights reserved. // import Foundation /** This class provide a simple interface that let you use the MQTT protocol */ public class SimpleMQTTClient: NSObject, MQTTSessionDelegate { // Options public var synchronous = false var session: MQTTSession // Subscribed channels var subscribedChannels: [String: Bool] var subscribedChannelMessageIds: [Int: String] var unsubscribedChannelMessageIds: [Int: String] // Session variables var sessionConnected = false var sessionError = false // Server hostname var host: String? = nil // Delegate public weak var delegate: SimpleMQTTClientDelegate? /** Delegate initializer. - parameter synchronous: If true the client is synchronous, otherwise all the functions will return immediately without waiting for acks. - parameter clientId: The client id used internally by the protocol. You need to have a good reason for set this, otherwise it is better to let the function generate it for you. */ public init(synchronous: Bool, clientId optionalClientId: String? = nil) { self.synchronous = synchronous if let clientId = optionalClientId { session = MQTTSession( clientId: clientId, userName: nil, password: nil, keepAlive: 60, cleanSession: true, will: false, willTopic: nil, willMsg: nil, willQoS: MQTTQosLevel.QoSLevelAtMostOnce, willRetainFlag: false, protocolLevel: 4, runLoop: nil, forMode: nil ) } else { // Random generate clientId let chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; let length = 22; // Imposed by MQTT protocol var clientId = String(); for (var i = length; i > 0; i -= 1) { clientId += chars[Int(arc4random_uniform(UInt32(length)))]; } session = MQTTSession( clientId: clientId, userName: nil, password: nil, keepAlive: 60, cleanSession: true, will: false, willTopic: nil, willMsg: nil, willQoS: MQTTQosLevel.QoSLevelAtMostOnce, willRetainFlag: false, protocolLevel: 4, runLoop: nil, forMode: nil ) } self.subscribedChannels = [:] self.subscribedChannelMessageIds = [:] self.unsubscribedChannelMessageIds = [:] super.init() session.delegate = self; } /** Convenience initializers. It inizialize the client and connect to a server - parameter host: The hostname. - parameter synchronous: If synchronous or not - parameter clientId: An optional client id, you need to have a good reason for setting this, otherwise let the system generate it for you. */ public convenience init(host: String, synchronous: Bool, clientId optionalClientId: String? = nil) { self.init(synchronous: synchronous, clientId: optionalClientId) connect(host) } /** Subscribe to an MQTT channel. - parameter channel: The name of the channel. */ public func subscribe(channel: String) { while !sessionConnected && !sessionError { NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 1)) } _ = 0 if(synchronous) { if session.subscribeAndWaitToTopic(channel, atLevel: MQTTQosLevel.QoSLevelAtMostOnce) { subscribedChannels[channel] = true } } else { let messageId = Int(session.subscribeToTopic(channel, atLevel: MQTTQosLevel.QoSLevelAtMostOnce)) subscribedChannelMessageIds[messageId] = channel } } /** Unsubscribe from an MQTT channel. - parameter channel: The name of the channel. */ public func unsubscribe(channel: String) { if(synchronous) { if let entry = subscribedChannels[channel] { if entry.boolValue { if(session.unsubscribeAndWaitTopic(channel)) { subscribedChannels[channel] = false } } } } else { let messageId = Int(session.unsubscribeTopic(channel)) unsubscribedChannelMessageIds[messageId] = channel } } /** Return an array of channels, it contains also the wildcards. - returns: Array of strings, every sstring is a channel subscribed. */ public func getSubscribedChannels() -> [String] { var channels:[String] = [] for (channel, subscribed) in subscribedChannels { if subscribed { channels.append(channel) } } return channels } /** Return true if is subscribeb or no to a channel, takes into account wildcards. - parameter channel: Channel name. - returns: true if is is subscribed to the channel. */ public func isSubscribed(channel: String) -> Bool { for (c, subscribed) in subscribedChannels { if subscribed && c.substringToIndex(c.endIndex.predecessor()).isSubinitialStringOf(channel) { return true } } return false } /** Return the wildcard that contains the current channel if there's any - parameter channel: Channel name. - returns: the String of the wildcard */ public func wildcardSubscribed(channel: String) -> String? { for (c, subscribed) in subscribedChannels { if subscribed && c.substringToIndex(c.endIndex.predecessor()).isSubinitialStringOf(channel) { return c } } return nil } /** Publish a message on the desired MQTT channel. - parameter channel: The name of the channel. - parameter message: The message. */ public func publish(channel: String, message: String) { while !sessionConnected && !sessionError { NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 1)) } if(synchronous) { session.publishAndWaitData(message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false), onTopic: channel, retain: false, qos: MQTTQosLevel.QoSLevelAtMostOnce) } else{ session.publishData(message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false), onTopic: channel, retain: false, qos: MQTTQosLevel.QoSLevelAtMostOnce) } } /** Disconnect the client immediately. */ public func disconnect() { self.host = nil session.close() sessionConnected = false } /** Connect the client to an MQTT server. - parameter host: The hostname of the server. */ public func connect(host: String) { self.host = host if( sessionConnected == false) { subscribedChannels = [:] if(synchronous) { session.connectAndWaitToHost(host, port: 1883, usingSSL: false) } else { session.connectToHost(host, port: 1883, usingSSL: false) } } } var previouslySubscribedChannels: [String:Bool]? /** Reconnect the client to the MQTT server. */ public func reconnect() { // Only if the session was previously connected if(sessionConnected == true) { // Save the previous subscribed channels if self.previouslySubscribedChannels == nil { self.previouslySubscribedChannels = self.subscribedChannels } self.subscribedChannels = [:] if(synchronous) { session.connectAndWaitToHost(host, port: 1883, usingSSL: false) if let psc = self.previouslySubscribedChannels { for (channel, status) in psc { if(status == true) { self.subscribe(channel) } } } } else { session.connectToHost(host, port: 1883, usingSSL: false) // TODO: resubmit to every channel } } } // Timer callback 1.0 seconds after the disconnection public func reconnect(timer: NSTimer) { self.reconnect() } // MARK: MQTTSessionDelegate protocol public func newMessage(session: MQTTSession!, data: NSData!, onTopic topic: String!, qos: MQTTQosLevel, retained: Bool, mid: UInt32) { print("New message received \(NSString(data: data, encoding: NSUTF8StringEncoding))", terminator: "") self.delegate?.messageReceived?( topic, message: NSString(data: data, encoding: NSUTF8StringEncoding)! as String ) } public func handleEvent(session: MQTTSession!, event eventCode: MQTTSessionEvent, error: NSError!) { switch eventCode { case .Connected: sessionConnected = true self.previouslySubscribedChannels = nil // Delete the channels in the previous session self.delegate?.connected?() case .ConnectionClosed: print("SimpleMQTTClient: Connection closed, retry to re-connect in 1 second", terminator: "") NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(SimpleMQTTClient.reconnect(_:)), userInfo: nil, repeats: false) //sessionConnected = false //self.delegate?.disconnected?() default: sessionError = true } } public func subAckReceived(session: MQTTSession, msgID: UInt16, grantedQoss: [AnyObject]) { if let channel = subscribedChannelMessageIds[Int(msgID)] { subscribedChannels[channel] = true } } public func unsubAckReceived(session: MQTTSession, msgID: UInt16, grantedQoss: [AnyObject]) { if let channel = unsubscribedChannelMessageIds[Int(msgID)] { subscribedChannels[channel] = false } } }
mit
df86379d7f4c7b549a686aa9b3ea72c4
31.77907
185
0.555565
5.389579
false
false
false
false
fouquet/MonthlySales
MonthlySalesTests/Mocks.swift
1
1740
// // Mocks.swift // MonthlySales // // Created by René Fouquet on 12.06.17. // Copyright © 2017 René Fouquet. All rights reserved. // import Foundation @testable import MonthlySales final class ApiMock: ApiMethodsProtocol { init(formatters: FormattersProtocol) {} func getSalesDataFor(startDate: Date, endDate: Date, completion: @escaping (Data?) -> Void) { if let filePath = Bundle.main.path(forResource: "MockData", ofType: "json"), let jsonData = try? Data(contentsOf: URL(fileURLWithPath: filePath), options: .mappedIfSafe) { completion(jsonData) } } func fetchUserInfo(completion: @escaping ((user: String?, currencySymbol: String?)) -> Void) { completion((user: nil, currencySymbol: nil)) } } final class DefaultsMock: DefaultsProtocol { var resultString: String? var key: String? func set(_ string: String, forKey: String) { resultString = string key = forKey } func string(forKey: String) -> String? { return resultString } } final class InternalCalendarMock: InternalCalendarProtocol { var isDateToday = false var isDateYesterday = false var numberOfDays = 0 var todayDate = Date() func isDateInToday(_ date: Date) -> Bool { return isDateToday } func isDateInYesterday(_ date: Date) -> Bool { return isDateYesterday } func numberOfDaysBetween(firstDate: Date, secondDate: Date) -> Int { return numberOfDays } func today() -> Date { return todayDate } func resetMock() { isDateToday = false isDateYesterday = false numberOfDays = 0 todayDate = Date() } }
mit
03d8f70dc51e775017a4d40ea75a458e
24.544118
179
0.630973
4.419847
false
false
false
false
SuPair/firefox-ios
StorageTests/TestLogins.swift
1
31359
/* 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 Shared @testable import Storage import XCGLogger import Deferred import XCTest private let log = XCGLogger.default class TestSQLiteLogins: XCTestCase { var db: BrowserDB! var logins: SQLiteLogins! let formSubmitURL = "http://submit.me" let login = Login.createWithHostname("hostname1", username: "username1", password: "password1", formSubmitURL: "http://submit.me") override func setUp() { super.setUp() let files = MockFiles() self.db = BrowserDB(filename: "testsqlitelogins.db", schema: LoginsSchema(), files: files) self.logins = SQLiteLogins(db: self.db) let expectation = self.expectation(description: "Remove all logins.") self.removeAllLogins().upon({ res in expectation.fulfill() }) waitForExpectations(timeout: 10.0, handler: nil) } func testAddLogin() { log.debug("Created \(self.login)") let expectation = self.expectation(description: "Add login") addLogin(login) >>> getLoginsFor(login.protectionSpace, expected: [login]) >>> done(expectation) waitForExpectations(timeout: 10.0, handler: nil) } func testGetOrder() { let expectation = self.expectation(description: "Add login") // Different GUID. let login2 = Login.createWithHostname("hostname1", username: "username2", password: "password2") login2.formSubmitURL = "http://submit.me" addLogin(login) >>> { self.addLogin(login2) } >>> getLoginsFor(login.protectionSpace, expected: [login2, login]) >>> done(expectation) waitForExpectations(timeout: 10.0, handler: nil) } func testRemoveLogin() { let expectation = self.expectation(description: "Remove login") addLogin(login) >>> { self.removeLogin(self.login) } >>> getLoginsFor(login.protectionSpace, expected: []) >>> done(expectation) waitForExpectations(timeout: 10.0, handler: nil) } func testRemoveLogins() { let loginA = Login.createWithHostname("alphabet.com", username: "username1", password: "password1", formSubmitURL: formSubmitURL) let loginB = Login.createWithHostname("alpha.com", username: "username2", password: "password2", formSubmitURL: formSubmitURL) let loginC = Login.createWithHostname("berry.com", username: "username3", password: "password3", formSubmitURL: formSubmitURL) let loginD = Login.createWithHostname("candle.com", username: "username4", password: "password4", formSubmitURL: formSubmitURL) func addLogins() -> Success { addLogin(loginA).succeeded() addLogin(loginB).succeeded() addLogin(loginC).succeeded() addLogin(loginD).succeeded() return succeed() } addLogins().succeeded() let guids = [loginA.guid, loginB.guid] logins.removeLoginsWithGUIDs(guids).succeeded() let result = logins.getAllLogins().value.successValue! XCTAssertEqual(result.count, 2) } func testRemoveManyLogins() { log.debug("Remove a large number of logins at once") var guids: [GUID] = [] for i in 0..<2000 { let login = Login.createWithHostname("mozilla.org", username: "Fire", password: "fox", formSubmitURL: formSubmitURL) if i <= 1000 { guids += [login.guid] } addLogin(login).succeeded() } logins.removeLoginsWithGUIDs(guids).succeeded() let result = logins.getAllLogins().value.successValue! XCTAssertEqual(result.count, 999) } func testUpdateLogin() { let expectation = self.expectation(description: "Update login") let updated = Login.createWithHostname("hostname1", username: "username1", password: "password3", formSubmitURL: formSubmitURL) updated.guid = self.login.guid addLogin(login) >>> { self.updateLogin(updated) } >>> getLoginsFor(login.protectionSpace, expected: [updated]) >>> done(expectation) waitForExpectations(timeout: 10.0, handler: nil) } func testAddInvalidLogin() { let emptyPasswordLogin = Login.createWithHostname("hostname1", username: "username1", password: "", formSubmitURL: formSubmitURL) var result = logins.addLogin(emptyPasswordLogin).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with an empty password.") let emptyHostnameLogin = Login.createWithHostname("", username: "username1", password: "password", formSubmitURL: formSubmitURL) result = logins.addLogin(emptyHostnameLogin).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with an empty hostname.") let credential = URLCredential(user: "username", password: "password", persistence: .forSession) let protectionSpace = URLProtectionSpace(host: "https://website.com", port: 443, protocol: "https", realm: "Basic Auth", authenticationMethod: "Basic Auth") let bothFormSubmitURLAndRealm = Login.createWithCredential(credential, protectionSpace: protectionSpace) bothFormSubmitURLAndRealm.formSubmitURL = "http://submit.me" result = logins.addLogin(bothFormSubmitURLAndRealm).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with both a httpRealm and formSubmitURL.") let noFormSubmitURLOrRealm = Login.createWithHostname("host", username: "username1", password: "password", formSubmitURL: nil) result = logins.addLogin(noFormSubmitURLOrRealm).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login without a httpRealm or formSubmitURL.") } func testUpdateInvalidLogin() { let updated = Login.createWithHostname("hostname1", username: "username1", password: "", formSubmitURL: formSubmitURL) updated.guid = self.login.guid addLogin(login).succeeded() var result = logins.updateLoginByGUID(login.guid, new: updated, significant: true).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with an empty password.") let emptyHostnameLogin = Login.createWithHostname("", username: "username1", password: "", formSubmitURL: formSubmitURL) emptyHostnameLogin.guid = self.login.guid result = logins.updateLoginByGUID(login.guid, new: emptyHostnameLogin, significant: true).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with an empty hostname.") let credential = URLCredential(user: "username", password: "password", persistence: .forSession) let protectionSpace = URLProtectionSpace(host: "https://website.com", port: 443, protocol: "https", realm: "Basic Auth", authenticationMethod: "Basic Auth") let bothFormSubmitURLAndRealm = Login.createWithCredential(credential, protectionSpace: protectionSpace) bothFormSubmitURLAndRealm.formSubmitURL = "http://submit.me" bothFormSubmitURLAndRealm.guid = self.login.guid result = logins.updateLoginByGUID(login.guid, new: bothFormSubmitURLAndRealm, significant: true).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with both a httpRealm and formSubmitURL.") let noFormSubmitURLOrRealm = Login.createWithHostname("host", username: "username1", password: "password", formSubmitURL: nil) noFormSubmitURLOrRealm.guid = self.login.guid result = logins.updateLoginByGUID(login.guid, new: noFormSubmitURLOrRealm, significant: true).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login without a httpRealm or formSubmitURL.") } func testSearchLogins() { let loginA = Login.createWithHostname("alphabet.com", username: "username1", password: "password1", formSubmitURL: formSubmitURL) let loginB = Login.createWithHostname("alpha.com", username: "username2", password: "password2", formSubmitURL: formSubmitURL) let loginC = Login.createWithHostname("berry.com", username: "username3", password: "password3", formSubmitURL: formSubmitURL) let loginD = Login.createWithHostname("candle.com", username: "username4", password: "password4", formSubmitURL: formSubmitURL) func addLogins() -> Success { addLogin(loginA).succeeded() addLogin(loginB).succeeded() addLogin(loginC).succeeded() addLogin(loginD).succeeded() return succeed() } func checkAllLogins() -> Success { return logins.getAllLogins() >>== { results in XCTAssertEqual(results.count, 4) return succeed() } } func checkSearchHostnames() -> Success { return logins.searchLoginsWithQuery("pha") >>== { results in XCTAssertEqual(results.count, 2) XCTAssertEqual(results[0]!.hostname, "http://alpha.com") XCTAssertEqual(results[1]!.hostname, "http://alphabet.com") return succeed() } } func checkSearchUsernames() -> Success { return logins.searchLoginsWithQuery("username") >>== { results in XCTAssertEqual(results.count, 4) XCTAssertEqual(results[0]!.username, "username2") XCTAssertEqual(results[1]!.username, "username1") XCTAssertEqual(results[2]!.username, "username3") XCTAssertEqual(results[3]!.username, "username4") return succeed() } } func checkSearchPasswords() -> Success { return logins.searchLoginsWithQuery("pass") >>== { results in XCTAssertEqual(results.count, 4) XCTAssertEqual(results[0]!.password, "password2") XCTAssertEqual(results[1]!.password, "password1") XCTAssertEqual(results[2]!.password, "password3") XCTAssertEqual(results[3]!.password, "password4") return succeed() } } XCTAssertTrue(addLogins().value.isSuccess) XCTAssertTrue(checkAllLogins().value.isSuccess) XCTAssertTrue(checkSearchHostnames().value.isSuccess) XCTAssertTrue(checkSearchUsernames().value.isSuccess) XCTAssertTrue(checkSearchPasswords().value.isSuccess) XCTAssertTrue(removeAllLogins().value.isSuccess) } /* func testAddUseOfLogin() { let expectation = self.self.expectation(description: "Add visit") if var usageData = login as? LoginUsageData { usageData.timeCreated = Date.nowMicroseconds() } addLogin(login) >>> addUseDelayed(login, time: 1) >>> getLoginDetailsFor(login, expected: login as! LoginUsageData) >>> done(login.protectionSpace, expectation: expectation) waitForExpectations(timeout: 10.0, handler: nil) } */ func done(_ expectation: XCTestExpectation) -> () -> Success { return { self.removeAllLogins() >>> self.getLoginsFor(self.login.protectionSpace, expected: []) >>> { expectation.fulfill() return succeed() } } } // Note: These functions are all curried so that we pass arguments, but still chain them below func addLogin(_ login: LoginData) -> Success { log.debug("Add \(login)") return logins.addLogin(login) } func updateLogin(_ login: LoginData) -> Success { log.debug("Update \(login)") return logins.updateLoginByGUID(login.guid, new: login, significant: true) } func addUseDelayed(_ login: Login, time: UInt32) -> Success { sleep(time) login.timeLastUsed = Date.nowMicroseconds() let res = logins.addUseOfLoginByGUID(login.guid) sleep(time) return res } func getLoginsFor(_ protectionSpace: URLProtectionSpace, expected: [LoginData]) -> (() -> Success) { return { log.debug("Get logins for \(protectionSpace)") return self.logins.getLoginsForProtectionSpace(protectionSpace) >>== { results in XCTAssertEqual(expected.count, results.count) for (index, login) in expected.enumerated() { XCTAssertEqual(results[index]!.username!, login.username!) XCTAssertEqual(results[index]!.hostname, login.hostname) XCTAssertEqual(results[index]!.password, login.password) } return succeed() } } } /* func getLoginDetailsFor(login: LoginData, expected: LoginUsageData) -> (() -> Success) { return { log.debug("Get details for \(login)") let deferred = self.logins.getUsageDataForLogin(login) log.debug("Final result \(deferred)") return deferred >>== { l in log.debug("Got cursor") XCTAssertLessThan(expected.timePasswordChanged - l.timePasswordChanged, 10) XCTAssertLessThan(expected.timeLastUsed - l.timeLastUsed, 10) XCTAssertLessThan(expected.timeCreated - l.timeCreated, 10) return succeed() } } } */ func removeLogin(_ login: LoginData) -> Success { log.debug("Remove \(login)") return logins.removeLoginByGUID(login.guid) } func removeAllLogins() -> Success { log.debug("Remove All") // Because we don't want to just mark them as deleted. return self.db.run("DELETE FROM loginsM") >>> { self.db.run("DELETE FROM loginsL") } } } class TestSQLiteLoginsPerf: XCTestCase { var db: BrowserDB! var logins: SQLiteLogins! override func setUp() { super.setUp() let files = MockFiles() self.db = BrowserDB(filename: "testsqlitelogins.db", schema: LoginsSchema(), files: files) self.logins = SQLiteLogins(db: self.db) } func testLoginsSearchMatchOnePerf() { populateTestLogins() // Measure time to find one entry amongst the 1000 of them self.measureMetrics([XCTPerformanceMetric.wallClockTime], automaticallyStartMeasuring: true) { for _ in 0...5 { self.logins.searchLoginsWithQuery("username500").succeeded() } self.stopMeasuring() } XCTAssertTrue(removeAllLogins().value.isSuccess) } func testLoginsSearchMatchAllPerf() { populateTestLogins() // Measure time to find all matching results self.measureMetrics([XCTPerformanceMetric.wallClockTime], automaticallyStartMeasuring: true) { for _ in 0...5 { self.logins.searchLoginsWithQuery("username").succeeded() } self.stopMeasuring() } XCTAssertTrue(removeAllLogins().value.isSuccess) } func testLoginsGetAllPerf() { populateTestLogins() // Measure time to find all matching results self.measureMetrics([XCTPerformanceMetric.wallClockTime], automaticallyStartMeasuring: true) { self.logins.getAllLogins().succeeded() self.stopMeasuring() } XCTAssertTrue(removeAllLogins().value.isSuccess) } func populateTestLogins() { var results = [Success]() for i in 0..<1000 { let login = Login.createWithHostname("website\(i).com", username: "username\(i)", password: "password\(i)", formSubmitURL: "test") results.append(addLogin(login)) } _ = all(results).value } func addLogin(_ login: LoginData) -> Success { return logins.addLogin(login) } func removeAllLogins() -> Success { log.debug("Remove All") // Because we don't want to just mark them as deleted. return self.db.run("DELETE FROM loginsM") >>> { self.db.run("DELETE FROM loginsL") } } } class TestSyncableLogins: XCTestCase { var db: BrowserDB! var logins: SQLiteLogins! override func setUp() { super.setUp() let files = MockFiles() self.db = BrowserDB(filename: "testsyncablelogins.db", schema: LoginsSchema(), files: files) self.logins = SQLiteLogins(db: self.db) let expectation = self.expectation(description: "Remove all logins.") self.removeAllLogins().upon({ res in expectation.fulfill() }) waitForExpectations(timeout: 10.0, handler: nil) } func removeAllLogins() -> Success { log.debug("Remove All") // Because we don't want to just mark them as deleted. return self.db.run("DELETE FROM loginsM") >>> { self.db.run("DELETE FROM loginsL") } } func testDiffers() { let guid = "abcdabcdabcd" let host = "http://example.com" let user = "username" let loginA1 = Login(guid: guid, hostname: host, username: user, password: "password1") loginA1.formSubmitURL = "\(host)/form1/" loginA1.usernameField = "afield" let loginA2 = Login(guid: guid, hostname: host, username: user, password: "password1") loginA2.formSubmitURL = "\(host)/form1/" loginA2.usernameField = "somefield" let loginB = Login(guid: guid, hostname: host, username: user, password: "password2") loginB.formSubmitURL = "\(host)/form1/" let loginC = Login(guid: guid, hostname: host, username: user, password: "password") loginC.formSubmitURL = "\(host)/form2/" XCTAssert(loginA1.isSignificantlyDifferentFrom(loginB)) XCTAssert(loginA1.isSignificantlyDifferentFrom(loginC)) XCTAssert(loginA2.isSignificantlyDifferentFrom(loginB)) XCTAssert(loginA2.isSignificantlyDifferentFrom(loginC)) XCTAssert(!loginA1.isSignificantlyDifferentFrom(loginA2)) } func testLocalNewStaysNewAndIsRemoved() { let guidA = "abcdabcdabcd" let loginA1 = Login(guid: guidA, hostname: "http://example.com", username: "username", password: "password") loginA1.formSubmitURL = "http://example.com/form/" loginA1.timesUsed = 1 XCTAssertTrue((self.logins as BrowserLogins).addLogin(loginA1).value.isSuccess) let local1 = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! XCTAssertNotNil(local1) XCTAssertEqual(local1!.guid, guidA) XCTAssertEqual(local1!.syncStatus, SyncStatus.new) XCTAssertEqual(local1!.timesUsed, 1) XCTAssertTrue(self.logins.addUseOfLoginByGUID(guidA).value.isSuccess) // It's still new. let local2 = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! XCTAssertNotNil(local2) XCTAssertEqual(local2!.guid, guidA) XCTAssertEqual(local2!.syncStatus, SyncStatus.new) XCTAssertEqual(local2!.timesUsed, 2) // It's removed immediately, because it was never synced. XCTAssertTrue((self.logins as BrowserLogins).removeLoginByGUID(guidA).value.isSuccess) XCTAssertNil(self.logins.getExistingLocalRecordByGUID(guidA).value.successValue!) } func testApplyLogin() { let guidA = "abcdabcdabcd" let loginA1 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "password", modified: 1234) loginA1.formSubmitURL = "http://example.com/form/" loginA1.timesUsed = 3 XCTAssertTrue(self.logins.applyChangedLogin(loginA1).value.isSuccess) let local = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! let mirror = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue! XCTAssertTrue(nil == local) XCTAssertTrue(nil != mirror) XCTAssertEqual(mirror!.guid, guidA) XCTAssertFalse(mirror!.isOverridden) XCTAssertEqual(mirror!.serverModified, Timestamp(1234), "Timestamp matches.") XCTAssertEqual(mirror!.timesUsed, 3) XCTAssertTrue(nil == mirror!.httpRealm) XCTAssertTrue(nil == mirror!.passwordField) XCTAssertTrue(nil == mirror!.usernameField) XCTAssertEqual(mirror!.formSubmitURL!, "http://example.com/form/") XCTAssertEqual(mirror!.hostname, "http://example.com") XCTAssertEqual(mirror!.username!, "username") XCTAssertEqual(mirror!.password, "password") // Change it. let loginA2 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "newpassword", modified: 2234) loginA2.formSubmitURL = "http://example.com/form/" loginA2.timesUsed = 4 XCTAssertTrue(self.logins.applyChangedLogin(loginA2).value.isSuccess) let changed = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue! XCTAssertTrue(nil != changed) XCTAssertFalse(changed!.isOverridden) XCTAssertEqual(changed!.serverModified, Timestamp(2234), "Timestamp is new.") XCTAssertEqual(changed!.username!, "username") XCTAssertEqual(changed!.password, "newpassword") XCTAssertEqual(changed!.timesUsed, 4) // Change it locally. let preUse = Date.now() XCTAssertTrue(self.logins.addUseOfLoginByGUID(guidA).value.isSuccess) let localUsed = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! let mirrorUsed = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue! XCTAssertNotNil(localUsed) XCTAssertNotNil(mirrorUsed) XCTAssertEqual(mirrorUsed!.guid, guidA) XCTAssertEqual(localUsed!.guid, guidA) XCTAssertEqual(mirrorUsed!.password, "newpassword") XCTAssertEqual(localUsed!.password, "newpassword") XCTAssertTrue(mirrorUsed!.isOverridden) // It's now overridden. XCTAssertEqual(mirrorUsed!.serverModified, Timestamp(2234), "Timestamp is new.") XCTAssertTrue(localUsed!.localModified >= preUse) // Local record is modified. XCTAssertEqual(localUsed!.syncStatus, SyncStatus.synced) // Uses aren't enough to warrant upload. // Uses are local until reconciled. XCTAssertEqual(localUsed!.timesUsed, 5) XCTAssertEqual(mirrorUsed!.timesUsed, 4) // Change the password and form URL locally. let newLocalPassword = Login(guid: guidA, hostname: "http://example.com", username: "username", password: "yupyup") newLocalPassword.formSubmitURL = "http://example.com/form2/" let preUpdate = Date.now() // Updates always bump our usages, too. XCTAssertTrue(self.logins.updateLoginByGUID(guidA, new: newLocalPassword, significant: true).value.isSuccess) let localAltered = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! let mirrorAltered = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue! XCTAssertFalse(mirrorAltered!.isSignificantlyDifferentFrom(mirrorUsed!)) // The mirror is unchanged. XCTAssertFalse(mirrorAltered!.isSignificantlyDifferentFrom(localUsed!)) XCTAssertTrue(mirrorAltered!.isOverridden) // It's still overridden. XCTAssertTrue(localAltered!.isSignificantlyDifferentFrom(localUsed!)) XCTAssertEqual(localAltered!.password, "yupyup") XCTAssertEqual(localAltered!.formSubmitURL!, "http://example.com/form2/") XCTAssertTrue(localAltered!.localModified >= preUpdate) XCTAssertEqual(localAltered!.syncStatus, SyncStatus.changed) // Changes are enough to warrant upload. XCTAssertEqual(localAltered!.timesUsed, 6) XCTAssertEqual(mirrorAltered!.timesUsed, 4) } func testDeltas() { // Shared. let guidA = "abcdabcdabcd" let loginA1 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "password", modified: 1234) loginA1.timeCreated = 1200 loginA1.timeLastUsed = 1234 loginA1.timePasswordChanged = 1200 loginA1.formSubmitURL = "http://example.com/form/" loginA1.timesUsed = 3 let a1a1 = loginA1.deltas(from: loginA1) XCTAssertEqual(0, a1a1.nonCommutative.count) XCTAssertEqual(0, a1a1.nonConflicting.count) XCTAssertEqual(0, a1a1.commutative.count) let loginA2 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "password", modified: 1235) loginA2.timeCreated = 1200 loginA2.timeLastUsed = 1235 loginA2.timePasswordChanged = 1200 loginA2.timesUsed = 4 let a1a2 = loginA2.deltas(from: loginA1) XCTAssertEqual(2, a1a2.nonCommutative.count) XCTAssertEqual(0, a1a2.nonConflicting.count) XCTAssertEqual(1, a1a2.commutative.count) switch a1a2.commutative[0] { case let .timesUsed(increment): XCTAssertEqual(increment, 1) break } switch a1a2.nonCommutative[0] { case let .formSubmitURL(to): XCTAssertNil(to) break default: XCTFail("Unexpected non-commutative login field.") } switch a1a2.nonCommutative[1] { case let .timeLastUsed(to): XCTAssertEqual(to, 1235) break default: XCTFail("Unexpected non-commutative login field.") } let loginA3 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "something else", modified: 1280) loginA3.timeCreated = 1200 loginA3.timeLastUsed = 1250 loginA3.timePasswordChanged = 1250 loginA3.formSubmitURL = "http://example.com/form/" loginA3.timesUsed = 5 let a1a3 = loginA3.deltas(from: loginA1) XCTAssertEqual(3, a1a3.nonCommutative.count) XCTAssertEqual(0, a1a3.nonConflicting.count) XCTAssertEqual(1, a1a3.commutative.count) switch a1a3.commutative[0] { case let .timesUsed(increment): XCTAssertEqual(increment, 2) break } switch a1a3.nonCommutative[0] { case let .password(to): XCTAssertEqual("something else", to) break default: XCTFail("Unexpected non-commutative login field.") } switch a1a3.nonCommutative[1] { case let .timeLastUsed(to): XCTAssertEqual(to, 1250) break default: XCTFail("Unexpected non-commutative login field.") } switch a1a3.nonCommutative[2] { case let .timePasswordChanged(to): XCTAssertEqual(to, 1250) break default: XCTFail("Unexpected non-commutative login field.") } // Now apply the deltas to the original record and check that they match! XCTAssertFalse(loginA1.applyDeltas(a1a2).isSignificantlyDifferentFrom(loginA2)) XCTAssertFalse(loginA1.applyDeltas(a1a3).isSignificantlyDifferentFrom(loginA3)) let merged = Login.mergeDeltas(a: (loginA2.serverModified, a1a2), b: (loginA3.serverModified, a1a3)) let mCCount = merged.commutative.count let a2CCount = a1a2.commutative.count let a3CCount = a1a3.commutative.count XCTAssertEqual(mCCount, a2CCount + a3CCount) let mNCount = merged.nonCommutative.count let a2NCount = a1a2.nonCommutative.count let a3NCount = a1a3.nonCommutative.count XCTAssertLessThanOrEqual(mNCount, a2NCount + a3NCount) XCTAssertGreaterThanOrEqual(mNCount, max(a2NCount, a3NCount)) let mFCount = merged.nonConflicting.count let a2FCount = a1a2.nonConflicting.count let a3FCount = a1a3.nonConflicting.count XCTAssertLessThanOrEqual(mFCount, a2FCount + a3FCount) XCTAssertGreaterThanOrEqual(mFCount, max(a2FCount, a3FCount)) switch merged.commutative[0] { case let .timesUsed(increment): XCTAssertEqual(1, increment) } switch merged.commutative[1] { case let .timesUsed(increment): XCTAssertEqual(2, increment) } switch merged.nonCommutative[0] { case let .password(to): XCTAssertEqual("something else", to) break default: XCTFail("Unexpected non-commutative login field.") } switch merged.nonCommutative[1] { case let .formSubmitURL(to): XCTAssertNil(to) break default: XCTFail("Unexpected non-commutative login field.") } switch merged.nonCommutative[2] { case let .timeLastUsed(to): XCTAssertEqual(to, 1250) break default: XCTFail("Unexpected non-commutative login field.") } switch merged.nonCommutative[3] { case let .timePasswordChanged(to): XCTAssertEqual(to, 1250) break default: XCTFail("Unexpected non-commutative login field.") } // Applying the merged deltas gives us the expected login. let expected = Login(guid: guidA, hostname: "http://example.com", username: "username", password: "something else") expected.timeCreated = 1200 expected.timeLastUsed = 1250 expected.timePasswordChanged = 1250 expected.formSubmitURL = nil expected.timesUsed = 6 let applied = loginA1.applyDeltas(merged) XCTAssertFalse(applied.isSignificantlyDifferentFrom(expected)) XCTAssertFalse(expected.isSignificantlyDifferentFrom(applied)) } func testLoginsIsSynced() { let loginA = Login.createWithHostname("alphabet.com", username: "username1", password: "password1") let serverLoginA = ServerLogin(guid: loginA.guid, hostname: "alpha.com", username: "username1", password: "password1", modified: Date.now()) XCTAssertFalse(logins.hasSyncedLogins().value.successValue ?? true) let _ = logins.addLogin(loginA).value XCTAssertFalse(logins.hasSyncedLogins().value.successValue ?? false) let _ = logins.applyChangedLogin(serverLoginA).value XCTAssertTrue(logins.hasSyncedLogins().value.successValue ?? false) } }
mpl-2.0
10e0311ff3bc6b845067147fed752125
41.319838
164
0.651934
4.909817
false
false
false
false
catloafsoft/AudioKit
AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Sampler Instrument - Wav file.xcplaygroundpage/Contents.swift
1
1307
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Sampler Instrument - Wav File //: ### Loading a sampler with a reference wav file import XCPlayground import AudioKit let pulse = 0.23 // seconds //: We are going to load an EXS24 instrument and send it random notes let sampler = AKSampler() //: Here is where we reference the Wav file as it is in the app bundle sampler.loadWav("Sounds/fmpia1") let ampedSampler = AKBooster(sampler, gain: 3.0) var delay = AKDelay(ampedSampler) delay.time = pulse * 1.5 delay.dryWetMix = 0.3 delay.feedback = 0.2 let reverb = AKReverb(delay) reverb.loadFactoryPreset(.LargeRoom) //: Connect the sampler to the main output AudioKit.output = reverb AudioKit.start() //: This is a loop to send a random note to the sampler //: The sampler 'playNote' function is very useful here AKPlaygroundLoop(every: pulse) { let scale = [0,2,4,5,7,9,11,12] var note = scale.randomElement() let octave = randomInt(3...6) * 12 if random(0, 10) < 1.0 { note++ } if !scale.contains(note % 12) { print("ACCIDENT!") } if random(0, 6) > 1.0 { sampler.playNote(note + octave) } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
mit
6d9b5a38a85a1d43bae53350fafdb596
27.413043
72
0.68707
3.3257
false
false
false
false
banxi1988/BXAppKit
BXForm/Cells/BasicInputCell.swift
1
2736
// // BasicInputCell.swift // Youjia // // Created by Haizhen Lee on 16/1/6. // Copyright © 2016年 xiyili. All rights reserved. // import UIKit import BXModel import BXiOSUtils public final class BasicInputCell : StaticTableViewCell{ open let textField = UITextField(frame:CGRect.zero) public convenience init() { self.init(style: .default, reuseIdentifier: "BasicInputCellCell") } public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) commonInit() } open override func awakeFromNib() { super.awakeFromNib() commonInit() } var allOutlets :[UIView]{ return [textField] } var allUITextFieldOutlets :[UITextField]{ return [textField] } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open func commonInit(){ staticHeight = 65 for childView in allOutlets{ contentView.addSubview(childView) childView.translatesAutoresizingMaskIntoConstraints = false } installConstaints() setupAttrs() } open var paddingLeft:CGFloat = FormMetrics.cellPaddingLeft{ didSet{ paddingLeftConstraint?.constant = paddingLeft } } open var paddingRight:CGFloat = FormMetrics.cellPaddingRight{ didSet{ paddingRightConstraint?.constant = paddingRight } } fileprivate var paddingLeftConstraint:NSLayoutConstraint? fileprivate var paddingRightConstraint:NSLayoutConstraint? open func installConstaints(){ paddingLeftConstraint = textField.pa_leadingMargin.eq(paddingLeft).install() // pa_leading.eq(15) paddingRightConstraint = textField.pa_trailingMargin.eq(paddingRight).install() // pa_trailing.eq(15) textField.pa_bottom.eq(10).install() //pinBottom(10) textField.pa_top.eq(10).install() // pa_top.eq(10) } open func setupAttrs(){ textField.font = UIFont.systemFont(ofSize: FormMetrics.primaryFontSize) textField.backgroundColor = FormColors.textFieldBackgroundColor textField.textColor = FormColors.accentColor } } extension BasicInputCell{ public var inputText:String{ get{ return textField.text?.trimmed() ?? "" } set{ textField.text = newValue } } public var placeholder:String?{ get{ return textField.placeholder } set{ if let str = newValue{ textField.attributedPlaceholder = NSAttributedString(string: str,attributes:[ NSAttributedStringKey.font: UIFont.systemFont(ofSize: FormMetrics.secondaryFontSize), NSAttributedStringKey.foregroundColor: FormColors.hintTextColor ]) }else{ textField.attributedPlaceholder = nil } } } }
mit
e5bd9acfefd1e89005e4e4288b31e1cd
25.278846
106
0.707281
4.663823
false
false
false
false
microtherion/Octarine
Octarine/OctPreferences.swift
1
4303
// // OctPreferences.swift // Octarine // // Created by Matthias Neeracher on 07/05/16. // Copyright © 2016 Matthias Neeracher. All rights reserved. // import Cocoa class OctPreferences: NSWindowController, NSOpenSavePanelDelegate { @IBOutlet weak var octApp : OctApp! convenience init() { self.init(windowNibName: "OctPreferences") } override func windowDidLoad() { super.windowDidLoad() } @IBAction func resetDatabase(_: AnyObject) { let alert = NSAlert() alert.alertStyle = .CriticalAlertStyle alert.messageText = "Do you really want to reset the database? This will delete all stored items." alert.addButtonWithTitle("Cancel") alert.addButtonWithTitle("Reset") alert.beginSheetModalForWindow(window!) { (response: NSModalResponse) in if response == 1001 { let fetchRequest = NSFetchRequest(entityName: "OctItem") fetchRequest.predicate = NSPredicate(format: "ident == ''") let results = try? self.octApp.managedObjectContext.executeFetchRequest(fetchRequest) if let results = results as? [NSManagedObject] { for result in results { self.octApp.managedObjectContext.deleteObject(result) } NSNotificationCenter.defaultCenter().postNotificationName(OCTARINE_DATABASE_RESET, object: self) } } } } @IBAction func migrateDatabase(_: AnyObject) { let defaults = NSUserDefaults.standardUserDefaults() let openPanel = NSOpenPanel() openPanel.canChooseFiles = false openPanel.canChooseDirectories = true openPanel.canCreateDirectories = true openPanel.allowsMultipleSelection = false openPanel.allowedFileTypes = [kUTTypeDirectory as String] openPanel.delegate = nil if let path = defaults.stringForKey("DatabasePath") { openPanel.directoryURL = NSURL(fileURLWithPath: path) } openPanel.beginSheetModalForWindow(window!) { (response: Int) in if response == NSFileHandlingPanelOKButton { let url = openPanel.URL!.URLByAppendingPathComponent("Octarine.storedata") let coordinator = self.octApp.persistentStoreCoordinator let oldStore = coordinator.persistentStores[0] if let _ = try? coordinator.migratePersistentStore(oldStore, toURL: url, options: nil, withType: NSSQLiteStoreType) { defaults.setObject(openPanel.URL?.path, forKey: "DatabasePath") } } } } @IBAction func openDatabase(_: AnyObject) { let defaults = NSUserDefaults.standardUserDefaults() let openPanel = NSOpenPanel() openPanel.canChooseFiles = true openPanel.canChooseDirectories = false openPanel.allowsMultipleSelection = false openPanel.allowedFileTypes = ["storedata"] openPanel.delegate = nil if let path = defaults.stringForKey("DatabasePath") { openPanel.directoryURL = NSURL(fileURLWithPath: path) } openPanel.beginSheetModalForWindow(window!) { (response: Int) in if response == NSFileHandlingPanelOKButton { let url = openPanel.URL! let coordinator = self.octApp.persistentStoreCoordinator let oldStore = coordinator.persistentStores[0] if let _ = try? coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) { try! coordinator.removePersistentStore(oldStore) defaults.setObject(url.URLByDeletingLastPathComponent?.path, forKey: "DatabasePath") NSNotificationCenter.defaultCenter().postNotificationName(OCTARINE_DATABASE_RESET, object: self) } } } } func panel(sender: AnyObject, shouldEnableURL url: NSURL) -> Bool { return url.lastPathComponent == "Octarine.storedata" } }
bsd-2-clause
5884d0858990776233e751d53dfbef76
43.8125
135
0.612041
5.645669
false
false
false
false
CosmicMind/MaterialKit
Sources/iOS/TabBar.swift
1
18959
/* * Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit open class TabItem: FlatButton { /// A dictionary of TabItemStates to UIColors for states. fileprivate var colorForState = [TabItemState: UIColor]() /// A dictionary of TabItemStates to UIImages for states. fileprivate var imageForState = [TabItemState: UIImage]() /// Sets the normal and highlighted image for the button. open override var image: UIImage? { didSet { setTabItemImage(image, for: .normal) setTabItemImage(image, for: .selected) setTabItemImage(image, for: .highlighted) super.image = image } } open override func prepare() { super.prepare() pulseAnimation = .none prepareImages() prepareColors() updateColors() } } fileprivate extension TabItem { /// Prepares the tabsItems images. func prepareImages() { imageForState[.normal] = image imageForState[.selected] = image imageForState[.highlighted] = image } /// Prepares the tabsItems colors. func prepareColors() { colorForState[.normal] = Color.grey.base colorForState[.selected] = Color.blue.base colorForState[.highlighted] = Color.blue.base } } fileprivate extension TabItem { /// Updates the tabItems colors. func updateColors() { let normalColor = colorForState[.normal]! let selectedColor = colorForState[.selected]! let highlightedColor = colorForState[.highlighted]! setTitleColor(normalColor, for: .normal) setImage(imageForState[.normal]?.tint(with: normalColor), for: .normal) setTitleColor(selectedColor, for: .selected) setImage(imageForState[.selected]?.tint(with: selectedColor), for: .selected) setTitleColor(highlightedColor, for: .highlighted) setImage(imageForState[.highlighted]?.tint(with: highlightedColor), for: .highlighted) } } extension TabItem { /** Retrieves the tabItem color for a given state. - Parameter for state: A TabItemState. - Returns: A UIColor. */ open func getTabItemColor(for state: TabItemState) -> UIColor { return colorForState[state]! } /** Sets the color for the tabItem given a TabItemState. - Parameter _ color: A UIColor. - Parameter for state: A TabItemState. */ open func setTabItemColor(_ color: UIColor, for state: TabItemState) { colorForState[state] = color updateColors() } /** Retrieves the tabItem image for a given state. - Parameter for state: A TabItemState. - Returns: An optional UIImage. */ open func getTabItemImage(for state: TabItemState) -> UIImage? { return imageForState[state] } /** Sets the image for the tabItem given a TabItemState. - Parameter _ image: An optional UIImage. - Parameter for state: A TabItemState. */ open func setTabItemImage(_ image: UIImage?, for state: TabItemState) { imageForState[state] = image updateColors() } } @objc(TabItemState) public enum TabItemState: Int { case normal case highlighted case selected } @objc(TabItemLineState) public enum TabItemLineState: Int { case selected } @objc(TabBarLineAlignment) public enum TabBarLineAlignment: Int { case top case bottom } @objc(TabBarDelegate) public protocol TabBarDelegate { /** A delegation method that is executed to determine if the TabBar should transition to the next tab. - Parameter tabBar: A TabBar. - Parameter tabItem: A TabItem. - Returns: A Boolean. */ @objc optional func tabBar(tabBar: TabBar, shouldSelect tabItem: TabItem) -> Bool /** A delegation method that is executed when the tabItem will trigger the animation to the next tab. - Parameter tabBar: A TabBar. - Parameter tabItem: A TabItem. */ @objc optional func tabBar(tabBar: TabBar, willSelect tabItem: TabItem) /** A delegation method that is executed when the tabItem did complete the animation to the next tab. - Parameter tabBar: A TabBar. - Parameter tabItem: A TabItem. */ @objc optional func tabBar(tabBar: TabBar, didSelect tabItem: TabItem) } @objc(_TabBarDelegate) internal protocol _TabBarDelegate { /** A delegation method that is executed to determine if the TabBar should transition to the next tab. - Parameter tabBar: A TabBar. - Parameter tabItem: A TabItem. - Returns: A Boolean. */ func _tabBar(tabBar: TabBar, shouldSelect tabItem: TabItem) -> Bool } @objc(TabBarStyle) public enum TabBarStyle: Int { case auto case nonScrollable case scrollable } public enum TabBarCenteringStyle { case never case auto case always } public enum TabBarLineStyle { case auto case fixed(CGFloat) case custom((TabItem) -> CGFloat) } open class TabBar: Bar { /// A dictionary of TabItemLineStates to UIColors for the line. fileprivate var lineColorForState = [TabItemLineState: UIColor]() /// Only for inital load to get the line animation correct. fileprivate var shouldNotAnimateLineView = false /// The total width of the tabItems. fileprivate var tabItemsTotalWidth: CGFloat { var w: CGFloat = 0 let q = 2 * tabItemsInterimSpace let p = q + tabItemsInterimSpace for v in tabItems { let x = v.sizeThatFits(CGSize(width: .greatestFiniteMagnitude, height: scrollView.bounds.height)).width w += x w += p } w -= tabItemsInterimSpace return w } /// An enum that determines the tab bar style. open var tabBarStyle = TabBarStyle.auto { didSet { layoutSubviews() } } /// An enum that determines the tab bar centering style. open var tabBarCenteringStyle = TabBarCenteringStyle.always { didSet { layoutSubviews() } } /// An enum that determines the tab bar items style. open var tabBarLineStyle = TabBarLineStyle.auto { didSet { layoutSubviews() } } /// A reference to the scroll view when the tab bar style is scrollable. open let scrollView = UIScrollView() /// Enables and disables bouncing when swiping. open var isScrollBounceEnabled: Bool { get { return scrollView.bounces } set(value) { scrollView.bounces = value } } /// A delegation reference. open weak var delegate: TabBarDelegate? internal weak var _delegate: _TabBarDelegate? /// The currently selected tabItem. open internal(set) var selectedTabItem: TabItem? { didSet { oldValue?.isSelected = false selectedTabItem?.isSelected = true } } /// A preset wrapper around tabItems contentEdgeInsets. open var tabItemsContentEdgeInsetsPreset: EdgeInsetsPreset { get { return contentView.grid.contentEdgeInsetsPreset } set(value) { contentView.grid.contentEdgeInsetsPreset = value } } /// A reference to EdgeInsets. @IBInspectable open var tabItemsContentEdgeInsets: EdgeInsets { get { return contentView.grid.contentEdgeInsets } set(value) { contentView.grid.contentEdgeInsets = value } } /// A preset wrapper around tabItems interimSpace. open var tabItemsInterimSpacePreset: InterimSpacePreset { get { return contentView.grid.interimSpacePreset } set(value) { contentView.grid.interimSpacePreset = value } } /// A wrapper around tabItems interimSpace. @IBInspectable open var tabItemsInterimSpace: InterimSpace { get { return contentView.grid.interimSpace } set(value) { contentView.grid.interimSpace = value } } /// TabItems. @objc open var tabItems = [TabItem]() { didSet { oldValue.forEach { $0.removeFromSuperview() } prepareTabItems() layoutSubviews() } } /// A reference to the line UIView. open let line = UIView() /// A value for the line alignment. @objc open var lineAlignment = TabBarLineAlignment.bottom { didSet { layoutSubviews() } } /// The line height. @objc open var lineHeight: CGFloat { get { return line.bounds.height } set(value) { line.frame.size.height = value } } /// The line color. @objc open var lineColor: UIColor { get { return lineColorForState[.selected]! } set(value) { setLineColor(value, for: .selected) } } open override func layoutSubviews() { super.layoutSubviews() guard willLayout else { return } layoutScrollView() layoutLine() updateScrollView() } open override func prepare() { super.prepare() contentEdgeInsetsPreset = .none interimSpacePreset = .interimSpace6 tabItemsInterimSpacePreset = .interimSpace4 prepareContentView() prepareScrollView() prepareDivider() prepareLine() prepareLineColor() updateLineColors() } } fileprivate extension TabBar { // Prepares the line. func prepareLine() { line.layer.zPosition = 10000 lineHeight = 3 scrollView.addSubview(line) } /// Prepares the divider. func prepareDivider() { dividerColor = Color.grey.lighten2 dividerAlignment = .top } /// Prepares the tabItems. func prepareTabItems() { shouldNotAnimateLineView = true for v in tabItems { v.grid.columns = 0 v.contentEdgeInsets = .zero prepareTabItemHandler(tabItem: v) } selectedTabItem = tabItems.first } /// Prepares the line colors. func prepareLineColor() { lineColorForState[.selected] = Color.blue.base } /** Prepares the tabItem animation handler. - Parameter tabItem: A TabItem. */ func prepareTabItemHandler(tabItem: TabItem) { removeTabItemHandler(tabItem: tabItem) tabItem.addTarget(self, action: #selector(handleTabItemsChange(tabItem:)), for: .touchUpInside) } /// Prepares the contentView. func prepareContentView() { contentView.layer.zPosition = 6000 } /// Prepares the scroll view. func prepareScrollView() { scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false centerViews = [scrollView] } } fileprivate extension TabBar { /// Layout the scrollView. func layoutScrollView() { contentView.grid.reload() if .scrollable == tabBarStyle || (.auto == tabBarStyle && tabItemsTotalWidth > scrollView.bounds.width) { var w: CGFloat = 0 let q = 2 * tabItemsInterimSpace let p = q + tabItemsInterimSpace for v in tabItems { v.sizeToFit() let x = v.sizeThatFits(CGSize(width: .greatestFiniteMagnitude, height: scrollView.bounds.height)).width v.frame.size.height = scrollView.bounds.height v.frame.size.width = x + q v.frame.origin.x = w w += x w += p if scrollView != v.superview { scrollView.addSubview(v) } } w -= tabItemsInterimSpace scrollView.contentSize = CGSize(width: w, height: scrollView.bounds.height) } else { scrollView.grid.begin() scrollView.grid.views = tabItems scrollView.grid.axis.columns = tabItems.count scrollView.grid.contentEdgeInsets = tabItemsContentEdgeInsets scrollView.grid.interimSpace = tabItemsInterimSpace scrollView.grid.commit() scrollView.contentSize = scrollView.frame.size } } /// Layout the line view. func layoutLine() { guard let v = selectedTabItem else { return } guard shouldNotAnimateLineView else { let f = lineFrame(for: v, forMotion: true) line.animate(.duration(0), .size(f.size), .position(f.origin)) return } line.frame = lineFrame(for: v) shouldNotAnimateLineView = false } func lineFrame(for tabItem: TabItem, forMotion: Bool = false) -> CGRect { let y = .bottom == lineAlignment ? scrollView.bounds.height - (forMotion ? lineHeight / 2 : lineHeight) : (forMotion ? lineHeight / 2 : 0) let w: CGFloat = { switch tabBarLineStyle { case .auto: return tabItem.bounds.width case .fixed(let w): return w case .custom(let closure): return closure(tabItem) } }() let x = forMotion ? tabItem.center.x : (tabItem.frame.origin.x + (tabItem.bounds.width - w) / 2) return CGRect(x: x, y: y, width: w, height: lineHeight) } } extension TabBar { /** Retrieves the tabItem color for a given state. - Parameter for state: A TabItemState. - Returns: A optional UIColor. */ open func getTabItemColor(for state: TabItemState) -> UIColor? { return tabItems.first?.getTabItemColor(for: state) } /** Sets the color for the tabItem given a TabItemState. - Parameter _ color: A UIColor. - Parameter for state: A TabItemState. */ open func setTabItemsColor(_ color: UIColor, for state: TabItemState) { for v in tabItems { v.setTabItemColor(color, for: state) } } /** Retrieves the line color for a given state. - Parameter for state: A TabItemLineState. - Returns: A UIColor. */ open func getLineColor(for state: TabItemLineState) -> UIColor { return lineColorForState[state]! } /** Sets the color for the line given a TabItemLineState. - Parameter _ color: A UIColor. - Parameter for state: A TabItemLineState. */ open func setLineColor(_ color: UIColor, for state: TabItemLineState) { lineColorForState[state] = color updateLineColors() } } fileprivate extension TabBar { /** Removes the tabItem animation handler. - Parameter tabItem: A TabItem. */ func removeTabItemHandler(tabItem: TabItem) { tabItem.removeTarget(self, action: #selector(handleTabItemsChange(tabItem:)), for: .touchUpInside) } } fileprivate extension TabBar { /// Handles the tabItem touch event. @objc func handleTabItemsChange(tabItem: TabItem) { guard !(false == delegate?.tabBar?(tabBar: self, shouldSelect: tabItem)) else { return } guard !(false == _delegate?._tabBar(tabBar: self, shouldSelect: tabItem)) else { return } animate(to: tabItem, isTriggeredByUserInteraction: true) } } extension TabBar { /** Selects a given index from the tabItems array. - Parameter at index: An Int. - Paramater completion: An optional completion block. */ @objc open func select(at index: Int, completion: ((TabItem) -> Void)? = nil) { guard -1 < index, index < tabItems.count else { return } animate(to: tabItems[index], isTriggeredByUserInteraction: false, completion: completion) } /** Animates to a given tabItem. - Parameter to tabItem: A TabItem. - Parameter completion: An optional completion block. */ open func animate(to tabItem: TabItem, completion: ((TabItem) -> Void)? = nil) { animate(to: tabItem, isTriggeredByUserInteraction: false, completion: completion) } } fileprivate extension TabBar { /// Updates the line colors. func updateLineColors() { line.backgroundColor = lineColorForState[.selected] } } fileprivate extension TabBar { /** Animates to a given tabItem. - Parameter to tabItem: A TabItem. - Parameter isTriggeredByUserInteraction: A boolean indicating whether the state was changed by a user interaction, true if yes, false otherwise. - Parameter completion: An optional completion block. */ func animate(to tabItem: TabItem, isTriggeredByUserInteraction: Bool, completion: ((TabItem) -> Void)? = nil) { if isTriggeredByUserInteraction { delegate?.tabBar?(tabBar: self, willSelect: tabItem) } selectedTabItem = tabItem let f = lineFrame(for: tabItem, forMotion: true) line.animate(.duration(0.25), .size(f.size), .position(f.origin), .completion({ [weak self, isTriggeredByUserInteraction = isTriggeredByUserInteraction, tabItem = tabItem, completion = completion] in guard let `self` = self else { return } if isTriggeredByUserInteraction { self.delegate?.tabBar?(tabBar: self, didSelect: tabItem) } completion?(tabItem) })) updateScrollView() } } fileprivate extension TabBar { /// Updates the scrollView. func updateScrollView() { guard let v = selectedTabItem else { return } let contentOffsetX: CGFloat? = { let shouldScroll = !scrollView.bounds.contains(v.frame) switch tabBarCenteringStyle { case .auto: guard shouldScroll else { return nil } fallthrough case .always: return v.center.x - bounds.width / 2 case .never: guard shouldScroll else { return nil } return v.frame.origin.x < scrollView.bounds.minX ? v.frame.origin.x : v.frame.maxX - scrollView.bounds.width } }() if let x = contentOffsetX { let normalizedOffsetX = min(max(x, 0), scrollView.contentSize.width - scrollView.bounds.width) scrollView.setContentOffset(CGPoint(x: normalizedOffsetX, y: 0), animated: true) } } }
bsd-3-clause
9d672819a5031dea7f99d16878d16567
25.854108
150
0.664328
4.526982
false
false
false
false
hooman/swift
test/expr/closure/single_expr_ifdecl.swift
10
4270
// RUN: %target-typecheck-verify-swift func takeIntToInt(_ f: (Int) -> Int) { } func takeIntIntToInt(_ f: (Int, Int) -> Int) { } // Simple closures with anonymous arguments func simple() { takeIntToInt({ #if true $0 + 1 #else $0 + 2 #endif }) takeIntIntToInt({ #if true $0 + $1 + 1 #else $0 + $1 + 2 #endif }) } // Anonymous arguments with inference func myMap<T, U>(_ array: [T], _ f: (T) -> U) -> [U] {} func testMap(_ array: [Int]) { var farray = myMap(array, { #if true Float($0) #else Float($0 + 1) #endif }) var _ : Float = farray[0] let farray2 = myMap(array, { (x : Int) in #if true Float(x) #else Float(x + 1) #endif }) farray = farray2 _ = farray } // Nested single-expression closures -- <rdar://problem/20931915> class NestedSingleExpr { private var b: Bool = false private func callClosureA(_ callback: () -> Void) {} private func callClosureB(_ callback: () -> Void) {} func call() { callClosureA { [weak self] in #if true self?.callClosureA { #if true self?.b = true #else self?.b = false #endif } #else self?.callClosureB { #if true self?.b = true #else self?.b = false #endif } #endif } } } // Autoclosure nested inside single-expr closure should get discriminator // <rdar://problem/22441425> Swift compiler "INTERNAL ERROR: this diagnostic should not be produced" struct Expectation<T> {} func expect<T>(_ expression: @autoclosure () -> T) -> Expectation<T> { return Expectation<T>() } func describe(_ closure: () -> ()) {} func f() { #if true describe { #if false _ = expect("this") #else _ = expect("what") #endif } #endif } struct Blob {} func withBlob(block: (Blob) -> ()) {} protocol Binding {} extension Int: Binding {} extension Double: Binding {} extension String: Binding {} extension Blob: Binding {} struct Stmt { @discardableResult func bind(_ values: Binding?...) -> Stmt { return self } @discardableResult func bind(_ values: [Binding?]) -> Stmt { return self } @discardableResult func bind(_ values: [String: Binding?]) -> Stmt { return self } } let stmt = Stmt() withBlob { #if true stmt.bind(1, 2.0, "3", $0) #endif } withBlob { #if true stmt.bind([1, 2.0, "3", $0]) #endif } withBlob { #if true stmt.bind(["1": 1, "2": 2.0, "3": "3", "4": $0]) #endif } // <rdar://problem/19840785> // We shouldn't crash on the call to 'a.dispatch' below. class A { func dispatch(_ f : () -> Void) { f() } } class C { var prop = 0 var a = A() func act() { a.dispatch({() -> Void in #if true self.prop // expected-warning {{expression of type 'Int' is unused}} #endif }) } } // Never-returning expressions func haltAndCatchFire() -> Never { #if true while true { } #else while false { } #endif } let backupPlan: () -> Int = { #if true haltAndCatchFire() #endif } func missionCritical(storage: () -> String) {} missionCritical(storage: { #if true haltAndCatchFire() #endif }) // <https://bugs.swift.org/browse/SR-4963> enum E { } func takesAnotherUninhabitedType(e: () -> E) {} takesAnotherUninhabitedType { #if true haltAndCatchFire() #endif } // Weak capture bug caught by rdar://problem/67351438 class Y { var toggle: Bool = false func doSomething(animated: Bool, completionHandler: (Int, Int) -> Void) { } } class X { private(set) var someY: Y! func doSomething() { someY?.doSomething(animated: true, completionHandler: { [weak someY] _, _ in #if true someY?.toggle = true #else someY?.toggle = false #endif }) } } var intOrStringClosure_true = { #if true 42 #else "foo" #endif } var intOrStringClosure_false = { #if false 42 #else "foo" #endif } func testMultiType() { let a = intOrStringClosure_true() _ = a as Int _ = a as String // expected-error {{cannot convert value of type 'Int' to type 'String'}} let b = intOrStringClosure_false() _ = b as Int // expected-error {{cannot convert value of type 'String' to type 'Int'}} _ = b as String }
apache-2.0
f43cd4151d2771dabf992600aa3edc90
17.170213
100
0.58267
3.27957
false
false
false
false
pooi/SubwayAlerter
SubwayAlerter/LocationViewController.swift
1
10646
import UIKit import CoreLocation class LocationViewController : UIViewController,CLLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource { var lat : String = "" var lng : String = "" var mainRow : Array<nealStation> = [] @IBOutlet var underView: UIView! @IBOutlet var spinner: UIActivityIndicatorView! @IBOutlet var tableView: UITableView! @IBOutlet var refresh: UIButton! @IBAction func refreshBtn(sender: AnyObject) { self.lat = "" self.lng = "" self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.requestWhenInUseAuthorization() self.locationManager.startUpdatingLocation() //self.tableView.reloadData() } @IBAction func closeBtn(sender: AnyObject) { self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)//페이지 닫기 } let locationManager = CLLocationManager() override func viewDidLoad() { underView.bounds.size.height = settingFontSize(9) refresh.setFontSize(settingFontSize(0)) refresh.hidden = true for parent in self.navigationController!.navigationBar.subviews{ for childView in parent.subviews{ if(childView is UIImageView){ childView.removeFromSuperview() } } } //네비게이션바 색상변경 let navBarColor = navigationController!.navigationBar // navBarColor.translucent = false // navBarColor.barStyle = .Black navBarColor.barTintColor = UIColor(red: 230/255.0, green: 70/255.0, blue: 70/255.0, alpha: 0.0) navBarColor.tintColor = UIColor.whiteColor() navBarColor.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] self.lat = "" self.lng = "" self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.requestWhenInUseAuthorization() self.locationManager.startUpdatingLocation() self.spinner.startAnimating() } override func viewWillAppear(animated: Bool) { if(self.mainRow.count != 0){ self.tableView.reloadData() } } override func viewDidAppear(animated: Bool) { if(self.lng != "" && self.lat != ""){ self.mainRow = returnLocationRow() if(self.mainRow.count != 0){ self.tableView.reloadData() //self.refresh.hidden = false } }else{ let alert = UIAlertController(title: "오류", message: "현재 위치 정보를 가져오지 못하였습니다.", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "확인", style: .Cancel){(_) in self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)//페이지 닫기 } alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } self.spinner.stopAnimating() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mainRow.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return settingFontSize(9) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell; cell.textLabel?.text = "#\(indexPath.row+1) " + self.mainRow[indexPath.row].statnNm cell.detailTextLabel?.text = self.mainRow[indexPath.row].subwayNm cell.textLabel?.setFontSize(settingFontSize(0)) cell.detailTextLabel?.setFontSize(settingFontSize(0)) cell.detailTextLabel?.textColor = returnLineColor(SubwayId: self.mainRow[indexPath.row].subwayId) return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "moveToFinish") { let index = self.tableView.indexPathForCell(sender as! UITableViewCell) (segue.destinationViewController as? FinishSTViewController)?.startStation = self.mainRow[index!.row].statnNm } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.last //let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude) //let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1)) self.lat = String(location!.coordinate.latitude) self.lng = String(location!.coordinate.longitude) //print("r") self.locationManager.stopUpdatingLocation() } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { let alert = UIAlertController(title: "오류", message: "위치정보를 가져오지 못하였습니다.", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "확인", style: .Cancel){(_) in self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)//페이지 닫기 } alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } func returnLocationRow() -> Array<nealStation>{ self.mainRow.removeAll() var nealTemp : Array<nealStation> = [] let wtm = getWTM()//wgs84 -> WTM convert let baseUrl = "http://swopenapi.seoul.go.kr/api/subway/\(KEY)/json/nearBy/0/50/\(wtm.0)/\(wtm.1)" let escapedText = baseUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) let apiURI = NSURL(string: escapedText!) let apidata : NSData? = NSData(contentsOfURL: apiURI!) do{ let apiDictionary = try NSJSONSerialization.JSONObjectWithData(apidata!, options: []) as! NSDictionary if(apiDictionary["stationList"] as? NSArray != nil){ let sub = apiDictionary["stationList"] as! NSArray //let sub2 = sub["row"] as! NSArray for row in sub{ nealTemp.append(nealStation( statnNm: row["statnNm"] as! String, subwayId: row["subwayId"] as! String, subwayNm: row["subwayNm"] as! String, ord: Int(row["ord"] as! String)! )) } nealTemp = nealTemp.sort({$0.ord < $1.ord}) }else{ let alert = UIAlertController(title: "오류", message: "목록을 가져오는데 실패하였습니다.(1)", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "확인", style: .Cancel, handler: nil) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } }catch{ let alert = UIAlertController(title: "오류", message: "목록을 가져오는데 실패하였습니다.(2)", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "확인", style: .Cancel, handler: nil) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } return nealTemp } func getWTM() -> (String, String){ var x : Double = 0 var y : Double = 0 let baseUrl = "http://apis.daum.net/maps/transcoord?apikey=874c220047db1145942dd82def9e2f8f&x=\(self.lng)&y=\(self.lat)&toCoord=WTM&fromCoord=WGS84&output=json" let escapedText = baseUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) let apiURI = NSURL(string: escapedText!) let apidata : NSData? = NSData(contentsOfURL: apiURI!) do{ let apiDictionary = try NSJSONSerialization.JSONObjectWithData(apidata!, options: []) as? NSDictionary if(apiDictionary != nil){ let sub = apiDictionary! x = sub["x"] as! Double y = sub["y"] as! Double }else{ let alert = UIAlertController(title: "오류", message: "좌표정보를 가져오는데 실패하였습니다.(1)", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "확인", style: .Cancel, handler: nil) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } }catch{ let alert = UIAlertController(title: "오류", message: "좌표정보를 가져오는데 실패하였습니다.(2)", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "확인", style: .Cancel, handler: nil) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } return (String(x), String(y)) } }
bsd-3-clause
e2c32e48e4aea615060cce9570444226
33.294702
168
0.564986
5.103992
false
false
false
false
omise/omise-ios
OmiseSDK/Token.swift
1
8297
import Foundation /// Parameter for creating a new `Token` /// - seealso: Token public struct CreateTokenParameter: Encodable { /// Card holder's full name. public let name: String /// Card number. public let pan: PAN /// Masked PAN number public var number: String { return pan.number } /// Card expiration month (1-12) public let expirationMonth: Int /// Card expiration year (Gregorian) public let expirationYear: Int /// Security code (CVV, CVC, etc) printed on the back of the card. public let securityCode: String /// Issuing city. public let city: String? /// Postal code. public let postalCode: String? private enum TokenCodingKeys: String, CodingKey { case card enum CardCodingKeys: String, CodingKey { case number case name case expirationMonth = "expiration_month" case expirationYear = "expiration_year" case securityCode = "security_code" case city case postalCode = "postal_code" } } /// Initializes new token request. public init( name: String, pan: PAN, expirationMonth: Int, expirationYear: Int, securityCode: String, city: String? = nil, postalCode: String? = nil ) { self.name = name self.pan = pan self.expirationMonth = expirationMonth self.expirationYear = expirationYear self.securityCode = securityCode self.city = city self.postalCode = postalCode } /// Initializes a new token request. public init( name: String, number: String, expirationMonth: Int, expirationYear: Int, securityCode: String, city: String? = nil, postalCode: String? = nil ) { self.init( name: name, pan: PAN(number), expirationMonth: expirationMonth, expirationYear: expirationYear, securityCode: securityCode, city: city, postalCode: postalCode ) } public func encode(to encoder: Encoder) throws { var tokenContainer = encoder.container(keyedBy: TokenCodingKeys.self) var cardContainer = tokenContainer.nestedContainer(keyedBy: TokenCodingKeys.CardCodingKeys.self, forKey: .card) try cardContainer.encode(pan.pan, forKey: .number) try cardContainer.encodeIfPresent(name, forKey: .name) try cardContainer.encodeIfPresent(expirationMonth, forKey: .expirationMonth) try cardContainer.encodeIfPresent(expirationYear, forKey: .expirationYear) try cardContainer.encodeIfPresent(securityCode, forKey: .securityCode) try cardContainer.encodeIfPresent(city, forKey: .city) try cardContainer.encodeIfPresent(postalCode, forKey: .postalCode) } } /// Represents an Charge status public enum ChargeStatus: String, Codable { case unknown case failed case expired case pending case reversed case successful } /// Represents an Omise Token object public struct Token: CreatableObject { public typealias CreateParameter = CreateTokenParameter public static let postURL: URL = Configuration.default.environment.tokenURL public let object: String /// Omise ID of the token public let id: String /// Boolean indicates that if this Token is in the live mode public let isLiveMode: Bool /// URL for fetching the Token data public let location: String /// Boolean indicates that if this token is already used for creating a charge already public var isUsed: Bool /// Card that is used for creating this Token public let card: Card? /// Date that this Token was created public let createdDate: Date /// Status of charge created using this token public let chargeStatus: ChargeStatus private enum CodingKeys: String, CodingKey { case object case location case id case createdDate = "created_at" case isLiveMode = "livemode" case isUsed = "used" case card case chargeStatus = "charge_status" } } public struct Card: Decodable { /// Card's ID. public let id: String /// Boolean flag indicating wether this card is a live card or a test card. public let isLiveMode: Bool /// Card's creation time. public let createdDate: Date /// ISO3166 Country code based on the card number. /// - note: This is informational only and may not always be 100% accurate. public let countryCode: String? /// Issuing city. /// - note: This is informational only and may not always be 100% accurate. public let city: String? /// Postal code. public let postalCode: String? /// Credit card financing type. (debit or credit) public let financing: String? /// Last 4 digits of the card number. public let lastDigits: String /// Card brand. (e.g. Visa, Mastercard, ...) public let brand: String? /// Card expiration month (1-12) public let expirationMonth: Int? /// Card expiration year (Gregrorian) public let expirationYear: Int? /// Unique card-based fingerprint. Allows detection of identical cards without /// exposing card numbers directly. public let fingerprint: String? /// Card holder's full name. public let name: String? /// Boolean indicates that whether that the card is passed the security code check public let securityCodeCheck: Bool public let bankName: String? public let object: String private enum CodingKeys: String, CodingKey { case object case id case isLiveMode = "livemode" case createdDate = "created_at" case lastDigits = "last_digits" case brand case name case bankName = "bank" case postalCode = "postal_code" case countryCode = "country" case city case financing case fingerprint case expirationMonth = "expiration_month" case expirationYear = "expiration_year" case securityCodeCheck = "security_code_check" } } extension Calendar { /// Calendar used in the Credit Card information which is Gregorian Calendar public static let creditCardInformationCalendar = Calendar(identifier: .gregorian) /// Range contains the valid range of the expiration month value public static let validExpirationMonthRange: Range<Int> = Calendar.creditCardInformationCalendar.maximumRange(of: .month)! // swiftlint:disable:previous force_unwrapping } extension NSCalendar { /// Calendar used in the Credit Card information which is Gregorian Calendar @objc(creditCardInformationCalendar) public static var __creditCardInformationCalendar: Calendar { // swiftlint:disable:previous identifier_name return Calendar.creditCardInformationCalendar } } extension Request where T == Token { /// Initializes a new Token Request with the given information public init( name: String, pan: PAN, expirationMonth: Int, expirationYear: Int, securityCode: String, city: String? = nil, postalCode: String? = nil ) { self.init(parameter: CreateTokenParameter( name: name, pan: pan, expirationMonth: expirationMonth, expirationYear: expirationYear, securityCode: securityCode, city: city, postalCode: postalCode )) } /// Initializes a new Token Request with the given information public init( name: String, number: String, expirationMonth: Int, expirationYear: Int, securityCode: String, city: String? = nil, postalCode: String? = nil ) { self.init(parameter: CreateTokenParameter( name: name, number: number, expirationMonth: expirationMonth, expirationYear: expirationYear, securityCode: securityCode, city: city, postalCode: postalCode )) } }
mit
1d3ec3a6444088f4c9ef24473f2bb3ac
30.911538
126
0.637821
4.995184
false
false
false
false
alexcomu/swift3-tutorial
02-swift-introduction/Swift-Introduction.playground/Contents.swift
1
7385
//: Playground - noun: a place where people can play import UIKit // INTRODUCTION // ***************************************** // // Variables var message = "Hello, Friend" var amIHappy = true amIHappy = !amIHappy var feelGood = true feelGood = amIHappy ? true : false var bankAccountBalance = 100 var cashMessage = bankAccountBalance > 50 ? "Great I'm rich" : "Oh F**k" // ***************************************** // // Strings var str: String = "Hello, I'm a string" // The following code is wrong! 'str' is a String Type // str = 50 var age = 25 var firstName = "Alex" var lastName = "Comu" // string concatenation var fullName = firstName + " " + lastName // string interpolation var fullName2 = "\(firstName) \(lastName) is \(age)" // append str to str fullName.append(" something more") // capitalized var songTitle = "bangarang - Skrillex" songTitle = songTitle.capitalized // lower case var chatRoomAnnoyingCapsGuy = "AHAHAHA IS ALL CAPITALIZED" var lowerCasedChat = chatRoomAnnoyingCapsGuy.lowercased() var sentence = "What the hell! You're crazy!" if sentence.contains("hell") || sentence.contains("crazy"){ sentence = sentence.replacingOccurrences(of: "hell", with: "dog") sentence = sentence.replacingOccurrences(of: "crazy", with: "cat") } // ***************************************** // // Numbers var myAge: Int = 27 // this is an integer! var someDoubleNumber: Double = 789789987878979878977897 // this is too big to be an integer! var someMinusNumber = -56.45 // this is a double var pi: Float = 3.14 // this is not allowed! Float = Double --> WRONG! // pi = someMinusNumber // Arithmetic Operators var mul = 15 * 20 var sum = 5 + 6 var diff = 10 - 3 var div = 12 / 3 var div1 = 13 / 5 var remainder = 13 % 5 var result = "The result of 13 / 5 is \(div1) with a remainder of \(remainder)" var randomNumber = 12 if randomNumber % 2 == 0 { print("this is an even number") // print out to the console } else { print("this is an odd number") } var result2 = 15 * ((5 + 7) / 3) // ***************************************** // // Functions //Shape 1 var length = 5 var width = 10 var area = length * width //Shape 2 var length2 = 6 var width2 = 12 var area2 = length2 * width2 //Shape 3 var length3 = 3 var width3 = 8 var area3 = length3 * width3 func calculateArea(length: Int, width: Int) -> Int{ return length * width } // call the function and store the results into 3 constants let shape1 = calculateArea(length: 1, width: 2) let shape2 = calculateArea(length: 12, width: 3) let shape3 = calculateArea(length: 11, width: 5) var myBankAccountBalance = 500.00 var iLikeThoseShoes = 350.00 // inout is used to pass the reference of the variable instead just the value func purchaseItem(currentBalance: inout Double, itemPrice: Double){ if itemPrice <= currentBalance{ currentBalance = currentBalance - itemPrice print("Purchased item for: $\(itemPrice)") }else{ print("Loser!") } } purchaseItem(currentBalance: &myBankAccountBalance, itemPrice: iLikeThoseShoes) var newTShirt = 40.00 purchaseItem(currentBalance: &myBankAccountBalance, itemPrice: newTShirt) // ***************************************** // // Bools / conditionals / compare Operators var isThisFileUseful = true isThisFileUseful = false if true == false || false == false{ print("WTF...") } var isLoadingFinished: Bool = false if !isLoadingFinished{ print("Loading...") } var randomCost = 50 if randomCost > 100{ print("WOW") } else if randomCost == 50{ print("I'm here") }else{ print("No way...") } // ***************************************** // // Logical Operators let amIAllowed = false let butIHaveTheCode = true if !amIAllowed{ print("Not Allowed!") } if amIAllowed || butIHaveTheCode{ print("I'm in!") }else{ print("Stay out") } // ***************************************** // // Arrays var peopleSalary: Array<Int> = [25000, 22000, 123] // array of integers var randomArray: [Any] = ["asd", 123, true] // array of ANY types randomArray.append(true) print(peopleSalary.count) peopleSalary.append(1) print(peopleSalary.count) peopleSalary.remove(at: 0) print(peopleSalary) var students = [String]() // create an empty array of type string -> Initialize var students2: [String] // this is just the declaration students.append("Alex") print(students) //students2.append("ALEX") // ERROR, you need to create an instance before use it students2 = [String]() students2.append("Pippo") print(students2) // ***************************************** // // Loops var salaries: [Double] = [10, 12, 15, 20, 5] print(salaries) var index = 0 // While statement repeat{ salaries[index] = salaries[index] + (salaries[index] * 0.10) index += 1 }while(index < salaries.count) print(salaries) // For statement for i in 0..<salaries.count{ salaries[i] = salaries[i] + (salaries[i] * 0.10) } print(salaries) // For each statement for salary in salaries { print("Salary: \(salary)") } // ***************************************** // // Dictionaries var myDictionary = [String: Any]() myDictionary["firstname"] = "Alex" myDictionary["lastname"] = "Comu" myDictionary["age"] = 27 print("My Dictionary has \(myDictionary.count) items") // clear the dictionary myDictionary = [:] print(myDictionary) if myDictionary.isEmpty { print("Empty Dictionary") }else{ print("WTF") } // null value myDictionary["firstname"] = nil myDictionary["firstname"] = "Alex" myDictionary["lastname"] = "Comu" myDictionary["age"] = 27 for (key, value) in myDictionary { print("Key: \(key) with value: \(value)") } for key in myDictionary.keys{ print("Key: \(key)") } for value in myDictionary.values{ print("Key: \(value)") } var info = [String: Array<[String: Int]>]() info["random"] = [["alex": 1]] for (key, value) in info { print("Key: \(key) value: \(value)") } // ***************************************** // // Optionals // I don't know if I have a value... so I'll use optionals! var optionalVariable: Int? // check this value! //print(optionalVariable!) // '!' is used to retrieve the value, in this case this is a crash! Because the value at the moment is nil! optionalVariable = 500 print(optionalVariable!) // BTW this is bad! var lotteryWinnings: Int? if lotteryWinnings != nil { // this garantee that we have a value print(lotteryWinnings!) } // Preferred way -> Create a constant and assign the value // if let if let winnings = lotteryWinnings{ print(winnings) } // Optionals example with Class (sorry if I'm using class.. see later for more information about classes) // create class Person class Person{ // class has a string called name var name: String? } // create a var alex that is a Person var alex: Person? // print the name value --> nil print(alex?.name) //Create an Instance the alex Person alex = Person() // set the value of the name alex?.name = "Alex" // now we can print the value using the 'if let' way! if let a = alex, let n = a.name{ print(n) } // Other Example class Man{ private var _age: Int! var age: Int{ if _age == nil{ _age = 0 } return _age } func setAge(newAge: Int) { self._age = newAge } } var comu = Man() print(comu.age) comu.setAge(newAge: 27) print(comu.age)
mit
9638fcba5241bb71ce64a8c05cfd681a
20.530612
138
0.63304
3.434884
false
false
false
false
salemoh/GoldenQuraniOS
GoldenQuranSwift/GoldenQuranSwift/PrayerAdjustmentTableViewCell.swift
1
1596
// // PrayerAdjustmentTableViewCell.swift // GoldenQuranSwift // // Created by Omar Fraiwan on 3/27/17. // Copyright © 2017 Omar Fraiwan. All rights reserved. // import UIKit class PrayerAdjustmentTableViewCell: UITableViewCell { var actionsHandler: ((Void)->Void)? @IBOutlet weak var lblTitle: GQLabel! @IBOutlet weak var lblTime: GQLabel! @IBOutlet weak var lblAdjustment: UILabel! @IBOutlet weak var btnMinus: UIButton! @IBOutlet weak var btnPlus: UIButton! var modificationKey:String? @IBAction func plusPressed(_ sender: UIButton) { var currentAdjustment = UserDefaults.standard.integer(forKey: modificationKey!) currentAdjustment += 1 UserDefaults.standard.set(currentAdjustment, forKey: modificationKey!) UserDefaults.standard.synchronize() if let _ = actionsHandler { actionsHandler!() } } @IBAction func minusPressed(_ sender: UIButton) { var currentAdjustment = UserDefaults.standard.integer(forKey: modificationKey!) currentAdjustment -= 1 UserDefaults.standard.set(currentAdjustment, forKey: modificationKey!) UserDefaults.standard.synchronize() if let _ = actionsHandler { actionsHandler!() } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
44d1b7a7fe1e9dd4da4c7055286d8764
28.537037
87
0.664577
4.775449
false
false
false
false
adrfer/swift
test/1_stdlib/TypeName.swift
3
4294
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test class C {} struct S {} enum E {} protocol P {} protocol P2 {} protocol AssociatedTypes { typealias A typealias B typealias C } class Model : AssociatedTypes { typealias A = C typealias B = S typealias C = E } struct Model2 : AssociatedTypes { typealias A = C typealias B = S typealias C = E } class GC<T : AssociatedTypes> {} struct GS<T : AssociatedTypes> {} enum GE<T : AssociatedTypes> {} class GC2<T : AssociatedTypes, U : AssociatedTypes> {} func printTypeName(t: Any.Type) { print(_typeName(t)) } printTypeName(Int.self) // CHECK: Swift.Int printTypeName(C.self) // CHECK-NEXT: [[THIS:.*]].C printTypeName(S.self) // CHECK-NEXT: [[THIS]].S printTypeName(E.self) // CHECK-NEXT: [[THIS]].E printTypeName(GC<Model>.self) // CHECK-NEXT: [[THIS]].GC<[[THIS]].Model> printTypeName(GS<Model>.self) // CHECK-NEXT: [[THIS]].GS<[[THIS]].Model> printTypeName(GE<Model>.self) // CHECK-NEXT: [[THIS]].GE<[[THIS]].Model> printTypeName(GC2<Model, Model2>.self) // CHECK-NEXT: [[THIS]].GC2<[[THIS]].Model, [[THIS]].Model2> printTypeName(P.self) // CHECK-NEXT: [[THIS]].P typealias PP2 = protocol<P, P2> printTypeName(PP2.self) // CHECK-NEXT: protocol<[[THIS]].P, [[THIS]].P2> printTypeName(Any.self) // CHECK-NEXT: protocol<> typealias F = () -> () typealias F2 = () -> () -> () typealias F3 = (() -> ()) -> () printTypeName(F.self) // CHECK-NEXT: () -> () printTypeName(F2.self) // CHECK-NEXT: () -> () -> () printTypeName(F3.self) // CHECK-NEXT: (() -> ()) -> () #if _runtime(_ObjC) typealias B = @convention(block) () -> () typealias B2 = () -> @convention(block) () -> () typealias B3 = (@convention(block) () -> ()) -> () printTypeName(B.self) printTypeName(B2.self) printTypeName(B3.self) #else print("@convention(block) () -> ()") print("() -> @convention(block) () -> ()") print("(@convention(block) () -> ()) -> ()") #endif // CHECK-NEXT: @convention(block) () -> () // CHECK-NEXT: () -> @convention(block) () -> () // CHECK-NEXT: (@convention(block) () -> ()) -> () printTypeName(F.Type.self) // CHECK-NEXT: (() -> ()).Type printTypeName(C.Type.self) // CHECK-NEXT: [[THIS]].C.Type printTypeName(C.Type.Type.self) // CHECK-NEXT: [[THIS]].C.Type.Type printTypeName(Any.Type.self) // CHECK-NEXT: protocol<>.Type printTypeName(Any.Protocol.self) // CHECK-NEXT: protocol<>.Protocol printTypeName(AnyObject.self) // CHECK-NEXT: {{^}}Swift.AnyObject{{$}} printTypeName(AnyClass.self) // CHECK-NEXT: {{^}}Swift.AnyObject.Type{{$}} printTypeName((AnyObject?).self) // CHECK-NEXT: {{^}}Swift.Optional<Swift.AnyObject>{{$}} printTypeName(Void.self) // CHECK-NEXT: () typealias Tup = (Any, F, C) printTypeName(Tup.self) // CHECK-NEXT: (protocol<>, () -> (), [[THIS]].C) typealias IF = inout Int -> () typealias IF2 = inout Int -> inout Int -> () typealias IF3 = (inout Int -> ()) -> () typealias IF3a = (inout (Int -> ())) -> () typealias IF3b = inout (Int -> ()) -> () typealias IF3c = ((inout Int) -> ()) -> () typealias IF4 = inout (() -> ()) -> () typealias IF5 = (inout Int, Any) -> () printTypeName(IF.self) // CHECK-NEXT: inout Swift.Int -> () printTypeName(IF2.self) // CHECK-NEXT: inout Swift.Int -> inout Swift.Int -> () printTypeName(IF3.self) // CHECK-NEXT: inout (Swift.Int -> ()) -> () printTypeName(IF3a.self) // CHECK-NEXT: inout (Swift.Int -> ()) -> () printTypeName(IF3b.self) // CHECK-NEXT: inout (Swift.Int -> ()) -> () printTypeName(IF3c.self) // CHECK-NEXT: (inout Swift.Int -> ()) -> () printTypeName(IF4.self) // CHECK-NEXT: inout (() -> ()) -> () printTypeName(IF5.self) // CHECK-NEXT: (inout Swift.Int, protocol<>) -> () func curry1() { } func curry1Throws() throws { } func curry2() -> () -> () { return curry1 } func curry2Throws() throws -> () -> () { return curry1 } func curry3() -> () throws -> () { return curry1Throws } func curry3Throws() throws -> () throws -> () { return curry1Throws } printTypeName(curry1.dynamicType) // CHECK-NEXT: () -> () printTypeName(curry2.dynamicType) // CHECK-NEXT: () -> () -> () printTypeName(curry2Throws.dynamicType) // CHECK-NEXT: () throws -> () -> () printTypeName(curry3.dynamicType) // CHECK-NEXT: () -> () throws -> () printTypeName(curry3Throws.dynamicType) // CHECK-NEXT: () throws -> () throws -> ()
apache-2.0
5dfaaae92fb66b98fe8258888c7f5e52
30.573529
99
0.625291
3.113851
false
false
false
false
caicai0/ios_demo
load/Carthage/Checkouts/Alamofire/Tests/ResponseTests.swift
14
15863
// // ResponseTests.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 Alamofire import Foundation import XCTest class ResponseTestCase: BaseTestCase { func testThatResponseReturnsSuccessResultWithValidData() { // Given let urlString = "https://httpbin.org/get" let expectation = self.expectation(description: "request should succeed") var response: DefaultDataResponse? // When Alamofire.request(urlString, parameters: ["foo": "bar"]).response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertNil(response?.error) if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) { XCTAssertNotNil(response?.metrics) } } func testThatResponseReturnsFailureResultWithOptionalDataAndError() { // Given let urlString = "https://invalid-url-here.org/this/does/not/exist" let expectation = self.expectation(description: "request should fail with 404") var response: DefaultDataResponse? // When Alamofire.request(urlString, parameters: ["foo": "bar"]).response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertNotNil(response?.error) if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) { XCTAssertNotNil(response?.metrics) } } } // MARK: - class ResponseDataTestCase: BaseTestCase { func testThatResponseDataReturnsSuccessResultWithValidData() { // Given let urlString = "https://httpbin.org/get" let expectation = self.expectation(description: "request should succeed") var response: DataResponse<Data>? // When Alamofire.request(urlString, parameters: ["foo": "bar"]).responseData { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertNotNil(response?.data) XCTAssertEqual(response?.result.isSuccess, true) if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) { XCTAssertNotNil(response?.metrics) } } func testThatResponseDataReturnsFailureResultWithOptionalDataAndError() { // Given let urlString = "https://invalid-url-here.org/this/does/not/exist" let expectation = self.expectation(description: "request should fail with 404") var response: DataResponse<Data>? // When Alamofire.request(urlString, parameters: ["foo": "bar"]).responseData { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertEqual(response?.result.isFailure, true) if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) { XCTAssertNotNil(response?.metrics) } } } // MARK: - class ResponseStringTestCase: BaseTestCase { func testThatResponseStringReturnsSuccessResultWithValidString() { // Given let urlString = "https://httpbin.org/get" let expectation = self.expectation(description: "request should succeed") var response: DataResponse<String>? // When Alamofire.request(urlString, parameters: ["foo": "bar"]).responseString { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertNotNil(response?.data) XCTAssertEqual(response?.result.isSuccess, true) if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) { XCTAssertNotNil(response?.metrics) } } func testThatResponseStringReturnsFailureResultWithOptionalDataAndError() { // Given let urlString = "https://invalid-url-here.org/this/does/not/exist" let expectation = self.expectation(description: "request should fail with 404") var response: DataResponse<String>? // When Alamofire.request(urlString, parameters: ["foo": "bar"]).responseString { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertEqual(response?.result.isFailure, true) if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) { XCTAssertNotNil(response?.metrics) } } } // MARK: - class ResponseJSONTestCase: BaseTestCase { func testThatResponseJSONReturnsSuccessResultWithValidJSON() { // Given let urlString = "https://httpbin.org/get" let expectation = self.expectation(description: "request should succeed") var response: DataResponse<Any>? // When Alamofire.request(urlString, parameters: ["foo": "bar"]).responseJSON { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertNotNil(response?.data) XCTAssertEqual(response?.result.isSuccess, true) if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) { XCTAssertNotNil(response?.metrics) } } func testThatResponseStringReturnsFailureResultWithOptionalDataAndError() { // Given let urlString = "https://invalid-url-here.org/this/does/not/exist" let expectation = self.expectation(description: "request should fail with 404") var response: DataResponse<Any>? // When Alamofire.request(urlString, parameters: ["foo": "bar"]).responseJSON { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertEqual(response?.result.isFailure, true) if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) { XCTAssertNotNil(response?.metrics) } } func testThatResponseJSONReturnsSuccessResultForGETRequest() { // Given let urlString = "https://httpbin.org/get" let expectation = self.expectation(description: "request should succeed") var response: DataResponse<Any>? // When Alamofire.request(urlString, parameters: ["foo": "bar"]).responseJSON { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertNotNil(response?.data) XCTAssertEqual(response?.result.isSuccess, true) if #available(iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *) { XCTAssertNotNil(response?.metrics) } if let responseDictionary = response?.result.value as? [String: Any], let args = responseDictionary["args"] as? [String: String] { XCTAssertEqual(args, ["foo": "bar"], "args should match parameters") } else { XCTFail("args should not be nil") } } func testThatResponseJSONReturnsSuccessResultForPOSTRequest() { // Given let urlString = "https://httpbin.org/post" let expectation = self.expectation(description: "request should succeed") var response: DataResponse<Any>? // When Alamofire.request(urlString, method: .post, parameters: ["foo": "bar"]).responseJSON { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertNotNil(response?.data) XCTAssertEqual(response?.result.isSuccess, true) if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) { XCTAssertNotNil(response?.metrics) } if let responseDictionary = response?.result.value as? [String: Any], let form = responseDictionary["form"] as? [String: String] { XCTAssertEqual(form, ["foo": "bar"], "form should match parameters") } else { XCTFail("form should not be nil") } } } // MARK: - class ResponseMapTestCase: BaseTestCase { func testThatMapTransformsSuccessValue() { // Given let urlString = "https://httpbin.org/get" let expectation = self.expectation(description: "request should succeed") var response: DataResponse<String>? // When Alamofire.request(urlString, parameters: ["foo": "bar"]).responseJSON { resp in response = resp.map { json in // json["args"]["foo"] is "bar": use this invariant to test the map function return ((json as? [String: Any])?["args"] as? [String: Any])?["foo"] as? String ?? "invalid" } expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertEqual(response?.result.isSuccess, true) XCTAssertEqual(response?.result.value, "bar") if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) { XCTAssertNotNil(response?.metrics) } } func testThatMapPreservesFailureError() { // Given let urlString = "https://invalid-url-here.org/this/does/not/exist" let expectation = self.expectation(description: "request should fail with 404") var response: DataResponse<String>? // When Alamofire.request(urlString, parameters: ["foo": "bar"]).responseData { resp in response = resp.map { _ in "ignored" } expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertEqual(response?.result.isFailure, true) if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) { XCTAssertNotNil(response?.metrics) } } } // MARK: - class ResponseFlatMapTestCase: BaseTestCase { func testThatFlatMapTransformsSuccessValue() { // Given let urlString = "https://httpbin.org/get" let expectation = self.expectation(description: "request should succeed") var response: DataResponse<String>? // When Alamofire.request(urlString, parameters: ["foo": "bar"]).responseJSON { resp in response = resp.flatMap { json in // json["args"]["foo"] is "bar": use this invariant to test the flatMap function return ((json as? [String: Any])?["args"] as? [String: Any])?["foo"] as? String ?? "invalid" } expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertEqual(response?.result.isSuccess, true) XCTAssertEqual(response?.result.value, "bar") if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) { XCTAssertNotNil(response?.metrics) } } func testThatFlatMapCatchesTransformationError() { // Given struct TransformError: Error {} let urlString = "https://httpbin.org/get" let expectation = self.expectation(description: "request should succeed") var response: DataResponse<String>? // When Alamofire.request(urlString, parameters: ["foo": "bar"]).responseData { resp in response = resp.flatMap { json in throw TransformError() } expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertEqual(response?.result.isFailure, true) if let error = response?.result.error { XCTAssertTrue(error is TransformError) } else { XCTFail("flatMap should catch the transformation error") } if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) { XCTAssertNotNil(response?.metrics) } } func testThatFlatMapPreservesFailureError() { // Given let urlString = "https://invalid-url-here.org/this/does/not/exist" let expectation = self.expectation(description: "request should fail with 404") var response: DataResponse<String>? // When Alamofire.request(urlString, parameters: ["foo": "bar"]).responseData { resp in response = resp.flatMap { _ in "ignored" } expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertEqual(response?.result.isFailure, true) if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) { XCTAssertNotNil(response?.metrics) } } }
mit
122c213f96a7cd67a3ed5de065d44978
31.84265
108
0.6263
4.867444
false
true
false
false
airbnb/lottie-ios
Sources/Private/Model/Layers/ImageLayerModel.swift
3
1025
// // ImageLayer.swift // lottie-swift // // Created by Brandon Withrow on 1/8/19. // import Foundation /// A layer that holds an image. final class ImageLayerModel: LayerModel { // MARK: Lifecycle required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: ImageLayerModel.CodingKeys.self) referenceID = try container.decode(String.self, forKey: .referenceID) try super.init(from: decoder) } required init(dictionary: [String: Any]) throws { referenceID = try dictionary.value(for: CodingKeys.referenceID) try super.init(dictionary: dictionary) } // MARK: Internal /// The reference ID of the image. let referenceID: String override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(referenceID, forKey: .referenceID) } // MARK: Private private enum CodingKeys: String, CodingKey { case referenceID = "refId" } }
apache-2.0
231482344ffa5a87fab433d6d833726e
23.404762
83
0.708293
3.927203
false
false
false
false
yoonhg84/CPAdManager-iOS
Source/AdPlatformQueue.swift
1
788
// // Created by Chope on 2017. 5. 17.. // Copyright (c) 2017 Chope. All rights reserved. // import Foundation public struct AdPlatformQueue<T: AdIdentifier> { public var current: T { return queue[index] } public var count: Int { return queue.count } private var queue: [T] private var index: Int public init(ads: [T], firstAd: T? = nil) { assert(ads.count > 0) index = ads.index(where: { $0 == firstAd }) ?? 0 queue = ads } public init(ads: [T], identifierForFirstAd identifier: String) { assert(ads.count > 0) index = ads.index(where: { $0.identifier == identifier }) ?? 0 queue = ads } public mutating func next() { index = (index + 1) % queue.count } }
mit
55449d6e9dfb4e23801b0a1235e4fb7a
20.916667
70
0.56599
3.648148
false
false
false
false
natecook1000/swift
test/SILGen/super.swift
2
10203
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_struct.swiftmodule -module-name resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_class.swiftmodule -module-name resilient_class %S/../Inputs/resilient_class.swift // RUN: %target-swift-emit-silgen -module-name super -parse-as-library -I %t %s | %FileCheck %s import resilient_class public class Parent { public final var finalProperty: String { return "Parent.finalProperty" } public var property: String { return "Parent.property" } public final class var finalClassProperty: String { return "Parent.finalProperty" } public class var classProperty: String { return "Parent.property" } public func methodOnlyInParent() {} public final func finalMethodOnlyInParent() {} public func method() {} public final class func finalClassMethodOnlyInParent() {} public class func classMethod() {} } public class Child : Parent { // CHECK-LABEL: sil @$S5super5ChildC8propertySSvg : $@convention(method) (@guaranteed Child) -> @owned String { // CHECK: bb0([[SELF:%.*]] : @guaranteed $Child): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $Child to $Parent // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$S5super6ParentC8propertySSvg : $@convention(method) (@guaranteed Parent) -> @owned String // CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) // CHECK: destroy_value [[CASTED_SELF_COPY]] // CHECK: return [[RESULT]] public override var property: String { return super.property } // CHECK-LABEL: sil @$S5super5ChildC13otherPropertySSvg : $@convention(method) (@guaranteed Child) -> @owned String { // CHECK: bb0([[SELF:%.*]] : @guaranteed $Child): // CHECK: [[COPIED_SELF:%.*]] = copy_value [[SELF]] // CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[COPIED_SELF]] : $Child to $Parent // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$S5super6ParentC13finalPropertySSvg // CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) // CHECK: destroy_value [[CASTED_SELF_COPY]] // CHECK: return [[RESULT]] public var otherProperty: String { return super.finalProperty } } public class Grandchild : Child { // CHECK-LABEL: sil @$S5super10GrandchildC06onlyInB0yyF public func onlyInGrandchild() { // CHECK: function_ref @$S5super6ParentC012methodOnlyInB0yyF : $@convention(method) (@guaranteed Parent) -> () super.methodOnlyInParent() // CHECK: function_ref @$S5super6ParentC017finalMethodOnlyInB0yyF super.finalMethodOnlyInParent() } // CHECK-LABEL: sil @$S5super10GrandchildC6methodyyF public override func method() { // CHECK: function_ref @$S5super6ParentC6methodyyF : $@convention(method) (@guaranteed Parent) -> () super.method() } } public class GreatGrandchild : Grandchild { // CHECK-LABEL: sil @$S5super15GreatGrandchildC6methodyyF public override func method() { // CHECK: function_ref @$S5super10GrandchildC6methodyyF : $@convention(method) (@guaranteed Grandchild) -> () super.method() } } public class ChildToResilientParent : ResilientOutsideParent { // CHECK-LABEL: sil @$S5super22ChildToResilientParentC6methodyyF : $@convention(method) (@guaranteed ChildToResilientParent) -> () public override func method() { // CHECK: bb0([[SELF:%.*]] : @guaranteed $ChildToResilientParent): // CHECK: [[COPY_SELF:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_SELF:%.*]] = upcast [[COPY_SELF]] // CHECK: [[BORROW_UPCAST_SELF:%.*]] = begin_borrow [[UPCAST_SELF]] // CHECK: [[CAST_BORROW_BACK_TO_BASE:%.*]] = unchecked_ref_cast [[BORROW_UPCAST_SELF]] // CHECK: [[FUNC:%.*]] = super_method [[CAST_BORROW_BACK_TO_BASE]] : $ChildToResilientParent, #ResilientOutsideParent.method!1 : (ResilientOutsideParent) -> () -> (), $@convention(method) (@guaranteed ResilientOutsideParent) -> () // CHECK: end_borrow [[BORROW_UPCAST_SELF]] from [[UPCAST_SELF]] // CHECK: apply [[FUNC]]([[UPCAST_SELF]]) super.method() } // CHECK: } // end sil function '$S5super22ChildToResilientParentC6methodyyF' // CHECK-LABEL: sil @$S5super22ChildToResilientParentC11classMethodyyFZ : $@convention(method) (@thick ChildToResilientParent.Type) -> () public override class func classMethod() { // CHECK: bb0([[METASELF:%.*]] : @trivial $@thick ChildToResilientParent.Type): // CHECK: [[UPCAST_METASELF:%.*]] = upcast [[METASELF]] // CHECK: [[FUNC:%.*]] = super_method [[SELF]] : $@thick ChildToResilientParent.Type, #ResilientOutsideParent.classMethod!1 : (ResilientOutsideParent.Type) -> () -> (), $@convention(method) (@thick ResilientOutsideParent.Type) -> () // CHECK: apply [[FUNC]]([[UPCAST_METASELF]]) super.classMethod() } // CHECK: } // end sil function '$S5super22ChildToResilientParentC11classMethodyyFZ' // CHECK-LABEL: sil @$S5super22ChildToResilientParentC11returnsSelfACXDyFZ : $@convention(method) (@thick ChildToResilientParent.Type) -> @owned ChildToResilientParent public class func returnsSelf() -> Self { // CHECK: bb0([[METASELF:%.*]] : @trivial $@thick ChildToResilientParent.Type): // CHECK: [[CAST_METASELF:%.*]] = unchecked_trivial_bit_cast [[METASELF]] : $@thick ChildToResilientParent.Type to $@thick @dynamic_self ChildToResilientParent.Type // CHECK: [[UPCAST_CAST_METASELF:%.*]] = upcast [[CAST_METASELF]] : $@thick @dynamic_self ChildToResilientParent.Type to $@thick ResilientOutsideParent.Type // CHECK: [[FUNC:%.*]] = super_method [[METASELF]] : $@thick ChildToResilientParent.Type, #ResilientOutsideParent.classMethod!1 : (ResilientOutsideParent.Type) -> () -> () // CHECK: apply [[FUNC]]([[UPCAST_CAST_METASELF]]) // CHECK: unreachable super.classMethod() } // CHECK: } // end sil function '$S5super22ChildToResilientParentC11returnsSelfACXDyFZ' } public class ChildToFixedParent : OutsideParent { // CHECK-LABEL: sil @$S5super18ChildToFixedParentC6methodyyF : $@convention(method) (@guaranteed ChildToFixedParent) -> () public override func method() { // CHECK: bb0([[SELF:%.*]] : @guaranteed $ChildToFixedParent): // CHECK: [[COPY_SELF:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_COPY_SELF:%.*]] = upcast [[COPY_SELF]] // CHECK: [[BORROWED_UPCAST_COPY_SELF:%.*]] = begin_borrow [[UPCAST_COPY_SELF]] // CHECK: [[DOWNCAST_BORROWED_UPCAST_COPY_SELF:%.*]] = unchecked_ref_cast [[BORROWED_UPCAST_COPY_SELF]] : $OutsideParent to $ChildToFixedParent // CHECK: [[FUNC:%.*]] = super_method [[DOWNCAST_BORROWED_UPCAST_COPY_SELF]] : $ChildToFixedParent, #OutsideParent.method!1 : (OutsideParent) -> () -> (), $@convention(method) (@guaranteed OutsideParent) -> () // CHECK: end_borrow [[BORROWED_UPCAST_COPY_SELF]] from [[UPCAST_COPY_SELF]] // CHECK: apply [[FUNC]]([[UPCAST_COPY_SELF]]) super.method() } // CHECK: } // end sil function '$S5super18ChildToFixedParentC6methodyyF' // CHECK-LABEL: sil @$S5super18ChildToFixedParentC11classMethodyyFZ : $@convention(method) (@thick ChildToFixedParent.Type) -> () public override class func classMethod() { // CHECK: bb0([[SELF:%.*]] : @trivial $@thick ChildToFixedParent.Type): // CHECK: [[UPCAST_SELF:%.*]] = upcast [[SELF]] // CHECK: [[FUNC:%.*]] = super_method [[SELF]] : $@thick ChildToFixedParent.Type, #OutsideParent.classMethod!1 : (OutsideParent.Type) -> () -> (), $@convention(method) (@thick OutsideParent.Type) -> () // CHECK: apply [[FUNC]]([[UPCAST_SELF]]) super.classMethod() } // CHECK: } // end sil function '$S5super18ChildToFixedParentC11classMethodyyFZ' // CHECK-LABEL: sil @$S5super18ChildToFixedParentC11returnsSelfACXDyFZ : $@convention(method) (@thick ChildToFixedParent.Type) -> @owned ChildToFixedParent public class func returnsSelf() -> Self { // CHECK: bb0([[SELF:%.*]] : @trivial $@thick ChildToFixedParent.Type): // CHECK: [[FIRST_CAST:%.*]] = unchecked_trivial_bit_cast [[SELF]] // CHECK: [[SECOND_CAST:%.*]] = upcast [[FIRST_CAST]] // CHECK: [[FUNC:%.*]] = super_method [[SELF]] : $@thick ChildToFixedParent.Type, #OutsideParent.classMethod!1 : (OutsideParent.Type) -> () -> () // CHECK: apply [[FUNC]]([[SECOND_CAST]]) // CHECK: unreachable super.classMethod() } // CHECK: } // end sil function '$S5super18ChildToFixedParentC11returnsSelfACXDyFZ' } public extension ResilientOutsideChild { public func callSuperMethod() { super.method() } public class func callSuperClassMethod() { super.classMethod() } } public class GenericBase<T> { public func method() {} } public class GenericDerived<T> : GenericBase<T> { public override func method() { // CHECK-LABEL: sil private @$S5super14GenericDerivedC6methodyyFyyXEfU_ : $@convention(thin) <T> (@guaranteed GenericDerived<T>) -> () // CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T> // CHECK: return { super.method() }() // CHECK: } // end sil function '$S5super14GenericDerivedC6methodyyFyyXEfU_' // CHECK-LABEL: sil private @$S5super14GenericDerivedC6methodyyF13localFunctionL_yylF : $@convention(thin) <T> (@guaranteed GenericDerived<T>) -> () // CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T> // CHECK: return // CHECK: } // end sil function '$S5super14GenericDerivedC6methodyyF13localFunctionL_yylF' func localFunction() { super.method() } localFunction() // CHECK-LABEL: sil private @$S5super14GenericDerivedC6methodyyF15genericFunctionL_yyqd__r__lF : $@convention(thin) <T><U> (@in_guaranteed U, @guaranteed GenericDerived<T>) -> () // CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T> // CHECK: return func genericFunction<U>(_: U) { super.method() } // CHECK: } // end sil function '$S5super14GenericDerivedC6methodyyF15genericFunctionL_yyqd__r__lF' genericFunction(0) } }
apache-2.0
cc36e546250f38cbda652c305295b647
49.509901
238
0.666961
3.780289
false
false
false
false
huangboju/Moots
Examples/SwiftUI/Mac/Get-It-master/Get It/secureOptionsTextfield.swift
1
1103
// // secureOptionsTextfield.swift // Get It // // Created by Kevin De Koninck on 04/02/2017. // Copyright © 2017 Kevin De Koninck. All rights reserved. // import Cocoa class secureOptionsTextfield: NSSecureTextField { override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) var bgColor = NSColor(red: 251/255.0, green: 251/255.0, blue: 251/255.0, alpha: 1.0) bgColor = NSColor(red: 245/255.0, green: 245/255.0, blue: 245/255.0, alpha: 1.0) self.focusRingType = .none self.isBordered = false self.drawsBackground = false self.backgroundColor = bgColor self.layer?.backgroundColor = bgColor.cgColor //underline let border = CALayer() let width = CGFloat(1.0) border.borderColor = blueColor.cgColor border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height) border.borderWidth = width self.layer?.addSublayer(border) self.layer?.masksToBounds = true } }
mit
e1733b2a06641216653b54d13e12e906
30.485714
133
0.628857
3.853147
false
false
false
false
Lollipop95/WeiBo
WeiBo/WeiBo/Classes/Tools/Network/WBNetworkManager.swift
1
4963
// // WBNetworkManager.swift // WeiBo // // Created by Ning Li on 2017/5/3. // Copyright © 2017年 Ning Li. All rights reserved. // import UIKit import AFNetworking enum WBHTTPMethod { case GET case POST } class WBNetworkManager: AFHTTPSessionManager { /// 单例 static let shared: WBNetworkManager = { let instance = WBNetworkManager() // 设置 AFN 反序列化支持的数据类型 instance.responseSerializer.acceptableContentTypes?.insert("text/plain") return instance }() /// 用户账户信息 lazy var userAccount = WBUserAccount() /// 用户登录标记 var userLogon: Bool { return userAccount.access_token != nil } /// 封装 AFN 的 GET/POST 方法 /// /// - Parameters: /// - method: 请求方法 /// - urlString: urlString /// - parameters: 参数字典 /// - completion: 完成回调 func request(method: WBHTTPMethod = .GET, urlString: String, parameters: [String: Any]?, completion: @escaping (_ json: Any?, _ isSuccess: Bool)->()) { // 成功回调 let success = { (task: URLSessionDataTask, json: Any?) -> Void in completion(json, true) } // 失败回调 let failure = { (task: URLSessionDataTask?, error: Error?) -> Void in // 处理 token 过期 if (task?.response as? HTTPURLResponse)?.statusCode == 403 { // 发送用户需要登录通知 NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: "bad token") } print("\(String(describing: error))") completion(error, false) } if method == .GET { get(urlString, parameters: parameters, progress: nil, success: success, failure: failure) } else { post(urlString, parameters: parameters, progress: nil, success: success, failure: failure) } } /// 封装 AFN 上传文件的方法 /// /// - Parameters: /// - urlString: urlString /// - parameters: 参数字典 /// - name: 服务器接收数据的字段 (新浪微博 - 'pic') /// - data: 要上传的二进制数据 /// - completion: 完成回调 func upload(urlString: String, parameters: [String: Any]?, name: String, data: Data, completion: @escaping (_ json: Any?, _ isSuccess: Bool)->()) { post(urlString, parameters: parameters, constructingBodyWith: { (formData) in /** 创建 formData * * data: 要上传的二进制数据 * name: 服务器接收数据的字段 * fileName: 保存在服务器的文件名 * mimeType: 上传的文件类型 */ formData.appendPart(withFileData: data, name: name, fileName: "xxx", mimeType: "application/octet-stream") }, progress: nil, success: { (_, json) in completion(json, true) }) { (task, error) in // token 过期处理 if (task?.response as? HTTPURLResponse)?.statusCode == 403 { // 发送通知,提示登录 NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: "bad token") } completion(error, false) } } /// 拼接 access_token 的网络请求方法 /// /// - Parameters: /// - urlString: urlString /// - parameters: 参数字典 /// - name: 服务器接收的字段 /// - data: 要上传的二进制数据 /// - completion: 完成回调 func tokenRequest(method: WBHTTPMethod = .GET, urlString: String, parameters: [String: Any]?, name: String? = nil, data: Data? = nil, completion: @escaping (_ json: Any?, _ isSuccess: Bool)->()) { guard let token = userAccount.access_token else { // 发送用户需要登录通知 NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil) completion(nil, false) return } var parameters = parameters if parameters == nil { parameters = [String: Any]() } parameters!["access_token"] = token if let name = name, let data = data { upload(urlString: urlString, parameters: parameters, name: name, data: data, completion: completion) } else { request(method: method, urlString: urlString, parameters: parameters, completion: completion) } } }
mit
7fe257177fc395462555eafa447930b0
30.232877
200
0.532675
4.662577
false
false
false
false
auth0/Auth0.swift
Auth0Tests/IDTokenValidatorMocks.swift
1
2188
import Foundation import JWTDecode @testable import Auth0 // MARK: - Signature Validator Mocks struct MockSuccessfulIDTokenSignatureValidator: JWTAsyncValidator { func validate(_ jwt: JWT, callback: @escaping (Auth0Error?) -> Void) { callback(nil) } } struct MockUnsuccessfulIDTokenSignatureValidator: JWTAsyncValidator { enum ValidationError: Auth0Error { case errorCase var debugDescription: String { return "Error message" } } func validate(_ jwt: JWT, callback: @escaping (Auth0Error?) -> Void) { callback(ValidationError.errorCase) } } class SpyThreadingIDTokenSignatureValidator: JWTAsyncValidator { var didExecuteInWorkerThread: Bool = false func validate(_ jwt: JWT, callback: @escaping (Auth0Error?) -> Void) { didExecuteInWorkerThread = !Thread.isMainThread callback(nil) } } // MARK: - Claims Validator Mocks struct MockSuccessfulIDTokenClaimsValidator: JWTValidator { func validate(_ jwt: JWT) -> Auth0Error? { return nil } } class SpyThreadingIDTokenClaimsValidator: JWTValidator { var didExecuteInWorkerThread: Bool = false func validate(_ jwt: JWT) -> Auth0Error? { didExecuteInWorkerThread = !Thread.isMainThread return nil } } struct MockSuccessfulIDTokenClaimValidator: JWTValidator { func validate(_ jwt: JWT) -> Auth0Error? { return nil } } class MockUnsuccessfulIDTokenClaimValidator: JWTValidator { enum ValidationError: Auth0Error { case errorCase1 case errorCase2 var debugDescription: String { return "Error message" } } let errorCase: ValidationError init(errorCase: ValidationError = .errorCase1) { self.errorCase = errorCase } func validate(_ jwt: JWT) -> Auth0Error? { return errorCase } } class SpyUnsuccessfulIDTokenClaimValidator: MockUnsuccessfulIDTokenClaimValidator { var didExecuteValidation: Bool = false override func validate(_ jwt: JWT) -> Auth0Error? { didExecuteValidation = true return super.validate(jwt) } }
mit
a64758830c07e38407c5d5dbf228d70f
24.149425
83
0.671846
4.41129
false
false
false
false
svdo/swift-RichString
Pods/Nimble/Sources/Nimble/Matchers/SatisfyAnyOf.swift
1
3886
/// A Nimble matcher that succeeds when the actual value matches with any of the matchers /// provided in the variable list of matchers. public func satisfyAnyOf<T>(_ predicates: Predicate<T>...) -> Predicate<T> { return satisfyAnyOf(predicates) } /// A Nimble matcher that succeeds when the actual value matches with any of the matchers /// provided in the variable list of matchers. @available(*, deprecated, message: "Use Predicate instead") public func satisfyAnyOf<T, U>(_ matchers: U...) -> Predicate<T> where U: Matcher, U.ValueType == T { return satisfyAnyOf(matchers.map { $0.predicate }) } internal func satisfyAnyOf<T>(_ predicates: [Predicate<T>]) -> Predicate<T> { return Predicate.define { actualExpression in var postfixMessages = [String]() var matches = false for predicate in predicates { let result = try predicate.satisfies(actualExpression) if result.toBoolean(expectation: .toMatch) { matches = true } postfixMessages.append("{\(result.message.expectedMessage)}") } var msg: ExpectationMessage if let actualValue = try actualExpression.evaluate() { msg = .expectedCustomValueTo( "match one of: " + postfixMessages.joined(separator: ", or "), actual: "\(actualValue)" ) } else { msg = .expectedActualValueTo( "match one of: " + postfixMessages.joined(separator: ", or ") ) } return PredicateResult(bool: matches, message: msg) } } public func || <T>(left: Predicate<T>, right: Predicate<T>) -> Predicate<T> { return satisfyAnyOf(left, right) } @available(*, deprecated, message: "Use Predicate instead") public func || <T>(left: NonNilMatcherFunc<T>, right: NonNilMatcherFunc<T>) -> Predicate<T> { return satisfyAnyOf(left, right) } @available(*, deprecated, message: "Use Predicate instead") public func || <T>(left: MatcherFunc<T>, right: MatcherFunc<T>) -> Predicate<T> { return satisfyAnyOf(left, right) } #if canImport(Darwin) import class Foundation.NSObject extension NMBPredicate { @objc public class func satisfyAnyOfMatcher(_ matchers: [NMBMatcher]) -> NMBPredicate { return NMBPredicate { actualExpression in if matchers.isEmpty { return NMBPredicateResult( status: NMBPredicateStatus.fail, message: NMBExpectationMessage( fail: "satisfyAnyOf must be called with at least one matcher" ) ) } var elementEvaluators = [Predicate<NSObject>]() for matcher in matchers { let elementEvaluator = Predicate<NSObject> { expression in if let predicate = matcher as? NMBPredicate { return predicate.satisfies({ try expression.evaluate() }, location: actualExpression.location).toSwift() } else { let failureMessage = FailureMessage() let success = matcher.matches( // swiftlint:disable:next force_try { try! expression.evaluate() }, failureMessage: failureMessage, location: actualExpression.location ) return PredicateResult(bool: success, message: failureMessage.toExpectationMessage()) } } elementEvaluators.append(elementEvaluator) } return try satisfyAnyOf(elementEvaluators).satisfies(actualExpression).toObjectiveC() } } } #endif
mit
3d16d0c2635fde52a06dc7536d79b3e4
39.479167
128
0.577972
5.287075
false
false
false
false
benlangmuir/swift
stdlib/public/Distributed/DistributedActor.swift
4
17462
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift import _Concurrency // ==== Distributed Actor ----------------------------------------------------- /// Common protocol to which all distributed actors conform implicitly. /// /// The `DistributedActor` protocol generalizes over all distributed actor types. /// Distributed actor types implicitly conform to this protocol. /// /// It is not possible to conform to this protocol by any other declaration other than a `distributed actor`. /// /// It is possible to require a type to conform to the /// ``DistributedActor`` protocol by refining it with another protocol, /// or by using a generic constraint. /// /// ## Synthesized properties /// For every concrete distributed actor declaration, the compiler synthesizes two properties: `actorSystem` and `id`. /// They witness the ``actorSystem`` and ``id`` protocol requirements of the ``DistributedActor`` protocol. /// /// It is not possible to implement these properties explicitly in user code. /// These properties are `nonisolated` and accessible even if the instance is _remote_, /// because _all_ distributed actor references must store the actor system remote calls /// will be delivered through, as well as the id identifying the target of those calls. /// /// ## The ActorSystem associated type /// Every distributed actor must declare what type of actor system /// it is part of by implementing the ``ActorSystem`` associated type requirement. /// /// This causes a number of other properties of the actor to be inferred: /// - the ``SerializationRequirement`` that will be used at compile time to /// verify `distributed` target declarations are well formed, /// - if the distributed actor is `Codable`, based on the ``ID`` being Codable or not, /// - the type of the ``ActorSystem`` accepted in the synthesized default initializer. /// /// A distributed actor must declare what type of actor system it is ready to /// work with by fulfilling the ``ActorSystem`` type member requirement: /// /// ```swift /// distributed actor Greeter { /// typealias ActorSystem = GreetingSystem // which conforms to DistributedActorSystem /// /// func greet() -> String { "Hello!" } /// } /// ``` /// /// ### The DefaultDistributedActorSystem type alias /// Since it is fairly common to only be using one specific type of actor system /// within a module or entire codebase, it is possible to declare the default type /// of actor system all distributed actors will be using in a module by declaring /// a `DefaultDistributedActorSystem` module wide typealias: /// /// ```swift /// import Distributed /// import AmazingActorSystemLibrary /// /// typealias DefaultDistributedActorSystem = AmazingActorSystem /// /// distributed actor Greeter {} // ActorSystem == AmazingActorSystem /// ``` /// /// This declaration makes all `distributed actor` declarations /// that do not explicitly specify an ``ActorSystem`` type alias to assume the /// `AmazingActorSystem` as their `ActorSystem`. /// /// It is possible for a specific actor to override the system it is using, /// by declaring an ``ActorSystem`` type alias as usual: /// /// ```swift /// typealias DefaultDistributedActorSystem = AmazingActorSystem /// /// distributed actor Amazing { /// // ActorSystem == AmazingActorSystem /// } /// /// distributed actor Superb { /// typealias ActorSystem = SuperbActorSystem /// } /// ``` /// /// In general the `DefaultDistributedActorSystem` should not be declared public, /// as picking the default should be left up to each specific module of a project. /// /// ## Default initializer /// While classes and actors receive a synthesized *argument-free default /// initializer* (`init()`), distributed actors synthesize a default initializer /// that accepts a distributed actor system the actor is part of: `init(actorSystem:)`. /// /// The accepted actor system must be of the `Self.ActorSystem` type, which /// must conform to the ``DistributedActorSystem`` protocol. This is required /// because distributed actors are always managed by a concrete /// distributed actor system and cannot exist on their own without one. /// /// It is possible to explicitly declare a parameter-free initializer (`init()`), /// however the `actorSystem` property still must be assigned a concrete actor /// system instance the actor shall be part of. /// /// In general it is recommended to always have an `actorSystem` parameter as /// the last non-defaulted non-closure parameter in every actor's /// initializer parameter list. This way it is simple to swap in a "test actor /// system" instance in unit tests, and avoid relying on global state which could /// make testing more difficult. /// /// ## Implicit properties /// Every concrete `distributed actor` type receives two synthesized properties, /// which implement the protocol requirements of this protocol: `id` and `actorSystem`. /// /// ### Property: Actor System /// The ``actorSystem`` property is an important part of every distributed actor's lifecycle management. /// /// Both initialization as well as de-initialization require interactions with the actor system, /// and it is the actor system that handles all remote interactions of an actor, by both sending /// or receiving remote calls made on the actor. /// /// The ``actorSystem`` property must be assigned in every designated initializer /// of a distributed actor explicitly. It is highly recommended to make it a /// parameter of every distributed actor initializer, and simply forward the /// value to the stored property, like this: /// /// ```swift /// init(name: String, actorSystem: Self.ActorSystem) { /// self.name = name /// self.actorSystem = actorSystem /// } /// ``` /// /// Forgetting to initialize the actor system, will result in a compile time error: /// /// ```swift /// // BAD /// init(name: String, actorSystem: Self.ActorSystem) { /// self.name = name /// // BAD, will cause compile-time error; the `actorSystem` was not initialized. /// } /// ``` /// /// ### Property: Distributed Actor Identity /// ``id`` is assigned by the actor system during the distributed actor's /// initialization, and cannot be set or mutated by the actor itself. /// /// ``id`` is the effective identity of the actor, and is used in equality checks, /// as well as the actor's synthesized ``Codable`` conformance if the ``ID`` type /// conforms to ``Codable``. /// /// ## Automatic Conformances /// /// ### Hashable and Identifiable conformance /// Every distributed actor conforms to the `Hashable` and `Identifiable` protocols. /// Its identity is strictly driven by its ``id``, and therefore hash and equality /// implementations directly delegate to the ``id`` property. /// /// Comparing a local distributed actor instance and a remote reference to it /// (both using the same ``id``) always returns true, as they both conceptually /// point at the same distributed actor. /// /// It is not possible to implement these protocols relying on the actual actor's /// state, because it may be remote and the state may not be available. In other /// words, since these protocols must be implemented using `nonisolated` functions, /// only `nonisolated` `id` and `actorSystem` properties are accessible for their /// implementations. /// /// ### Implicit Codable conformance /// If created with an actor system whose ``DistributedActorSystem/ActorID`` is ``Codable``, the /// compiler will synthesize code for the concrete distributed actor to conform /// to ``Codable`` as well. /// /// This is necessary to support distributed calls where the `SerializationRequirement` /// is ``Codable`` and thus users may want to pass actors as arguments to remote calls. /// /// The synthesized implementations use a single ``SingleValueEncodingContainer`` to /// encode/decode the ``id`` property of the actor. The ``Decoder`` required /// ``Decoder/init(from:)`` is implemented by retrieving an actor system from the /// decoders' `userInfo`, effectively like as follows: /// /// ```swift /// decoder.userInfo[.actorSystemKey] as? ActorSystem // ``` /// /// The such obtained actor system is then used to ``resolve(id:using:)`` the decoded ``ID``. /// /// Use the ``CodingUserInfoKey/actorSystemKey`` to provide the necessary /// actor system for the decoding initializer when decoding a distributed actor. /// /// - SeeAlso: ``DistributedActorSystem`` /// - SeeAlso: ``Actor`` /// - SeeAlso: ``AnyActor`` @available(SwiftStdlib 5.7, *) public protocol DistributedActor: AnyActor, Identifiable, Hashable where ID == ActorSystem.ActorID, SerializationRequirement == ActorSystem.SerializationRequirement { /// The type of transport used to communicate with actors of this type. associatedtype ActorSystem: DistributedActorSystem /// The serialization requirement to apply to all distributed declarations inside the actor. associatedtype SerializationRequirement /// Logical identity of this distributed actor. /// /// Many distributed actor references may be pointing at, logically, the same actor. /// For example, calling `resolve(id:using:)` multiple times, is not guaranteed /// to return the same exact resolved actor instance, however all the references would /// represent logically references to the same distributed actor, e.g. on a different node. /// /// Depending on the capabilities of the actor system producing the identifiers, /// the `ID` may also be used to store instance specific metadata. /// /// ## Synthesized property /// /// In concrete distributed actor declarations, a witness for this protocol requirement is synthesized by the compiler. /// /// It is not possible to assign a value to the `id` directly; instead, it is assigned during an actors `init` (or `resolve`), /// by the managing actor system. nonisolated override var id: ID { get } /// The ``DistributedActorSystem`` that is managing this distributed actor. /// /// It is immutable and equal to the system assigned during the distributed actor's local initializer /// (or to the system passed to the ``resolve(id:using:)`` static function). /// /// ## Synthesized property /// /// In concrete distributed actor declarations, a witness for this protocol requirement is synthesized by the compiler. /// /// It is required to assign an initial value to the `actorSystem` property inside a distributed actor's designated initializer. /// Semantically, it can be treated as a `let` declaration, that must be assigned in order to fully-initialize the instance. /// /// If a distributed actor declares no initializer, its default initializer will take the shape of `init(actorSystem:)`, /// and initialize this property using the passed ``DistributedActorSystem``. If any user-defined initializer exists, /// the default initializer is not synthesized, and all the user-defined initializers must take care to initialize this property. nonisolated var actorSystem: ActorSystem { get } /// Resolves the passed in `id` against the `system`, returning /// either a local or remote actor reference. /// /// The system will be asked to `resolve` the identity and return either /// a local instance or request a proxy to be created for this identity. /// /// A remote distributed actor reference will forward all invocations through /// the system, allowing it to take over the remote messaging with the /// remote actor instance. /// /// - Postcondition: upon successful return, the returned actor's ``id`` and ``actorSystem`` properties /// will be equal to the values passed as parameters to this method. /// - Parameter id: identity uniquely identifying a, potentially remote, actor in the system /// - Parameter system: `system` which should be used to resolve the `identity`, and be associated with the returned actor static func resolve(id: ID, using system: ActorSystem) throws -> Self } // ==== Hashable conformance --------------------------------------------------- @available(SwiftStdlib 5.7, *) extension DistributedActor { /// A distributed actor's hash and equality is implemented by directly delegating to its ``id``. /// /// For more details see the "Hashable and Identifiable conformance" section of ``DistributedActor``. nonisolated public func hash(into hasher: inout Hasher) { self.id.hash(into: &hasher) } /// A distributed actor's hash and equality is implemented by directly delegating to its ``id``. /// /// For more details see the "Hashable and Identifiable conformance" section of ``DistributedActor``. nonisolated public static func ==(lhs: Self, rhs: Self) -> Bool { lhs.id == rhs.id } } // ==== Codable conformance ---------------------------------------------------- extension CodingUserInfoKey { /// Key which is required to be set on a `Decoder`'s `userInfo` while attempting /// to `init(from:)` a `DistributedActor`. The stored value under this key must /// conform to ``DistributedActorSystem``. /// /// Forgetting to set this key will result in that initializer throwing, because /// an actor system is required in order to call ``DistributedActor/resolve(id:using:)`` using it. @available(SwiftStdlib 5.7, *) public static let actorSystemKey = CodingUserInfoKey(rawValue: "$distributed_actor_system")! } @available(SwiftStdlib 5.7, *) extension DistributedActor /*: implicitly Decodable */ where Self.ID: Decodable { /// Initializes an instance of this distributed actor by decoding its ``id``, /// and passing it to the ``DistributedActorSystem`` obtained from `decoder.userInfo[actorSystemKey]`. /// /// ## Requires: The decoder must have the ``CodingUserInfoKey/actorSystemKey`` set to /// the ``ActorSystem`` that this actor expects, as it will be used to call ``DistributedActor/resolve(id:using:)`` /// on, in order to obtain the instance this initializer should return. /// /// - Parameter decoder: used to decode the ``ID`` of this distributed actor. /// - Throws: If the actor system value in `decoder.userInfo` is missing or mis-typed; /// the `ID` fails to decode from the passed `decoder`; // or if the ``DistributedActor/resolve(id:using:)`` method invoked by this initializer throws. nonisolated public init(from decoder: Decoder) throws { guard let system = decoder.userInfo[.actorSystemKey] as? ActorSystem else { throw DistributedActorCodingError(message: "Missing system (for key .actorSystemKey) " + "in Decoder.userInfo, while decoding \(Self.self).") } let id: ID = try Self.ID(from: decoder) self = try Self.resolve(id: id, using: system) } } @available(SwiftStdlib 5.7, *) extension DistributedActor /*: implicitly Encodable */ where Self.ID: Encodable { /// Encodes the `actor.id` as a single value into the passed `encoder`. nonisolated public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.id) } } // ==== Local actor special handling ------------------------------------------- @available(SwiftStdlib 5.7, *) extension DistributedActor { /// Executes the passed 'body' only when the distributed actor is local instance. /// /// The `Self` passed to the body closure is isolated, meaning that the /// closure can be used to call non-distributed functions, or even access actor /// state. /// /// When the actor is remote, the closure won't be executed and this function will return nil. public nonisolated func whenLocal<T: Sendable>( _ body: @Sendable (isolated Self) async throws -> T ) async rethrows -> T? { if __isLocalActor(self) { return try await body(self) } else { return nil } } } /******************************************************************************/ /************************* Runtime Functions **********************************/ /******************************************************************************/ // ==== isRemote / isLocal ----------------------------------------------------- /// Verifies if the passed ``DistributedActor`` conforming type is a remote reference. /// Passing a type not conforming to ``DistributedActor`` may result in undefined behavior. /// /// Official API to perform this task is `whenLocal`. @_silgen_name("swift_distributed_actor_is_remote") public func __isRemoteActor(_ actor: AnyObject) -> Bool /// Verifies if the passed ``DistributedActor`` conforming type is a local reference. /// Passing a type not conforming to ``DistributedActor`` may result in undefined behavior. /// /// Official API to perform this task is `whenLocal`. public func __isLocalActor(_ actor: AnyObject) -> Bool { return !__isRemoteActor(actor) } // ==== Proxy Actor lifecycle -------------------------------------------------- @_silgen_name("swift_distributedActor_remote_initialize") func _distributedActorRemoteInitialize(_ actorType: Builtin.RawPointer) -> Any
apache-2.0
3fdb9202492302d6c2c7da69c304c715
45.073879
131
0.692876
4.732249
false
false
false
false
liulichao123/fangkuaishou
快手/快手/classes/右侧/我/view/PersonHeaderView.swift
1
4671
// // PersonHeaderView.swift // 快手 // // Created by liulichao on 16/5/17. // Copyright © 2016年 刘立超. All rights reserved. // import UIKit class PersonHeaderView: UICollectionReusableView { var imageView: UIImageView? var iconView: UIImageView? var editPerson: UIButton? var fensi: UIButton? var guanzhu: UIButton? var jianjie: UIButton? var zuopin: UIButton? var like: UIButton? var buju: UIButton? override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.whiteColor() let screenW = ScreenSize.width var y : CGFloat = 0 var x = y //顶部背景 imageView = UIImageView(frame: CGRectMake(x, y, screenW, 200)) imageView?.backgroundColor = UIColor.grayColor() imageView?.image = UIImage(named: "gougou.jpg") addSubview(imageView!) //头像 y = (imageView?.frame.maxY)! - 20 x = 10 iconView = UIImageView(frame: CGRectMake(x, y, 80, 80)) iconView?.backgroundColor = UIColor.blueColor() iconView?.image = UIImage(named: "xiaohuangren.jpg") iconView?.layer.masksToBounds = true iconView?.layer.cornerRadius = 40 addSubview(iconView!) //编辑 x = (iconView?.frame.maxX)! + 20 y = (imageView?.frame.maxY)! + 10 editPerson = UIButton(type: UIButtonType.Custom) editPerson?.frame = CGRectMake(x, y, 170, 20) editPerson?.backgroundColor = UIColor.orangeColor() editPerson?.setTitle("编辑个人信息", forState: UIControlState.Normal) editPerson?.titleLabel?.font = UIFont.systemFontOfSize(13) editPerson?.layer.borderWidth = 1 editPerson?.layer.borderColor = UIColor.grayColor().CGColor addSubview(editPerson!) //粉丝 y = (editPerson?.frame.maxY)! + 10 fensi = UIButton(type: UIButtonType.Custom) fensi?.frame = CGRectMake(x, y, 80, 20) fensi?.setTitle("粉丝:0", forState: UIControlState.Normal) fensi?.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) // fensi?.backgroundColor = UIColor.purpleColor() addSubview(fensi!) //关注 x = (fensi?.frame.maxX)! + 20 guanzhu = UIButton(type: UIButtonType.Custom) guanzhu?.frame = CGRectMake(x, y, 80, 20) guanzhu?.setTitle("关注:0", forState: UIControlState.Normal) guanzhu?.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) // guanzhu?.backgroundColor = UIColor.greenColor() addSubview(guanzhu!) //简介 x = 0 y = (iconView?.frame.maxY)! jianjie = UIButton(type: UIButtonType.Custom) jianjie?.frame = CGRectMake(x, y, screenW, 30) jianjie?.setTitle("简介", forState: UIControlState.Normal) jianjie?.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) // jianjie?.backgroundColor = UIColor.greenColor() jianjie?.titleLabel?.textAlignment = NSTextAlignment.Left jianjie?.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left jianjie?.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0) addSubview(jianjie!) //作品 y = (jianjie?.frame.maxY)! let w: CGFloat = (screenW - 30) * 0.5 zuopin = UIButton(type: UIButtonType.Custom) zuopin?.frame = CGRectMake(x, y, w, 30) zuopin?.setTitle("作品", forState: UIControlState.Normal) // zuopin?.backgroundColor = UIColor.greenColor() zuopin?.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) zuopin?.layer.borderWidth = 1 addSubview(zuopin!) //喜欢 x = (zuopin?.frame.maxX)! like = UIButton(type: UIButtonType.Custom) like?.frame = CGRectMake(x, y, w, 30) like?.setTitle("喜欢", forState: UIControlState.Normal) like?.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) // like?.backgroundColor = UIColor.greenColor() like?.layer.borderWidth = 1 addSubview(like!) //布局 x = (like?.frame.maxX)! buju = UIButton(type: UIButtonType.Custom) buju?.frame = CGRectMake(x, y, 30, 30) buju?.setTitle("排", forState: UIControlState.Normal) buju?.backgroundColor = UIColor.greenColor() buju?.layer.borderWidth = 1 addSubview(buju!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
1a3004e3c746b3fe5e2ee79b12fa2c77
36.85124
86
0.623144
4.186472
false
false
false
false
PureSwift/Bluetooth
Sources/Bluetooth/LowEnergyScanTimeInterval.swift
1
1264
// // LowEnergyScanTimeInterval.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // /// LE Scan Time Interval /// /// Range: 0x0004 to 0x4000 /// Time = N * 0.625 msec /// Time Range: 2.5 msec to 10240 msec @frozen public struct LowEnergyScanTimeInterval: RawRepresentable, Equatable, Comparable, Hashable { /// 2.5 msec public static let min = LowEnergyScanTimeInterval(0x0004) /// 10.24 seconds public static let max = LowEnergyScanTimeInterval(0x4000) public let rawValue: UInt16 public init?(rawValue: UInt16) { guard rawValue >= LowEnergyScanTimeInterval.min.rawValue, rawValue <= LowEnergyScanTimeInterval.max.rawValue else { return nil } self.rawValue = rawValue } /// Time = N * 0.625 msec public var miliseconds: Double { return Double(rawValue) * 0.625 } // Private, unsafe init(_ rawValue: UInt16) { self.rawValue = rawValue } // Comparable public static func < (lhs: LowEnergyScanTimeInterval, rhs: LowEnergyScanTimeInterval) -> Bool { return lhs.rawValue < rhs.rawValue } }
mit
1d59593c06947ee5c6b3e222f08eaa3b
24.26
99
0.625495
4.385417
false
false
false
false
InsectQY/HelloSVU_Swift
HelloSVU_Swift/Classes/Module/Home/WallPaper/Category/Model/ImgCategory.swift
1
446
// // ImgCategory.swift // HelloSVU_Swift // // Created by Insect on 2017/9/27. // Copyright © 2017年 Insect. All rights reserved. // import UIKit import HandyJSON struct ImgCategory: HandyJSON { /// 图片 URL var cover = "" /// 分类名称 var name = "" /// 分类id var id = "" } struct test: HandyJSON { var msg = "" var res: res? } struct res: HandyJSON { var category = [ImgCategory]() }
apache-2.0
c16c827e43b36ba1022aa53ddb475540
13.724138
50
0.583138
3.284615
false
false
false
false
krevis/MIDIApps
Applications/SysExLibrarian/AppController.swift
1
8115
/* Copyright (c) 2002-2021, Kurt Revis. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. */ import Cocoa import SnoizeMIDI import Sparkle.SPUStandardUpdaterController class AppController: NSObject { override init() { super.init() } @IBOutlet var updaterController: SPUStandardUpdaterController? private(set) var midiContext: MIDIContext? // MARK: Private private var hasFinishedLaunching = false private var filePathsToImport: [String] = [] } extension AppController: NSApplicationDelegate { func applicationWillFinishLaunching(_ notification: Notification) { // Initialize CoreMIDI while the app's icon is still bouncing, so we don't have a large // pause after it stops bouncing but before the app's window opens. // (CoreMIDI needs to find and possibly start its server process, which can take a while.) let context = MIDIContext() midiContext = context if !context.connectedToCoreMIDI { let alert = NSAlert() alert.alertStyle = .critical alert.messageText = NSLocalizedString("Error", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "title of error alert") alert.informativeText = NSLocalizedString("There was a problem initializing the MIDI system. To try to fix this, log out and log back in, or restart the computer.", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "error message if MIDI initialization fails") alert.addButton(withTitle: NSLocalizedString("Quit", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "title of quit button")) _ = alert.runModal() NSApp.terminate(nil) } } func applicationDidFinishLaunching(_ notification: Notification) { hasFinishedLaunching = true if let preflightErrorString = Library.shared.preflightAndLoadEntries() { let alert = NSAlert() alert.alertStyle = .critical alert.messageText = NSLocalizedString("Error", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "title of error alert") alert.informativeText = preflightErrorString alert.addButton(withTitle: NSLocalizedString("Quit", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "title of quit button")) _ = alert.runModal() NSApp.terminate(nil) } else { showMainWindow(nil) if !filePathsToImport.isEmpty { importFiles() } } } func application(_ sender: NSApplication, openFile filename: String) -> Bool { filePathsToImport.append(filename) if hasFinishedLaunching { showMainWindow(nil) importFiles() } return true } func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { if flag { if let mainWindow = MainWindowController.shared.window, mainWindow.isMiniaturized { mainWindow.deminiaturize(nil) } } else { showMainWindow(nil) } return false } func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { true } } extension AppController: NSUserInterfaceValidations { func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool { if item.action == #selector(self.showMainWindowAndAddToLibrary(_:)) { // Don't allow adds if the main window is open and has a sheet on it let mainWindow = MainWindowController.shared.window return (mainWindow == nil || mainWindow!.attachedSheet == nil) } return true } } extension AppController /* Actions */ { @IBAction func showPreferences(_ sender: Any?) { PreferencesWindowController.shared.showWindow(nil) } @IBAction func showAboutBox(_ sender: Any?) { var options: [NSApplication.AboutPanelOptionKey: Any] = [:] // Don't show the version as "Version 1.5 (1.5)". Omit the "(1.5)". options[NSApplication.AboutPanelOptionKey.version] = "" // The RTF file Credits.rtf has foreground text color = black, but that's wrong for 10.14 dark mode. // Similarly the font is not necessarily the system font. Override both. if let creditsURL = Bundle.main.url(forResource: "Credits", withExtension: "rtf"), let credits = try? NSMutableAttributedString(url: creditsURL, options: [:], documentAttributes: nil) { let range = NSRange(location: 0, length: credits.length) credits.addAttribute(.font, value: NSFont.labelFont(ofSize: NSFont.labelFontSize), range: range) credits.addAttribute(.foregroundColor, value: NSColor.labelColor, range: range) options[NSApplication.AboutPanelOptionKey.credits] = credits } NSApp.orderFrontStandardAboutPanel(options: options) } @IBAction func showHelp(_ sender: Any?) { var message: String? if var url = Bundle.main.url(forResource: "docs", withExtension: "htmld") { url.appendPathComponent("index.html") if !NSWorkspace.shared.open(url) { message = NSLocalizedString("The help file could not be opened.", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "error message if opening the help file fails") } } else { message = NSLocalizedString("The help file could not be found.", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "error message if help file can't be found") } if let message = message { let title = NSLocalizedString("Error", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "title of error alert") let alert = NSAlert() alert.messageText = title alert.informativeText = message _ = alert.runModal() } } @IBAction func sendFeedback(_ sender: Any?) { var success = false let feedbackEmailAddress = "[email protected]" // Don't localize this let feedbackEmailSubject = NSLocalizedString("SysEx Librarian Feedback", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "subject of feedback email") let mailToURLString = "mailto:\(feedbackEmailAddress)?Subject=\(feedbackEmailSubject)" // Escape the whitespace characters in the URL before opening let allowedCharacterSet = CharacterSet.whitespaces.inverted if let escapedMailToURLString = mailToURLString.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet), let mailToURL = URL(string: escapedMailToURLString) { success = NSWorkspace.shared.open(mailToURL) } if !success { let message = NSLocalizedString("SysEx Librarian could not ask your email application to create a new message.\nPlease send email to:\n%@", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "message of alert when can't send feedback email") let title = NSLocalizedString("Error", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "title of error alert") let alert = NSAlert() alert.messageText = title alert.informativeText = String.localizedStringWithFormat(message, feedbackEmailAddress) _ = alert.runModal() } } @IBAction func showMainWindow(_ sender: Any?) { MainWindowController.shared.showWindow(nil) } @IBAction func showMainWindowAndAddToLibrary(_ sender: Any?) { MainWindowController.shared.showWindow(nil) MainWindowController.shared.addToLibrary(sender) } } extension AppController /* Private */ { private func importFiles() { MainWindowController.shared.importFiles(filePathsToImport, showingProgress: false) filePathsToImport = [] } }
bsd-3-clause
5a35ce039e6d71ed2cf674b219604419
38.202899
281
0.660382
4.876803
false
false
false
false
PimCoumans/Foil
Foil/Nodes/Node.swift
2
12209
// // Node.swift // Foil // // Created by Pim Coumans on 25/11/16. // Copyright © 2016 pixelrock. All rights reserved. // import Foundation import QuartzCore import GLKit import MetalKit class Node: Interactable, Animatable { // MARK: Geometry // Position and scale are based on the parents local coordinate system // If the parent has a scale of 2, this node has a scale of 1 // it will be rendered twice as big var position = CGPoint.zero { didSet { clearCache(name: "globalPosition"); clearCache(name: "globalFrame") } } var zPosition: CGFloat = 0 { didSet { guard zPosition != oldValue else { return }; clearCache(name: "globalZPosition"); scene?.clearCache(name: "nodes") } } var anchorPoint = CGPoint(x: 0.5, y: 0.5) { didSet { clearCache(name: "globalFrame"); clearCache(name: "globalTransform") } } var scale = CGSize(width: 1, height: 1) { didSet { clearCache(name: "globalScale"); clearCache(name: "globalPosition"); clearCache(name: "globalFrame") } } var frame: CGRect { var frame = bounds frame.origin += position return frame.applying(transform) } var bounds: CGRect { return CGRect(origin: .zero, size: .zero) } // MARK: Hierarchy fileprivate(set) var scene:Scene? { willSet { willMoveToScene(newValue) } didSet { didMoveToScene() for node in children { node.scene = scene } } } fileprivate(set) weak var parent:Node? { willSet { willMoveToParent(newValue) } didSet { clearCache(); didMoveToParent() } } fileprivate(set) var children = [Node]() let uid:Int init() { uid = Node.nextUid() } func addChild(_ node:Node) { assert(!children.contains(node)) children.append(node) node.parent = self if let scene = self as? Scene { node.scene = scene } else { node.scene = scene } node.scene?.clearCache(name: "nodes") } func removeFromParent() { guard let parent = parent, let index = parent.children.index(of: self) else { return } parent.children.remove(at: index) scene?.clearCache(name: "nodes") self.parent = nil self.scene = nil } // MARK: Updates func willMoveToParent(_ parent:Node?) {} func didMoveToParent() {} func willMoveToScene(_ scene:Scene?) {} func didMoveToScene() {} // MARK: Rendering func render(with context:RenderContext) { } func renderRecursively(with context:RenderContext) { guard !hidden else { return } render(with: context) for node in children { node.renderRecursively(with:context) } } // MARK: Interactable var handlesInput: Bool { return false } var enabled: Bool = true var hidden: Bool = false var highlighted: Bool = false var selected: Bool = false var alpha: CGFloat = 1 var rotation: CGFloat = 0 { didSet { clearCache(name: "globalRotation"); clearCache(name: "globalTransform") } } var transform: CGAffineTransform { let boundingRect = globalFrame var center = boundingRect.origin center.x += boundingRect.width * anchorPoint.x center.y += boundingRect.height * -anchorPoint.y return CGAffineTransform(translationX: center.x, y: center.y) .rotated(by: rotation) .translatedBy(x: -center.x, y: -center.y) } var highlightedChildNode: Node? = nil var selectedChildNode: Node? = nil func canHandleTouch(atPosition position: CGPoint) -> Bool { return true } func touchBegan(atPosition position: CGPoint) {} func touchMoved(toPosition position: CGPoint, delta: CGPoint) {} func touchEnded(atPosition position: CGPoint, delta: CGPoint) {} func touchCancelled() {} // MARK: - Animatable func set<T:Lerpable>(_ property: Property, value: T) { switch property { case Property.position: position = value as? CGPoint ?? position case Property.positionX: position.x = value as? CGFloat ?? position.x case Property.positionY: position.y = value as? CGFloat ?? position.y case Property.scale: scale = value as? CGSize ?? scale case Property.scaleWidth: scale.width = value as? CGFloat ?? scale.width case Property.scaleHeight: scale.height = value as? CGFloat ?? scale.height case Property.rotation: rotation = value as? CGFloat ?? rotation case Property.relativeRotation: rotation = value as? CGFloat ?? rotation default: break } } func get<T:Lerpable>(_ property: Property) -> T? { switch property { case Property.position: return position as? T case Property.positionX: return position.x as? T case Property.positionY: return position.y as? T case Property.scale: return scale as? T case Property.scaleWidth: return scale.width as? T case Property.scaleHeight: return scale.height as? T case Property.rotation, Property.relativeRotation: return rotation as? T default: return nil } } var boundingFrameOfChildren: CGRect { var boundingFrame = self.frame for node in children { guard !node.hidden else { continue } var nodeFrame = node.boundingFrameOfChildren.applying(node.transform.inverted()) guard !nodeFrame.isNull && !nodeFrame.isInfinite else { continue } var topLeft = CGPoint(x: nodeFrame.minX, y: nodeFrame.maxY) * scale.width var bottomRight = CGPoint(x: nodeFrame.maxX, y: nodeFrame.minY) * scale.height topLeft += position bottomRight += position nodeFrame = CGRect(x: topLeft.x, y: topLeft.y, width: bottomRight.x - topLeft.x, height: bottomRight.y - topLeft.y) boundingFrame = boundingFrame.union(nodeFrame) } return boundingFrame.applying(transform) } private var geometryCache = [String: Any]() func cached<T>(_ name: String, or accessor: () -> T) -> T { if let value = geometryCache[name] as? T { return value } let value = accessor() geometryCache[name] = value return value } func clearCache(name: String? = nil) { if let name = name { geometryCache.removeValue(forKey: name) } else { geometryCache.removeAll(keepingCapacity: true) } for node in children { node.clearCache(name: name) } } } extension Node: Hashable { fileprivate static var uid = 1 fileprivate static func nextUid() -> Int { uid += 1 return uid } var hashValue: Int { return uid } public static func ==(lhs: Node, rhs: Node) -> Bool { return lhs.hashValue == rhs.hashValue } } extension Node { // MARK: Global calculation var globalPosition: CGPoint { return cached(#function) { var position = CGPoint.zero enumerateUp { node in var localPosition = node.position if let parent = node.parent { localPosition.x *= parent.scale.width localPosition.y *= parent.scale.height } position += localPosition } return position } } var globalZPosition: CGFloat { return cached(#function) { var position: CGFloat = 0 enumerateUp { node in position += node.zPosition } return position } } var globalScale: CGSize { return cached(#function) { var scale = CGSize(width:1,height:1) enumerateUp { node in scale = CGSize(width:scale.width * node.scale.width, height: scale.height * node.scale.height) } return scale } } var globalFrame: CGRect { return cached(#function) { let bounds = self.bounds var rect = CGRect() rect.origin = globalPosition let scale = globalScale let scaledSize = CGSize(width: bounds.width * scale.width, height: -bounds.height * scale.height) rect.origin.x -= scaledSize.width * anchorPoint.x rect.size = scaledSize rect.origin.y -= scaledSize.height * anchorPoint.y return rect } } var globalRotation: CGFloat { return cached(#function) { var rotation: CGFloat = 0 enumerateUp { node in rotation += node.rotation } return rotation } } var globalTransform: CGAffineTransform { return cached(#function) { var transform = CGAffineTransform.identity enumerateUp { node in transform = transform.concatenating(node.transform) } return transform } } func enumerateUp(using block: @escaping(_ parent:Node)->()) { var node:Node? = self while let currentNode = node { block(currentNode) node = currentNode.parent } } func convert(worldPosition position:CGPoint) -> CGPoint { var localPosition = position - globalPosition let scale = self.globalScale localPosition.x /= scale.width localPosition.y /= scale.height return localPosition.applying(globalTransform.inverted()) } func convert(position:CGPoint, toNode:Node) -> CGPoint { return .zero } func convert(position:CGPoint, fromNode:Node) -> CGPoint { return .zero } } extension Node { // MARK: Node finding /// Searches the reciever for nodes in it's local coordinate space /// /// - Parameter position: position in world space /// - Parameter predicate: Closure to which the node needs to comply /// - Returns: lowest childNote at given point func node(atPosition position: CGPoint, where predicate: ((Node) -> Bool)? = nil) -> Node? { func applyPredicate(withNode node: Node, predicate: ((Node) -> Bool)?) -> Node? { if let predicate = predicate { var parent: Node? = node while parent != nil { if let parent = parent { if predicate(parent) { return parent } } parent = parent?.parent } return nil } else { return self } } if children.count == 0 { return applyPredicate(withNode: self, predicate: predicate) } for node in children { let localPosition = self.convert(worldPosition: position) let nodePosition = node.convert(worldPosition: position) if node.boundingFrameOfChildren.contains(localPosition) && node.canHandleTouch(atPosition: nodePosition) { if let foundNode = node.node(atPosition: position, where: predicate) { return foundNode } else if let foundNode = applyPredicate(withNode: node, predicate: predicate) { return foundNode } } } return nil } func interactableNode(atPosition position: CGPoint) -> Node? { return node(atPosition: position, where: { $0.enabled && $0.handlesInput }) } }
mit
6753b684af6e09721031643d3bda450d
30.222506
133
0.560698
4.810087
false
false
false
false
malt03/ColorPickerView
Example/Pods/ImageColorPicker/Pod/Classes/ImageColorPicker.swift
1
2660
// // ImageColorPicker.swift // Pods // // Created by Koji Murata on 2016/04/06. // // import UIKit public class ImageColorPicker { private var pickerBytesPerRow: Int! private var pickerWidth: Int! private var pickerHeight: Int! private var pickerImageCoefficient: Int! private var pickerPixelBuffer: UnsafeMutablePointer<UInt8>? private var initImage: Bool private let nilWhenOutside: Bool public init(nilWhenOutside n: Bool = false) { initImage = false nilWhenOutside = n } public init(image: UIImage, nilWhenOutside n: Bool = false) { initImage = true nilWhenOutside = n setImage(image) } deinit { pickerPixelBuffer?.dealloc(pickerWidth * pickerHeight * 4) } public func setImage(image: UIImage?) { guard let i = image else { initImage = false return } pickerPixelBuffer?.dealloc(pickerWidth * pickerHeight * 4) let imageRef = i.CGImage pickerWidth = CGImageGetWidth(imageRef) pickerHeight = CGImageGetHeight(imageRef) pickerImageCoefficient = Int(CGFloat(pickerWidth) / i.size.width) pickerBytesPerRow = pickerWidth * 4 pickerPixelBuffer = UnsafeMutablePointer<UInt8>.alloc(pickerWidth * pickerHeight * 4) let colorSpace = CGColorSpaceCreateDeviceRGB() let option = CGBitmapInfo.ByteOrder32Little.rawValue | CGImageAlphaInfo.PremultipliedLast.rawValue let context = CGBitmapContextCreate(pickerPixelBuffer!, pickerWidth, pickerHeight, 8, pickerWidth * 4, colorSpace, option) CGContextSetBlendMode(context, .Copy) CGContextDrawImage(context, CGRect(origin: .zero, size: CGSize(width: pickerWidth, height: pickerHeight)), imageRef) initImage = true } public func pick(inout point: CGPoint) -> UIColor? { var x = Int(point.x) * pickerImageCoefficient var y = Int(point.y) * pickerImageCoefficient if nilWhenOutside { if x < 0 || pickerWidth - 1 < x || y < 0 || pickerHeight - 1 < y { return nil } } else { if x < 0 { x = 0 } else if pickerWidth - 1 < x { x = pickerWidth - 1 } if y < 0 { y = 0 } else if pickerHeight - 1 < y { y = pickerHeight - 1 } point = CGPoint(x: x / pickerImageCoefficient, y: y / pickerImageCoefficient) } let pixelInfo = pickerBytesPerRow * y + (x * 4) let a = CGFloat(pickerPixelBuffer![pixelInfo+0]) / CGFloat(255.0) let b = CGFloat(pickerPixelBuffer![pixelInfo+1]) / CGFloat(255.0) let g = CGFloat(pickerPixelBuffer![pixelInfo+2]) / CGFloat(255.0) let r = CGFloat(pickerPixelBuffer![pixelInfo+3]) / CGFloat(255.0) return UIColor(red: r, green: g, blue: b, alpha: a) } }
mit
58b5929c4334a5fd2c69401eab7b9e62
31.839506
126
0.678947
4.054878
false
false
false
false
vector-im/vector-ios
Riot/Modules/Onboarding/OnboardingCoordinator.swift
1
23405
// File created from FlowTemplate // $ createRootCoordinator.sh Onboarding/SplashScreen Onboarding OnboardingSplashScreen /* Copyright 2021 New Vector Ltd 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 /// OnboardingCoordinator input parameters struct OnboardingCoordinatorParameters { /// The navigation router that manage physical navigation let router: NavigationRouterType /// The credentials to use if a soft logout has taken place. let softLogoutCredentials: MXCredentials? init(router: NavigationRouterType? = nil, softLogoutCredentials: MXCredentials? = nil) { self.router = router ?? NavigationRouter(navigationController: RiotNavigationController(isLockedToPortraitOnPhone: true)) self.softLogoutCredentials = softLogoutCredentials } } @objcMembers /// A coordinator to manage the full onboarding flow with pre-auth screens, authentication and setup screens once signed in. final class OnboardingCoordinator: NSObject, OnboardingCoordinatorProtocol { // MARK: - Properties // MARK: Private private let parameters: OnboardingCoordinatorParameters // TODO: these can likely be consolidated using an additional authType. /// The any registration parameters for AuthenticationViewController from a server provisioning link. private var externalRegistrationParameters: [AnyHashable: Any]? /// A custom homeserver to be shown when logging in. private var customHomeserver: String? /// A custom identity server to be used once logged in. private var customIdentityServer: String? // MARK: Navigation State private var navigationRouter: NavigationRouterType { parameters.router } // Keep a strong ref as we need to init authVC early to preload its view private let authenticationCoordinator: AuthenticationCoordinatorProtocol /// A boolean to prevent authentication being shown when already in progress. private var isShowingAuthentication = false // MARK: Screen results private var splashScreenResult: OnboardingSplashScreenViewModelResult? private var useCaseResult: OnboardingUseCaseViewModelResult? private var authenticationType: MXKAuthenticationType? private var session: MXSession? private var shouldShowDisplayNameScreen = false private var shouldShowAvatarScreen = false /// Whether all of the onboarding steps have been completed or not. `false` if there are more screens to be shown. private var onboardingFinished = false /// Whether authentication is complete. `true` once authenticated, verified and the app is ready to be shown. private var authenticationFinished = false // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] var completion: (() -> Void)? // MARK: - Setup init(parameters: OnboardingCoordinatorParameters) { self.parameters = parameters // Preload the authVC (it is *really* slow to load in realtime) let authenticationParameters = AuthenticationCoordinatorParameters(navigationRouter: parameters.router, canPresentAdditionalScreens: false) authenticationCoordinator = AuthenticationCoordinator(parameters: authenticationParameters) super.init() } // MARK: - Public func start() { // TODO: Manage a separate flow for soft logout that just uses AuthenticationCoordinator if #available(iOS 14.0, *), parameters.softLogoutCredentials == nil, BuildSettings.authScreenShowRegister { showSplashScreen() } else { showAuthenticationScreen() } } func toPresentable() -> UIViewController { navigationRouter.toPresentable() } /// Force a registration process based on a predefined set of parameters from a server provisioning link. /// For more information see `AuthenticationViewController.externalRegistrationParameters`. func update(externalRegistrationParameters: [AnyHashable: Any]) { self.externalRegistrationParameters = externalRegistrationParameters authenticationCoordinator.update(externalRegistrationParameters: externalRegistrationParameters) } /// Set up the authentication screen with the specified homeserver and/or identity server. func updateHomeserver(_ homeserver: String?, andIdentityServer identityServer: String?) { self.customHomeserver = homeserver self.customIdentityServer = identityServer authenticationCoordinator.updateHomeserver(homeserver, andIdentityServer: identityServer) } /// When SSO login succeeded, when SFSafariViewController is used, continue login with success parameters. func continueSSOLogin(withToken loginToken: String, transactionID: String) -> Bool { guard isShowingAuthentication else { return false } return authenticationCoordinator.continueSSOLogin(withToken: loginToken, transactionID: transactionID) } // MARK: - Pre-Authentication @available(iOS 14.0, *) /// Show the onboarding splash screen as the root module in the flow. private func showSplashScreen() { MXLog.debug("[OnboardingCoordinator] showSplashScreen") let coordinator = OnboardingSplashScreenCoordinator() coordinator.completion = { [weak self, weak coordinator] result in guard let self = self, let coordinator = coordinator else { return } self.splashScreenCoordinator(coordinator, didCompleteWith: result) } coordinator.start() add(childCoordinator: coordinator) navigationRouter.setRootModule(coordinator, popCompletion: nil) } @available(iOS 14.0, *) /// Displays the next view in the flow after the splash screen. private func splashScreenCoordinator(_ coordinator: OnboardingSplashScreenCoordinator, didCompleteWith result: OnboardingSplashScreenViewModelResult) { splashScreenResult = result // Set the auth type early to allow network requests to finish during display of the use case screen. authenticationCoordinator.update(authenticationType: result.mxkAuthenticationType) switch result { case .register: showUseCaseSelectionScreen() case .login: showAuthenticationScreen() } } @available(iOS 14.0, *) /// Show the use case screen for new users. private func showUseCaseSelectionScreen() { MXLog.debug("[OnboardingCoordinator] showUseCaseSelectionScreen") let coordinator = OnboardingUseCaseSelectionCoordinator() coordinator.completion = { [weak self, weak coordinator] result in guard let self = self, let coordinator = coordinator else { return } self.useCaseSelectionCoordinator(coordinator, didCompleteWith: result) } coordinator.start() add(childCoordinator: coordinator) if navigationRouter.modules.isEmpty { navigationRouter.setRootModule(coordinator, popCompletion: nil) } else { navigationRouter.push(coordinator, animated: true) { [weak self] in self?.remove(childCoordinator: coordinator) } } } /// Displays the next view in the flow after the use case screen. @available(iOS 14.0, *) private func useCaseSelectionCoordinator(_ coordinator: OnboardingUseCaseSelectionCoordinator, didCompleteWith result: OnboardingUseCaseViewModelResult) { useCaseResult = result showAuthenticationScreen() } // MARK: - Authentication /// Show the authentication screen. Any parameters that have been set in previous screens are be applied. private func showAuthenticationScreen() { guard !isShowingAuthentication else { return } MXLog.debug("[OnboardingCoordinator] showAuthenticationScreen") let coordinator = authenticationCoordinator coordinator.completion = { [weak self, weak coordinator] result in guard let self = self, let coordinator = coordinator else { return } switch result { case .didLogin(let session, let authenticationType): self.authenticationCoordinator(coordinator, didLoginWith: session, and: authenticationType) case .didComplete: self.authenticationCoordinatorDidComplete(coordinator) } } // Due to needing to preload the authVC, this breaks the Coordinator init/start pattern. // This can be re-assessed once we re-write a native flow for authentication. if let externalRegistrationParameters = externalRegistrationParameters { coordinator.update(externalRegistrationParameters: externalRegistrationParameters) } coordinator.customServerFieldsVisible = useCaseResult == .customServer if let softLogoutCredentials = parameters.softLogoutCredentials { coordinator.update(softLogoutCredentials: softLogoutCredentials) } coordinator.start() add(childCoordinator: coordinator) if customHomeserver != nil || customIdentityServer != nil { coordinator.updateHomeserver(customHomeserver, andIdentityServer: customIdentityServer) } if navigationRouter.modules.isEmpty { navigationRouter.setRootModule(coordinator, popCompletion: nil) } else { navigationRouter.push(coordinator, animated: true) { [weak self] in self?.remove(childCoordinator: coordinator) self?.isShowingAuthentication = false } } isShowingAuthentication = true } /// Displays the next view in the flow after the authentication screen, /// whilst crypto and the rest of the app is launching in the background. private func authenticationCoordinator(_ coordinator: AuthenticationCoordinatorProtocol, didLoginWith session: MXSession, and authenticationType: MXKAuthenticationType) { self.session = session self.authenticationType = authenticationType // Check whether another screen should be shown. if #available(iOS 14.0, *) { if authenticationType == .register, let userId = session.credentials.userId, let userSession = UserSessionsService.shared.userSession(withUserId: userId), BuildSettings.onboardingShowAccountPersonalization { checkHomeserverCapabilities(for: userSession) return } else if Analytics.shared.shouldShowAnalyticsPrompt { showAnalyticsPrompt(for: session) return } } // Otherwise onboarding is finished. onboardingFinished = true completeIfReady() } /// Checks the capabilities of the user's homeserver in order to determine /// whether or not the display name and avatar can be updated. /// /// Once complete this method will start the post authentication flow automatically. @available(iOS 14.0, *) private func checkHomeserverCapabilities(for userSession: UserSession) { userSession.matrixSession.matrixRestClient.capabilities { [weak self] capabilities in guard let self = self else { return } self.shouldShowDisplayNameScreen = capabilities?.setDisplayName?.isEnabled == true self.shouldShowAvatarScreen = capabilities?.setAvatarUrl?.isEnabled == true self.beginPostAuthentication(for: userSession) } failure: { [weak self] _ in MXLog.warning("[OnboardingCoordinator] Homeserver capabilities not returned. Skipping personalisation") self?.beginPostAuthentication(for: userSession) } } /// Displays the next view in the flow after the authentication screen. private func authenticationCoordinatorDidComplete(_ coordinator: AuthenticationCoordinatorProtocol) { isShowingAuthentication = false // Handle the chosen use case where applicable if authenticationType == .register, let useCase = useCaseResult?.userSessionPropertyValue, let userSession = UserSessionsService.shared.mainUserSession { // Store the value in the user's session userSession.userProperties.useCase = useCase // Update the analytics user properties with the use case Analytics.shared.updateUserProperties(ftueUseCase: useCase) } // This method is only called when the app is ready so we can complete if finished authenticationFinished = true completeIfReady() } // MARK: - Post-Authentication /// Starts the part of the flow that comes after authentication for new users. @available(iOS 14.0, *) private func beginPostAuthentication(for userSession: UserSession) { showCongratulationsScreen(for: userSession) } /// Show the congratulations screen for new users. The screen will be configured based on the homeserver's capabilities. @available(iOS 14.0, *) private func showCongratulationsScreen(for userSession: UserSession) { MXLog.debug("[OnboardingCoordinator] showCongratulationsScreen") let parameters = OnboardingCongratulationsCoordinatorParameters(userSession: userSession, personalizationDisabled: !shouldShowDisplayNameScreen && !shouldShowAvatarScreen) let coordinator = OnboardingCongratulationsCoordinator(parameters: parameters) coordinator.completion = { [weak self, weak coordinator] result in guard let self = self, let coordinator = coordinator else { return } self.congratulationsCoordinator(coordinator, didCompleteWith: result) } add(childCoordinator: coordinator) coordinator.start() // Navigating back doesn't make any sense now, so replace the whole stack. navigationRouter.setRootModule(coordinator, hideNavigationBar: true, animated: true) { [weak self] in self?.remove(childCoordinator: coordinator) } } /// Displays the next view in the flow after the congratulations screen. @available(iOS 14.0, *) private func congratulationsCoordinator(_ coordinator: OnboardingCongratulationsCoordinator, didCompleteWith result: OnboardingCongratulationsCoordinatorResult) { switch result { case .personalizeProfile(let userSession): if shouldShowDisplayNameScreen { showDisplayNameScreen(for: userSession) return } else if shouldShowAvatarScreen { showAvatarScreen(for: userSession) return } else if Analytics.shared.shouldShowAnalyticsPrompt { showAnalyticsPrompt(for: userSession.matrixSession) return } case .takeMeHome(let userSession): if Analytics.shared.shouldShowAnalyticsPrompt { showAnalyticsPrompt(for: userSession.matrixSession) return } } onboardingFinished = true completeIfReady() } /// Show the display name personalization screen for new users using the supplied user session. @available(iOS 14.0, *) private func showDisplayNameScreen(for userSession: UserSession) { MXLog.debug("[OnboardingCoordinator]: showDisplayNameScreen") let parameters = OnboardingDisplayNameCoordinatorParameters(userSession: userSession) let coordinator = OnboardingDisplayNameCoordinator(parameters: parameters) coordinator.completion = { [weak self, weak coordinator] session in guard let self = self, let coordinator = coordinator else { return } self.displayNameCoordinator(coordinator, didCompleteWith: session) } add(childCoordinator: coordinator) coordinator.start() navigationRouter.setRootModule(coordinator, hideNavigationBar: false, animated: true) { [weak self] in self?.remove(childCoordinator: coordinator) } } /// Displays the next view in the flow after the display name screen. @available(iOS 14.0, *) private func displayNameCoordinator(_ coordinator: OnboardingDisplayNameCoordinator, didCompleteWith userSession: UserSession) { if shouldShowAvatarScreen { showAvatarScreen(for: userSession) } else { showCelebrationScreen(for: userSession) } } /// Show the avatar personalization screen for new users using the supplied user session. @available(iOS 14.0, *) private func showAvatarScreen(for userSession: UserSession) { MXLog.debug("[OnboardingCoordinator]: showAvatarScreen") let parameters = OnboardingAvatarCoordinatorParameters(userSession: userSession) let coordinator = OnboardingAvatarCoordinator(parameters: parameters) coordinator.completion = { [weak self, weak coordinator] session in guard let self = self, let coordinator = coordinator else { return } self.avatarCoordinator(coordinator, didCompleteWith: session) } add(childCoordinator: coordinator) coordinator.start() if navigationRouter.modules.isEmpty || !shouldShowDisplayNameScreen { navigationRouter.setRootModule(coordinator, hideNavigationBar: false, animated: true) { [weak self] in self?.remove(childCoordinator: coordinator) } } else { navigationRouter.push(coordinator, animated: true) { [weak self] in self?.remove(childCoordinator: coordinator) } } } /// Displays the next view in the flow after the avatar screen. @available(iOS 14.0, *) private func avatarCoordinator(_ coordinator: OnboardingAvatarCoordinator, didCompleteWith userSession: UserSession) { showCelebrationScreen(for: userSession) } @available(iOS 14.0, *) private func showCelebrationScreen(for userSession: UserSession) { MXLog.debug("[OnboardingCoordinator] showCelebrationScreen") let parameters = OnboardingCelebrationCoordinatorParameters(userSession: userSession) let coordinator = OnboardingCelebrationCoordinator(parameters: parameters) coordinator.completion = { [weak self, weak coordinator] userSession in guard let self = self, let coordinator = coordinator else { return } self.celebrationCoordinator(coordinator, didCompleteWith: userSession) } add(childCoordinator: coordinator) coordinator.start() navigationRouter.setRootModule(coordinator, hideNavigationBar: true, animated: true) { [weak self] in self?.remove(childCoordinator: coordinator) } } @available(iOS 14.0, *) private func celebrationCoordinator(_ coordinator: OnboardingCelebrationCoordinator, didCompleteWith userSession: UserSession) { if Analytics.shared.shouldShowAnalyticsPrompt { showAnalyticsPrompt(for: userSession.matrixSession) return } onboardingFinished = true completeIfReady() } /// Shows the analytics prompt for the supplied session. /// /// Check `Analytics.shared.shouldShowAnalyticsPrompt` before calling this method. @available(iOS 14.0, *) private func showAnalyticsPrompt(for session: MXSession) { MXLog.debug("[OnboardingCoordinator]: Invite the user to send analytics") let parameters = AnalyticsPromptCoordinatorParameters(session: session) let coordinator = AnalyticsPromptCoordinator(parameters: parameters) coordinator.completion = { [weak self, weak coordinator] in guard let self = self, let coordinator = coordinator else { return } self.analyticsPromptCoordinatorDidComplete(coordinator) } add(childCoordinator: coordinator) coordinator.start() // TODO: Re-asses replacing the stack based on the previous screen once the whole flow is implemented navigationRouter.setRootModule(coordinator, hideNavigationBar: true, animated: true) { [weak self] in self?.remove(childCoordinator: coordinator) } } /// Displays the next view in the flow after the analytics screen. private func analyticsPromptCoordinatorDidComplete(_ coordinator: AnalyticsPromptCoordinator) { onboardingFinished = true completeIfReady() } // MARK: - Finished /// Calls the coordinator's completion handler if both `onboardingFinished` and `authenticationFinished` /// are true. Otherwise displays any pending screens and waits to be called again. private func completeIfReady() { guard onboardingFinished else { MXLog.debug("[OnboardingCoordinator] Delaying onboarding completion until all screens have been shown.") return } guard authenticationFinished else { MXLog.debug("[OnboardingCoordinator] Allowing AuthenticationCoordinator to display any remaining screens.") authenticationCoordinator.presentPendingScreensIfNecessary() return } completion?() } } // MARK: - Helpers extension OnboardingSplashScreenViewModelResult { /// The result converted into the MatrixKit authentication type to use. var mxkAuthenticationType: MXKAuthenticationType { switch self { case .login: return .login case .register: return .register } } } extension OnboardingUseCaseViewModelResult { /// The result converted into the type stored in the user session. var userSessionPropertyValue: UserSessionProperties.UseCase? { switch self { case .personalMessaging: return .personalMessaging case .workMessaging: return .workMessaging case .communityMessaging: return .communityMessaging case .skipped: return .skipped case .customServer: return nil } } }
apache-2.0
e1f26e5e454eb80286e18478737c96ac
42.103131
166
0.676223
5.813462
false
false
false
false
lxian/LXPageViewWithButtonsViewController
Example/LXPageViewWithButtonsViewController/DemosTableViewController.swift
1
3884
// // DemosTableViewController.swift // LXPageViewWithButtonsViewController // // Created by XianLi on 1/8/2016. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import LXPageViewWithButtonsViewController private func randomColor() -> UIColor { let v = [0, 0, 0].map { (_) -> CGFloat in return CGFloat(arc4random_uniform(255)) / 255.0 } return UIColor.init(red: v[0], green: v[1], blue: v[2], alpha: 1) } private func randomDummyViewController(count: Int) -> [UIViewController] { return (0..<count).map({ (idx) -> UIViewController in let vc = UIViewController() vc.title = "Page \(String(idx))" vc.view.backgroundColor = randomColor() let label = UILabel() label.text = vc.title label.sizeToFit() vc.view.addSubview(label) return vc }) } class DemosTableViewController: UITableViewController { var titles: [String] = [] var viewControllers: [UIViewController] = [] override func viewDidLoad() { super.viewDidLoad() titles = [ "Default (Tabs at the top)", "Tabs in the navigation bar" ] /// Default (Tabs at the top) let defaultVC = LXPageViewWithButtonsViewController() defaultVC.viewControllers = randomDummyViewController(8) defaultVC.view.backgroundColor = UIColor.lightGrayColor() /// Tabs in the navigation bar let tabsInNavbarVC = TabsInNavbarPageViewWithButtonsViewController() tabsInNavbarVC.viewControllers = randomDummyViewController(8) viewControllers = [defaultVC, tabsInNavbarVC] tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewControllers.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell")! cell.textLabel?.text = titles[indexPath.row] return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let vc = viewControllers[indexPath.row] self.navigationController?.pushViewController(vc, animated: true) } } class TabsInNavbarPageViewWithButtonsViewController : LXPageViewWithButtonsViewController { override func viewDidLoad() { buttonsScrollView.appearance.button.height = 44 buttonsScrollView.frame = CGRectMake(100, 0, UIScreen.mainScreen().bounds.size.width - 100 , 44) navigationItem.titleView = buttonsScrollView super.viewDidLoad() } override func lx_LayoutViews() { let pageViewControllerView = pageViewController.view pageViewControllerView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activateConstraints([ NSLayoutConstraint(item: pageViewControllerView, attribute: .Top, relatedBy: .Equal, toItem: self.topLayoutGuide, attribute: .Bottom, multiplier: 1, constant: 0), NSLayoutConstraint(item: pageViewControllerView, attribute: .Bottom, relatedBy: .Equal, toItem: self.bottomLayoutGuide, attribute: .Top, multiplier: 1, constant: 0), NSLayoutConstraint(item: pageViewControllerView, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1, constant: 0), NSLayoutConstraint(item: pageViewControllerView, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1, constant: 0) ]) } }
mit
bd23c7e3dc98b5c63d8fce662711b0cd
39.447917
177
0.678084
5.016796
false
false
false
false
lstomberg/swift-PerformanceTestKit
Tests/TestSupport.swift
1
3687
// MIT License // // Copyright (c) 2017 Lucas Stomberg // // 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 extension Equatable { // infix operator ∈: AdditionPrecedence // swiftlint:disable identifier_name static func ∈<T:Collection>(object: Self, collection:T) -> Bool where T.Iterator.Element == Self { // swiftlint:enable identifier_name return collection.contains { $0 == object } } } /* * VARIABLE SETUP */ struct Test { var index = (int: 0, string: 0, module: 0, task: 0) static let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-=_+[];',./{}|:<>?" static func string(unique int: Int, length: Int = 6) -> String { let startOffset = int % characters.count let multiple = int / characters.count var string = "".padding(toLength: multiple, withPad: " ", startingAt: 0) for mIndex in 0..<length { let offset = (startOffset + multiple * mIndex) % characters.count let index = characters.index(characters.startIndex, offsetBy: offset) string = string.appending(String(characters[index])) } return string } static func int(unique int: Int) -> Int { return int } static func module(unique int: Int, withSegment: Bool) -> Module { return Module(name: string(unique: int, length: 6), segment: withSegment ? string(unique: int + 1) : nil) } static func partition(unique int: Int) -> String { return string(unique: int, length: 2) } } extension Task { func withNew(name:String) -> Task { return Task(name: name, module: module, executionDetails: executionDetails, startTime: startTime, partition: partition, results: results) } func withNew(module:Module) -> Task { return Task(name: name, module: module, executionDetails: executionDetails, startTime: startTime, partition: partition, results: results) } func withNew(partition:String?) -> Task { return Task(name: name, module: module, executionDetails: executionDetails, startTime: startTime, partition: partition, results: results) } func withNew(resultsDuration duration:Double) -> Task { return Task(name: name, module: module, executionDetails: executionDetails, startTime: startTime, partition: partition, results: Task.Result(duration:duration)) } func withNew(startTime:Date) -> Task { return Task(name: name, module: module, executionDetails: executionDetails, startTime: startTime, partition: partition, results: results) } }
mit
20e2cf205591625be9e2727caf9d243e
38.180851
119
0.686668
4.30257
false
false
false
false
ultimecia7/BestGameEver
Stick-Hero/Defined.swift
1
2833
// // Defined.swift // Stick-Hero // // Created by 顾枫 on 15/6/25. // Copyright © 2015年 koofrank. All rights reserved. // import Foundation import CoreGraphics let DefinedScreenWidth:CGFloat = 1536 let DefinedScreenHeight:CGFloat = 2048 enum StickHeroGameSceneChildName : String { case HeroName = "hero" case StickName = "stick" case StackName = "stack" case StackMidName = "stack_mid" case ScoreName = "score" case TipName = "tip" case PerfectName = "perfect" case GameOverLayerName = "over" case RetryButtonName = "retry" case HighScoreName = "highscore" } enum StickHeroGameSceneActionKey: String { case WalkAction = "walk" case StickGrowAudioAction = "stick_grow_audio" case StickGrowAction = "stick_grow" case HeroScaleAction = "hero_scale" } enum StickHeroGameSceneEffectAudioName: String { case DeadAudioName = "dead.wav" case StickGrowAudioName = "stick_grow_loop.wav" case StickGrowOverAudioName = "kick.wav" case StickFallAudioName = "fall.wav" case StickTouchMidAudioName = "touch_mid.wav" case VictoryAudioName = "victory.wav" case HighScoreAudioName = "highScore.wav" } enum StickHeroGameSceneZposition: CGFloat { case BackgroundZposition = 0 case StackZposition = 30 case StackMidZposition = 35 case StickZposition = 40 case ScoreBackgroundZposition = 50 case HeroZposition, ScoreZposition, TipZposition, PerfectZposition = 100 case EmitterZposition case GameOverZposition } enum SpeedModeSceneChildName : String { case HeroName = "hero" case StickName = "stick" case StackName = "stack" case StackMidName = "stack_mid" case ScoreName = "score" case TipName = "tip" case PerfectName = "perfect" case GameOverLayerName = "over" case RetryButtonName = "retry" case HighScoreName = "highscore" case TimerName="timer" } enum SpeedModeSceneActionKey: String { case WalkAction = "walk" case StickGrowAudioAction = "stick_grow_audio" case StickGrowAction = "stick_grow" case HeroScaleAction = "hero_scale" } enum SpeedModeSceneEffectAudioName: String { case DeadAudioName = "dead.wav" case StickGrowAudioName = "stick_grow_loop.wav" case StickGrowOverAudioName = "kick.wav" case StickFallAudioName = "fall.wav" case StickTouchMidAudioName = "touch_mid.wav" case VictoryAudioName = "victory.wav" case HighScoreAudioName = "highScore.wav" } enum SpeedModeSceneZposition: CGFloat { case BackgroundZposition = 0 case StackZposition = 30 case StackMidZposition = 35 case StickZposition = 40 case ScoreBackgroundZposition = 50 case TimerZposition = 60 case HeroZposition, ScoreZposition, TipZposition, PerfectZposition = 100 case EmitterZposition case GameOverZposition }
mit
71b0bc5286d95d95bdc2d8de9d202670
27.846939
76
0.719391
4.025641
false
false
false
false
caronae/caronae-ios
Caronae/Ride/CreateRideViewController.swift
1
16468
import UIKit import SVProgressHUD import ActionSheetPicker_3_0 class CreateRideViewController: UIViewController, NeighborhoodSelectionDelegate, HubSelectionDelegate { @IBOutlet weak var neighborhoodButton: UIButton! @IBOutlet weak var reference: UITextField! @IBOutlet weak var route: UITextField! @IBOutlet weak var centerButton: UIButton! @IBOutlet weak var routineSwitch: UISwitch! @IBOutlet weak var slotsStepper: UIStepper! @IBOutlet weak var slotsLabel: UILabel! @IBOutlet weak var notes: UITextView! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var createRideButton: UIButton! @IBOutlet weak var routinePatternView: UIView! @IBOutlet weak var routinePatternHeight: NSLayoutConstraint! @IBOutlet weak var routineDuration2MonthsButton: UIButton! @IBOutlet weak var routineDuration3MonthsButton: UIButton! @IBOutlet weak var routineDuration4MonthsButton: UIButton! @IBOutlet weak var dateButton: UIButton! var routinePatternHeightOriginal: CGFloat? var notesPlaceholder: String? var notesTextColor: UIColor? var weekDays = [String]() var routineDurationMonths: Int? var selectedDate: Date? { didSet { let dateString = dateFormatter.string(from: selectedDate!) dateButton.setTitle(dateString, for: .normal) } } let userDefaults = UserDefaults.standard let dateFormatter = DateFormatter() var selectedNeighborhood = String() { didSet { let selection = selectedNeighborhood.isEmpty ? "Bairro" : selectedNeighborhood self.neighborhoodButton.setTitle(selection, for: .normal) } } var selectedHub = String() { didSet { let selection = selectedHub.isEmpty ? "Centro Universitário" : selectedHub self.centerButton.setTitle(selection, for: .normal) } } var selectedZone = String() override func viewDidLoad() { super.viewDidLoad() checkIfUserHasCar() dateFormatter.dateFormat = "dd/MM/yyyy HH:mm" selectedDate = max(Date.nextHour, Date.currentTimePlus(minutes: 5)) routineDurationMonths = 2 segmentedControl.layer.cornerRadius = 8.0 segmentedControl.layer.borderColor = UIColor(white: 0.690, alpha: 1.0).cgColor segmentedControl.layer.borderWidth = 2.0 segmentedControl.layer.masksToBounds = true // Configure direction titles according to institution segmentedControl.setTitle(PlaceService.Institution.goingLabel, forSegmentAt: 0) segmentedControl.setTitle(PlaceService.Institution.leavingLabel, forSegmentAt: 1) notes.layer.cornerRadius = 8.0 notes.layer.borderColor = UIColor(white: 0.902, alpha: 1.0).cgColor notes.layer.borderWidth = 2.0 notes.textContainerInset = UIEdgeInsets(top: 10, left: 5, bottom: 5, right: 5) notes.delegate = self notesPlaceholder = notes.text notesTextColor = notes.textColor if let lastOfferedRide = userDefaults.dictionary(forKey: CaronaePreferenceLastOfferedRide.key) { if let lastZone = lastOfferedRide[CaronaePreferenceLastOfferedRide.zone] as? String, let lastNeighborhood = lastOfferedRide[CaronaePreferenceLastOfferedRide.neighborhood] as? String, let lastPlace = lastOfferedRide[CaronaePreferenceLastOfferedRide.place] as? String, let lastRoute = lastOfferedRide[CaronaePreferenceLastOfferedRide.route] as? String, let lastSlots = lastOfferedRide[CaronaePreferenceLastOfferedRide.slots] as? Double, let lastDescription = lastOfferedRide[CaronaePreferenceLastOfferedRide.description] as? String { selectedZone = lastZone selectedNeighborhood = lastNeighborhood reference.text = lastPlace route.text = lastRoute slotsStepper.value = lastSlots if !lastDescription.isEmpty { notes.text = lastDescription notes.textColor = .black } } if let lastHubGoing = lastOfferedRide[CaronaePreferenceLastOfferedRide.hubGoing] as? String { selectedHub = lastHubGoing } } slotsLabel.text = String(format: "%.f", slotsStepper.value) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.view.endEditing(true) } func checkIfUserHasCar() { if let user = UserService.instance.user, !user.carOwner { CaronaeAlertController.presentOkAlert(withTitle: "Você possui carro?", message: "Parece que você marcou no seu perfil que não possui um carro. Para criar uma carona, preencha os dados do seu carro no seu perfil.", handler: { self.didTapCancelButton(self) }) } } func generateRideFromView() -> Ride { let description = notes.text == notesPlaceholder ? "" : notes.text let going = self.segmentedControl.selectedSegmentIndex == 0 let ride = Ride() ride.region = selectedZone ride.neighborhood = selectedNeighborhood ride.place = reference.text ride.route = route.text ride.hub = selectedHub ride.notes = description ride.going = going ride.date = selectedDate ride.slots = Int(slotsStepper.value) // Routine fields if routineSwitch.isOn { let weekDaysString = weekDays.sorted().joined(separator: ",") ride.weekDays = weekDaysString // Calculate final date for event based on the selected duration var dateComponents = DateComponents() dateComponents.month = routineDurationMonths let repeatsUntilDate = Calendar.current.date(byAdding: dateComponents, to: ride.date) ride.repeatsUntil = repeatsUntilDate } return ride } func savePreset(ride: Ride) { let lastRidePresets = userDefaults.dictionary(forKey: CaronaePreferenceLastOfferedRide.key) var newPresets: [String: Any] = [CaronaePreferenceLastOfferedRide.zone: ride.region, CaronaePreferenceLastOfferedRide.neighborhood: ride.neighborhood, CaronaePreferenceLastOfferedRide.place: ride.place, CaronaePreferenceLastOfferedRide.route: ride.route, CaronaePreferenceLastOfferedRide.slots: ride.slots, CaronaePreferenceLastOfferedRide.description: ride.notes] if ride.going { newPresets[CaronaePreferenceLastOfferedRide.hubGoing] = ride.hub if let lastHubReturning = lastRidePresets?[CaronaePreferenceLastOfferedRide.hubReturning] { newPresets[CaronaePreferenceLastOfferedRide.hubReturning] = lastHubReturning } } else { newPresets[CaronaePreferenceLastOfferedRide.hubReturning] = ride.hub if let lastHubGoing = lastRidePresets?[CaronaePreferenceLastOfferedRide.hubGoing] { newPresets[CaronaePreferenceLastOfferedRide.hubGoing] = lastHubGoing } } userDefaults.set(newPresets, forKey: CaronaePreferenceLastOfferedRide.key) } func createRide(ride: Ride) { SVProgressHUD.show() createRideButton.isEnabled = false savePreset(ride: ride) RideService.instance.createRide(ride, success: { SVProgressHUD.dismiss() lastAllRidesUpdate = Date.distantPast self.dismiss(animated: true, completion: nil) }, error: { error in SVProgressHUD.dismiss() self.createRideButton.isEnabled = true NSLog("Error creating ride: %@", error.localizedDescription) CaronaeAlertController.presentOkAlert(withTitle: "Não foi possível criar a carona.", message: error.localizedDescription) }) } @IBAction func didTapCreateButton(_ sender: Any) { self.view.endEditing(true) // Check if the user selected the location and hub if selectedZone.isEmpty || selectedNeighborhood.isEmpty || selectedHub.isEmpty { CaronaeAlertController.presentOkAlert(withTitle: "Dados incompletos", message: "Ops! Parece que você esqueceu de preencher o local da sua carona.") return } // Check if the user has selected the routine details if routineSwitch.isOn && weekDays.isEmpty { CaronaeAlertController.presentOkAlert(withTitle: "Dados incompletos", message: "Ops! Parece que você esqueceu de marcar os dias da rotina.") return } SVProgressHUD.show() createRideButton.isEnabled = false let ride = generateRideFromView() RideService.instance.validateRideDate(ride: ride, success: { isValid, status in SVProgressHUD.dismiss() if isValid { self.createRide(ride: ride) } else { switch status { case "duplicate": CaronaeAlertController.presentOkAlert(withTitle: "Você já ofereceu uma carona muito parecida com essa", message: "Você pode verificar as suas caronas na seção 'Minhas' do aplicativo.", handler: { self.createRideButton.isEnabled = true }) default: let alert = CaronaeAlertController(title: "Parece que você já ofereceu uma carona para este dia", message: "Você pode cancelar e verificar as suas caronas ou continuar e criar a carona mesmo assim.", preferredStyle: .alert) alert?.addAction(SDCAlertAction(title: "Cancelar", style: .cancel, handler: { _ in self.createRideButton.isEnabled = true })) alert?.addAction(SDCAlertAction(title: "Criar", style: .recommended, handler: { _ in self.createRide(ride: ride) })) alert?.present(completion: nil) } } }, error: { error in SVProgressHUD.dismiss() self.createRideButton.isEnabled = true CaronaeAlertController.presentOkAlert(withTitle: "Não foi possível validar sua carona.", message: String(format: "Houve um erro de comunicação com nosso servidor. Por favor, tente novamente. (%@)", error!.localizedDescription)) }) } // MARK: IBActions @IBAction func didTapCancelButton(_ sender: Any) { SVProgressHUD.dismiss() self.dismiss(animated: true, completion: nil) } @IBAction func slotsStepperChanged(_ sender: UIStepper) { self.view.endEditing(true) slotsLabel.text = String(format: "%.f", sender.value) } @IBAction func routineSwitchChanged(_ sender: UISwitch) { view.endEditing(true) if sender.isOn { routinePatternHeight.constant = routinePatternHeightOriginal! UIView.animate(withDuration: 0.5, animations: { self.view.layoutIfNeeded() self.routinePatternView.alpha = 1.0 }) } else { routinePatternHeightOriginal = routinePatternHeight.constant routinePatternHeight.constant = 0 UIView.animate(withDuration: 0.5, animations: { self.view.layoutIfNeeded() self.routinePatternView.alpha = 0.0 }) } } @IBAction func routineWeekDayButtonTapped(_ sender: UIButton) { self.view.endEditing(true) sender.isSelected = !sender.isSelected if sender.isSelected { weekDays.append(String(sender.tag)) } else if let index = weekDays.index(of: String(sender.tag)) { weekDays.remove(at: index) } } @IBAction func routineDurationButtonTapped(_ sender: UIButton) { self.view.endEditing(true) routineDuration2MonthsButton.isSelected = false routineDuration3MonthsButton.isSelected = false routineDuration4MonthsButton.isSelected = false sender.isSelected = true routineDurationMonths = sender.tag } @IBAction func directionChanged(_ sender: UISegmentedControl) { view.endEditing(true) guard let lastOfferedRide = userDefaults.dictionary(forKey: CaronaePreferenceLastOfferedRide.key) else { selectedHub = "" return } if sender.selectedSegmentIndex == 0, let hubGoing = lastOfferedRide[CaronaePreferenceLastOfferedRide.hubGoing] as? String { selectedHub = hubGoing } else if sender.selectedSegmentIndex == 1, let hubReturning = lastOfferedRide[CaronaePreferenceLastOfferedRide.hubReturning] as? String { selectedHub = hubReturning } else { selectedHub = "" } } @IBAction func selectDateTapped(_ sender: Any) { self.view.endEditing(true) let title = segmentedControl.selectedSegmentIndex == 0 ? PlaceService.Institution.goingLabel : PlaceService.Institution.leavingLabel let datePicker = ActionSheetDatePicker(title: title, datePickerMode: .dateAndTime, selectedDate: self.selectedDate, target: self, action: #selector(timeWasSelected(selectedTime:)), origin: sender) datePicker?.minimumDate = Date.currentTimePlus(minutes: 5) datePicker?.show() } @IBAction func selectCenterTapped(_ sender: Any) { let hubType: HubSelectionViewController.HubTypeDirection = (segmentedControl.selectedSegmentIndex == 0) ? .centers : .hubs let selectionVC = HubSelectionViewController(selectionType: .oneSelection, hubTypeDirection: hubType) selectionVC.delegate = self self.navigationController?.show(selectionVC, sender: self) } @IBAction func selectNeighborhoodTapped(_ sender: Any) { let selectionVC = NeighborhoodSelectionViewController(selectionType: .oneSelection) selectionVC.delegate = self self.navigationController?.show(selectionVC, sender: self) } // MARK: Selection Methods @objc func timeWasSelected(selectedTime: Date) { selectedDate = selectedTime } func hasSelected(hubs: [String], inCampus campus: String) { self.selectedHub = hubs.first! } func hasSelected(neighborhoods: [String], inZone zone: String) { self.selectedZone = zone self.selectedNeighborhood = neighborhoods.first! } } // MARK: UITextViewDelegate extension CreateRideViewController: UITextViewDelegate { func textViewDidBeginEditing(_ textView: UITextView) { if textView.text == notesPlaceholder { textView.text = "" textView.textColor = .black } textView.becomeFirstResponder() } func textViewDidEndEditing(_ textView: UITextView) { if textView.text.isEmpty { textView.text = notesPlaceholder textView.textColor = notesTextColor } textView.resignFirstResponder() } }
gpl-3.0
721fbb4121ca9a8498b58c755a26d067
41.611399
192
0.605849
5.017694
false
false
false
false
itechline/bonodom_new
SlideMenuControllerSwift/AdmonitorDataCell.swift
1
2854
// // AdmonitorDataCell.swift // Bonodom // // Created by Attila Dán on 2016. 07. 07.. // Copyright © 2016. Itechline. All rights reserved. // import UIKit import SwiftyJSON struct AdmonitorData { init(id: Int, fel_id: Int, name: String, ingatlan_butorozott: Int, ingatlan_lift: Int, ingatlan_erkely: Int, ingatlan_meret: Int, ingatlan_szsz_min: Int, ingatlan_szsz_max: Int, ingatlan_emelet_max: Int, ingatlan_emelet_min: Int, ingatlan_allapot_id: Int, ingatlan_tipus_id: Int, ingatlan_energiatan_id: Int, ingatlan_kilatas_id: Int, ingatlan_parkolas_id: Int, ingatlan_ar_max: String, ingatlan_ar_min: String, keyword: String) { self.id = id self.fel_id = fel_id self.name = name self.ingatlan_butorozott = ingatlan_butorozott self.ingatlan_lift = ingatlan_lift self.ingatlan_erkely = ingatlan_erkely self.ingatlan_meret = ingatlan_meret self.ingatlan_szsz_min = ingatlan_szsz_min self.ingatlan_szsz_max = ingatlan_szsz_max self.ingatlan_emelet_max = ingatlan_emelet_max self.ingatlan_emelet_min = ingatlan_emelet_min self.ingatlan_allapot_id = ingatlan_allapot_id self.ingatlan_tipus_id = ingatlan_tipus_id self.ingatlan_energiatan_id = ingatlan_energiatan_id self.ingatlan_kilatas_id = ingatlan_kilatas_id self.ingatlan_parkolas_id = ingatlan_parkolas_id self.ingatlan_ar_max = ingatlan_ar_max self.ingatlan_ar_min = ingatlan_ar_min self.keyword = keyword } var id: Int var fel_id: Int var name: String var ingatlan_butorozott: Int var ingatlan_lift: Int var ingatlan_erkely: Int var ingatlan_meret: Int var ingatlan_szsz_min: Int var ingatlan_szsz_max: Int var ingatlan_emelet_max: Int var ingatlan_emelet_min: Int var ingatlan_allapot_id: Int var ingatlan_tipus_id: Int var ingatlan_energiatan_id: Int var ingatlan_kilatas_id: Int var ingatlan_parkolas_id: Int var ingatlan_ar_max: String var ingatlan_ar_min: String var keyword: String } class AdmonitorDataCell: BaseTableViewCell { @IBOutlet weak var name: UILabel! var id = 0 @IBAction func delete_admonitor(sender: AnyObject) { let fav: [String:AnyObject] = [ "id": String(id)] NSNotificationCenter.defaultCenter().postNotificationName("delete_admonitor", object: fav) } override func awakeFromNib() { //self.dataText?.font = UIFont.boldSystemFontOfSize(16) //self.dataText?.textColor = UIColor(hex: "000000") } override class func height() -> CGFloat { return 60 } override func setData(data: Any?) { if let data = data as? AdmonitorData { self.name.text = data.name self.id = data.id } } }
mit
e8fd186f05a24e4764a2c520773878cc
33.361446
434
0.657433
3.110142
false
false
false
false
CoderYLiu/30DaysOfSwift
Project 16 - SlideMenu/SlideMenu/NewsTableViewController.swift
1
3304
// // NewsTableViewController.swift // SlideMenu <https://github.com/DeveloperLY/30DaysOfSwift> // // Created by Liu Y on 16/4/22. // Copyright © 2016年 DeveloperLY. All rights reserved. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // import UIKit class NewsTableViewController: UITableViewController, MenuTransitionManagerDelegate { let menuTransitionManager = MenuTransitionManager() override var preferredStatusBarStyle : UIStatusBarStyle { return UIStatusBarStyle.lightContent } override func viewDidLoad() { super.viewDidLoad() self.title = "Everyday Moments" self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none self.view.backgroundColor = UIColor(red:0.062, green:0.062, blue:0.07, alpha:1) } func dismiss() { self.dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSections(in tableView: UITableView) -> Int { return 3 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! NewsTableViewCell cell.backgroundColor = UIColor.clear if indexPath.row == 0 { cell.postImageView.image = UIImage(named: "1") cell.postTitle.text = "Love mountain." cell.postAuthor.text = "Allen Wang" cell.authorImageView.image = UIImage(named: "a") } else if indexPath.row == 1 { cell.postImageView.image = UIImage(named: "2") cell.postTitle.text = "New graphic design - LIVE FREE" cell.postAuthor.text = "Cole" cell.authorImageView.image = UIImage(named: "b") } else if indexPath.row == 2 { cell.postImageView.image = UIImage(named: "3") cell.postTitle.text = "Summer sand" cell.postAuthor.text = "Daniel Hooper" cell.authorImageView.image = UIImage(named: "c") } else { cell.postImageView.image = UIImage(named: "4") cell.postTitle.text = "Seeking for signal" cell.postAuthor.text = "Noby-Wan Kenobi" cell.authorImageView.image = UIImage(named: "d") } return cell } @IBAction func unwindToHome(_ segue: UIStoryboardSegue) { let sourceController = segue.source as! MenuTableViewController self.title = sourceController.currentItem } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let menuTableViewController = segue.destination as! MenuTableViewController menuTableViewController.currentItem = self.title! menuTableViewController.transitioningDelegate = menuTransitionManager menuTransitionManager.delegate = self } }
mit
dc3736743f92d5d1841cdae14e794667
32.683673
110
0.631627
4.956456
false
false
false
false
zevwings/ZVRefreshing
ZVRefreshing/Support/UIScrollViewExtensions.swift
1
5010
// // Extensions.swift // ZVRefreshing // // Created by zevwings on 16/3/30. // Copyright © 2016年 zevwings. All rights reserved. // import UIKit private struct AssociatedKeys { static var refreshHeader = "com.zevwings.refreshing.header" static var refreshFooter = "com.zevwings.refreshing.footer" static var reloadHandler = "com.zevwings.refreshing.reloadhandler" } public extension UIScrollView { var refreshHeader: ZVRefreshHeader? { get { return objc_getAssociatedObject(self, &AssociatedKeys.refreshHeader) as? ZVRefreshHeader } set { guard refreshHeader != newValue else { return } refreshHeader?.removeFromSuperview() willChangeValue(forKey: "refreshHeader") objc_setAssociatedObject( self, &AssociatedKeys.refreshHeader, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) didChangeValue(forKey: "refreshHeader") guard let refreshHeader = refreshHeader else { return } addSubview(refreshHeader) sendSubviewToBack(refreshHeader) } } var refreshFooter: ZVRefreshFooter? { get { return objc_getAssociatedObject(self, &AssociatedKeys.refreshFooter) as? ZVRefreshFooter } set { guard refreshFooter != newValue else { return } refreshFooter?.removeFromSuperview() willChangeValue(forKey: "refreshFooter") objc_setAssociatedObject( self, &AssociatedKeys.refreshFooter, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) didChangeValue(forKey: "refreshFooter") guard let refreshFooter = refreshFooter else { return } addSubview(refreshFooter) sendSubviewToBack(refreshFooter) } } func removeAllRefreshControls() { print("removeRefreshControls") refreshHeader?.removeScrollViewObservers() refreshHeader?.removeFromSuperview() refreshHeader = nil refreshFooter?.removeScrollViewObservers() refreshFooter?.removeFromSuperview() refreshFooter = nil } } extension UIScrollView { typealias ReloadDataHandler = (_ totalCount: Int) -> Void private struct ReloadDataHandlerWrapper { var reloadDataHanader: ReloadDataHandler init(value: @escaping ReloadDataHandler) { self.reloadDataHanader = value } } var reloadDataHandler: ReloadDataHandler? { get { let wrapper = objc_getAssociatedObject(self, &AssociatedKeys.reloadHandler) as? ReloadDataHandlerWrapper return wrapper?.reloadDataHanader } set { if let reloadDataHanader = newValue { let wrapper = ReloadDataHandlerWrapper(value: reloadDataHanader) objc_setAssociatedObject( self, &AssociatedKeys.reloadHandler, wrapper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } else { objc_setAssociatedObject( self, &AssociatedKeys.reloadHandler, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } } } var totalDataCount: Int { var totalCount: Int = 0 if let tableView = self as? UITableView { for section in 0 ..< tableView.numberOfSections { totalCount += tableView.numberOfRows(inSection: section) } } else if let collectionView = self as? UICollectionView { for section in 0 ..< collectionView.numberOfSections { totalCount += collectionView.numberOfItems(inSection: section) } } return totalCount } fileprivate func executeReloadDataBlock() { reloadDataHandler?(totalDataCount) } } // MARK: - UICollectionView extension UICollectionView { static let once: Void = { SwizzleMethodInstanceMethod( origin: (UICollectionView.self, #selector(reloadData)), target: (UICollectionView.self, #selector(_reloadData)) ) }() @objc private func _reloadData() { _reloadData() executeReloadDataBlock() } } // MARK: - UITableView extension UITableView { static let once: Void = { SwizzleMethodInstanceMethod( origin: (UITableView.self, #selector(reloadData)), target: (UITableView.self, #selector(_reloadData)) ) }() @objc private func _reloadData() { _reloadData() executeReloadDataBlock() } } // MARK: - UIApplication extension UIApplication { override open var next: UIResponder? { UITableView.once UICollectionView.once return super.next } }
mit
8b2b4b1cfaa94fdab0e2c890c1f263f1
27.775862
116
0.596165
5.466157
false
false
false
false
Electrode-iOS/ELFoundation
ELFoundation/TestExtensions/TestHelper.swift
2
1815
// // TestHelper.swift // ELFoundation // // Created by Brandon Sneed on 8/13/15. // Copyright © 2015 WalmartLabs. All rights reserved. // import Foundation /** Determines if a given block of code is being run within the context of a unit test. */ public func isInUnitTest() -> Bool { struct Holder { /// Stored value after first calculation. static var isInUnitTests: Bool! } // Make sure stored value isn't nil before function returns if Holder.isInUnitTests == nil { Holder.isInUnitTests = ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil } return Holder.isInUnitTests } private enum WaitConditionError: Error { case timeout } extension NSObject { /** Pumps the run loop while waiting for the given conditions check to return true, or the timeout has expired. This function should only be used within unit tests, and will throw an exception if not. - parameter timeout: The timeout, in seconds. - parameter conditionsCheck: A block that performs the condition check and returns true/false. */ public func waitForConditionsWithTimeout(_ timeout: TimeInterval, conditionsCheck: () -> Bool) throws { if isInUnitTest() { var condition = false let startTime = Date() while (!condition) { RunLoop.current.run(until: Date.distantPast) condition = conditionsCheck() let currentTime = Date().timeIntervalSince(startTime) if currentTime > timeout { throw WaitConditionError.timeout } } } else { exceptionFailure("waitForConditionsWithTimeout should only be used in unit tests.") } } }
mit
8089141a48bf379b1f6ab07b154f3336
30.275862
107
0.638368
4.969863
false
true
false
false
shvets/WebAPI
Tests/WebAPITests/GidOnline2APITests.swift
1
8122
import XCTest import SwiftSoup import Alamofire @testable import WebAPI class GidOnline2APITests: XCTestCase { // var subject = GidOnline2API() // // var document: Document? // // var allMovies: [[String :Any]]? // // override func setUp() { // super.setUp() // // do { // document = try subject.fetchDocument(GidOnline2API.SiteUrl) // } // catch { // print("Error fetching document") // } // } // // override func tearDown() { // super.tearDown() // } // // func testGetGenres() throws { // let result = try subject.getGenres(document!) // // print(result as Any) // } // // func testGetTopLinks() throws { // let result = try subject.getTopLinks(document!) // // print(result as Any) // } // // func testGetActors() throws { // let result = try subject.getActors(document!) // // print(result as Any) // } // // func testGetActorsByLetter() throws { // let result = try subject.getActors(document!, letter: "А") // // print(result as Any) // } // // func testGetDirectors() throws { // let result = try subject.getDirectors(document!) // // print(result as Any) // } // // func testGetDirectorsByLetter() throws { // let result = try subject.getDirectors(document!, letter: "В") // // print(result as Any) // } // // func testGetCountries() throws { // let result = try subject.getCountries(document!) // // print(result as Any) // } // // func testGetYears() throws { // let result = try subject.getYears(document!) // // print(result as Any) // } // // func testGetSeasons() throws { // let result = try subject.getSeasons("\(GidOnlineAPI.SiteUrl)/2016/03/strazhi-galaktiki/", parentName: "parentName") // // print(result as Any) // } // //// func testGetEpisodes() throws { //// let result = try subject.getEpisodes("\(GidOnlineAPI.SiteUrl)/2016/03/strazhi-galaktiki", seasonNumber: "1") //// //// print(result as Any) //// } //// //// func testGetAllMovies() throws { //// let allMovies = try subject.getAllMovies() //// //// print(allMovies) //// } //// //// func testGetMoviesByGenre() throws { //// let document = try subject.fetchDocument(GidOnlineAPI.SiteUrl + "/genre/vestern/") //// //// let result = try subject.getMovies(document!, path: "/genre/vestern/") //// //// print(result as Any) //// } // //// func testGetUrls() throws { //// //let movieUrl = "http://gidonline.club/2017/02/kosmos-mezhdu-nami/" //// let movieUrl = "http://gidonline.club/2016/12/moana/" //// //// let urls = try subject.getUrls(movieUrl) //// //// print(urls) //// } // // func testGetUrls() throws { // let movieUrl = "http://gidonline-kino.club/2169-princessa-monako.html" // // let urls = try subject.getUrls(movieUrl) // // print(urls) // } // func testDownload() throws { // let url = "http://185.38.12.50/sec/1494153108/383030302a6e8eab9dd7342cd960e08f8bf79e1bbd4ebd40/ivs/ae/a6/350cc47282a3/360.mp4" // // let utilityQueue = DispatchQueue.global(qos: .utility) // // let semaphore = DispatchSemaphore.init(value: 0) // // let encodedPath = url.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)! // // let destination: DownloadRequest.DownloadFileDestination = { _, _ in // let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] // let fileURL = documentsURL.appendingPathComponent("downloadedFile.mp3") // // return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) // } // // let configuration = URLSessionConfiguration.default // // let proxyPort = 3130 // let proxyURL = "176.221.42.213" // // configuration.connectionProxyDictionary = [ // kCFNetworkProxiesHTTPEnable as AnyHashable: true, // kCFNetworkProxiesHTTPPort as AnyHashable: proxyPort, // kCFNetworkProxiesHTTPProxy as AnyHashable: proxyURL // ] // // let sessionManager = Alamofire.SessionManager(configuration: configuration) // // sessionManager.download(encodedPath, to: destination) // .downloadProgress(queue: utilityQueue) { progress in // print("Download Progress: \(progress.fractionCompleted)") // } // .responseData(queue: utilityQueue) { response in // FileManager.default.createFile(atPath: "downloadedFile.mp4", contents: response.result.value) // // semaphore.signal() // } // // _ = semaphore.wait(timeout: DispatchTime.distantFuture) // } // // func testDownload2() throws { // let url = "http://streamblast.cc/video/cafa7280ceff74b7/index.m3u8" // // let utilityQueue = DispatchQueue.global(qos: .utility) // // let semaphore = DispatchSemaphore.init(value: 0) // // //let encodedPath = url.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)! // // let destination: DownloadRequest.DownloadFileDestination = { _, _ in // let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] // let fileURL = documentsURL.appendingPathComponent("downloadedFile.mp3") // // return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) // } // // let configuration = URLSessionConfiguration.default // // let proxyPort = 3130 // let proxyURL = "176.221.42.213" // // configuration.connectionProxyDictionary = [ // kCFNetworkProxiesHTTPEnable as AnyHashable: true, // kCFNetworkProxiesHTTPPort as AnyHashable: proxyPort, // kCFNetworkProxiesHTTPProxy as AnyHashable: proxyURL // ] // // let sessionManager = Alamofire.SessionManager(configuration: configuration) // // let parameters = [ // "cd": "0", // "expired": "1494129784", // "frame_commit": "bd2d44bd3b8025d83a028a6b11be7c82", // "mw_pid": "4", // "signature": "3a0dc9f39d331340cf6fb20e6f0fa0bb", // "man_type": "zip1", // "eskobar": "pablo" // ] // sessionManager.download(url, parameters: parameters, to: destination) // .downloadProgress(queue: utilityQueue) { progress in // print("Download Progress: \(progress.fractionCompleted)") // } // .responseData(queue: utilityQueue) { response in // print(response.response?.statusCode as Any) // FileManager.default.createFile(atPath: "downloadedFile.txt", contents: response.result.value) // // semaphore.signal() // } // // _ = semaphore.wait(timeout: DispatchTime.distantFuture) // } // // func testGetSerialInfo() throws { // //let url = "http://gidonline.club/2016/03/strazhi-galaktiki/" // let url = "http://gidonline.club/2017/02/molodoj-papa/" // // let result = try subject.getSerialInfo(url) // // print(result as Any) // } // // func testGetMediaData() throws { // let allMovies = try subject.getAllMovies()["movies"]! as! [Any] // // let movieUrl = (allMovies[0] as! [String: String])["id"]! // // let document = try subject.fetchDocument(movieUrl) // // let result = try subject.getMediaData(document!) // // print(result as Any) // } // func skip_testIsSerial() throws { // let url = "http://gidonline.club/2016/07/priklyucheniya-vudi-i-ego-druzej/" // // let result = try subject.isSerial(url) // // print(result as Any) // } // // func testSearch() throws { // let query = "акула" // // let result = try subject.search(query) // // print(result as Any) // } // // func testSearchActors() throws { // let query = "Аллен" // // let result = try subject.searchActors(document!, query: query) // // print(result as Any) // } // // func testSearchDirectors() throws { // let query = "Люк" // // let result = try subject.searchDirectors(document!, query: query) // // print(result as Any) // } // // func testSearchCountries() throws { // let query = "Франция" // // let result = try subject.searchCountries(document!, query: query) // // print(result as Any) // } // // func testSearchYears() throws { // let query = "1984" // // let result = try subject.searchYears(document!, query: query) // // print(result as Any) // } }
mit
7a8e4c33cbc326700cd70fccbf19c890
27.521127
132
0.645185
3.344344
false
true
false
false
richardpiazza/SOSwift
Tests/SOSwiftTests/BrandOrOrganizationTests.swift
1
1409
import XCTest @testable import SOSwift class BrandOrOrganizationTests: XCTestCase { static var allTests = [ ("testDecode", testDecode), ("testEncode", testEncode), ] fileprivate class TestClass: Codable, Schema { var brand: BrandOrOrganization? var organization: BrandOrOrganization? } func testDecode() throws { let json = """ { "brand" : { "@type" : "Brand", "name" : "Brand" }, "organization" : { "@type" : "Organization", "name" : "Organization" } } """ let testClass = try TestClass.make(with: json) XCTAssertEqual(testClass.brand?.brand?.name, "Brand") XCTAssertNil(testClass.brand?.organization) XCTAssertEqual(testClass.organization?.organization?.name, "Organization") XCTAssertNil(testClass.organization?.brand) } func testEncode() throws { let testClass = TestClass() testClass.brand = BrandOrOrganization(Brand()) testClass.organization = BrandOrOrganization(Organization()) let dictionary = try testClass.asDictionary() XCTAssertNotNil(dictionary["brand"] as? [String : Any]) XCTAssertNotNil(dictionary["organization"] as? [String : Any]) } }
mit
e9eebd7dd70b41ab40058295e00a3dc8
28.354167
82
0.56494
5.296992
false
true
false
false
mleiv/MEGameTracker
MEGameTracker/Views/Common/Data Rows/Shepard Love Interest/ShepardLoveInterestRow.swift
1
1877
// // ShepardLoveInterestView.swift // MEGameTracker // // Created by Emily Ivie on 5/27/16. // Copyright © 2016 urdnot. All rights reserved. // import UIKit @IBDesignable final public class ShepardLoveInterestRow: HairlineBorderView, ValueDataRowDisplayable { // MARK: Inspectable @IBInspectable public var typeName: String = "None" { didSet { setDummyDataRowType() } } @IBInspectable public var isHideOnEmpty: Bool = true // MARK: Outlets @IBOutlet weak public var loveInterestImageView: UIImageView? @IBOutlet weak public var headingLabel: UILabel? @IBOutlet weak public var valueLabel: UILabel? @IBOutlet weak public var disclosureImageView: UIImageView? @IBOutlet weak public var button: UIButton? @IBOutlet weak public var rowDivider: HairlineBorderView? @IBAction public func buttonClicked(_ sender: UIButton) { onClick?(sender) } // MARK: Properties public var didSetup = false public var isSettingUp = false // Protocol: IBViewable public var isAttachedNibWrapper = false public var isAttachedNib = false public var onClick: ((UIButton) -> Void)? // MARK: IBViewable override public func awakeFromNib() { super.awakeFromNib() _ = attachOrAttachedNib() } override public func prepareForInterfaceBuilder() { _ = attachOrAttachedNib() super.prepareForInterfaceBuilder() } // MARK: Hide when not initialized (as though if empty) public override func layoutSubviews() { if !UIWindow.isInterfaceBuilder && !isAttachedNib && isHideOnEmpty && !didSetup { isHidden = true } else { setDummyDataRowType() } super.layoutSubviews() } // MARK: Customization Options private func setDummyDataRowType() { guard (isInterfaceBuilder || App.isInitializing) && !didSetup && isAttachedNibWrapper else { return } var dataRowType = ShepardLoveInterestRowType() dataRowType.row = self dataRowType.setupView() } }
mit
dd3ae1529f00fee4c1c5a6a38535c818
24.69863
103
0.747868
4.017131
false
false
false
false
huangboju/Eyepetizer
Eyepetizer/Eyepetizer/Controllers/Discover/BaseDiscoverDetail.swift
1
3203
// // Copyright © 2016年 xiAo_Ju. All rights reserved. // class BaseDiscoverDetail: UIViewController, LoadingPresenter, DataPresenter { var loaderView: LoaderView? var nextPageUrl: String? var categoryId = 0 //MARK: - 💛 DataPresenter 💛 var endpoint = "" { willSet { netWork(newValue, parameters: ["categoryId": categoryId], key: "videoList") } } var data: [ItemModel] = [ItemModel]() { willSet { if data.count != 0 { collectionView.footerViewEndRefresh() } } didSet { collectionView.reloadData() setLoaderViewHidden(true) } } lazy var collectionView: CollectionView = { let rect = CGRect(x: 0, y: 0, width: self.view.frame.width, height: SCREEN_HEIGHT - TAB_BAR_HEIGHT - TOP_BAR_HEIGHT) let collectionView = CollectionView(frame: rect, collectionViewLayout:CollectionLayout()) collectionView.delegate = self collectionView.dataSource = self return collectionView }() convenience init(categoryId: Int) { self.init() self.categoryId = categoryId } final override func viewDidLoad() { super.viewDidLoad() view.addSubview(collectionView) setupLoaderView() onPrepare() } func onLoadSuccess(isPaging: Bool, jsons: [DATA]) { let list = jsons.map({ (dict) -> ItemModel in ItemModel(dict: dict.dictionary) }) if isPaging { data = list } else { data.appendContentsOf(list) } } func onLoadFailure(error: NSError) {} func onPrepare() { setLoaderViewHidden(false) collectionView.footerViewPullToRefresh { [unowned self] in if let nextPageUrl = self.nextPageUrl { self.netWork(nextPageUrl, key: "videoList") } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension BaseDiscoverDetail: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return data.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCellWithReuseIdentifier(ChoiceCell.cellID, forIndexPath: indexPath) } func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { (cell as? ChoiceCell)?.model = data[indexPath.row] } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if parentViewController is DiscoverDetailController { (parentViewController as? DiscoverDetailController)?.selectCell = collectionView.cellForItemAtIndexPath(indexPath) as? ChoiceCell } navigationController?.pushViewController(VideoDetailController(model: data[indexPath.row]), animated: true) } }
mit
47dfce77116b4c72b842c2ba892227c7
32.621053
146
0.651221
5.323333
false
false
false
false
fjtrujy/FTMTableSectionModules
Sources/ModuleSnapshotServices/SnapshotTestingCellAdditions.swift
1
703
// // SnapshotTestingCellAdditions.swift // Pods // // Created by Francisco Javier Trujillo Mata on 13/06/2019. // import UIKit public extension UITableViewCell { override func adjustToFitScreen(orientation: UIInterfaceOrientation) { contentView.adjustToFitScreen(orientation: orientation) var adjustedFrame = contentView.bounds //Add separator height let scale = SnapshotTestDeviceInfo().scale adjustedFrame.size.height += CGFloat(NSDecimalNumber.one.floatValue) / scale adjustedFrame.size.height = ceil(adjustedFrame.size.height) contentView.bounds = adjustedFrame bounds = contentView.bounds } }
mit
139633f90ec361b5a699e13cab2d064d
28.291667
84
0.694168
4.950704
false
true
false
false
fireunit/login
login/PasswordViewController.swift
1
2094
// // PasswordViewController.swift // login // // Created by doug on 5/23/16. // Copyright © 2016 fireunit. All rights reserved. // import UIKit import Material import Firebase class PasswordViewController: UIViewController { var email = "" private let passwordTextField: TextField = TextField() override func viewDidLoad() { super.viewDidLoad() prepareView() preparePasswordField() prepareSubmitButton() } private func prepareView() { view.backgroundColor = MaterialColor.white } private func preparePasswordField() { passwordTextField.placeholder = "Password" passwordTextField.font = RobotoFont.regularWithSize(16) passwordTextField.textColor = MaterialColor.black passwordTextField.secureTextEntry = true view.addSubview(passwordTextField) let margin = CGFloat(16) passwordTextField.translatesAutoresizingMaskIntoConstraints = false MaterialLayout.size(view, child: passwordTextField, width: view.frame.width - margin * 2, height: 25) MaterialLayout.alignFromTopLeft(view, child: passwordTextField, top:160 , left: margin) } private func prepareSubmitButton() { let loginButton: RaisedButton = RaisedButton(frame: CGRectMake(107, 207, 100, 35)) loginButton.setTitle("Login", forState: .Normal) loginButton.titleLabel!.font = RobotoFont.mediumWithSize(14) loginButton.backgroundColor = MaterialColor.cyan.darken2 loginButton.pulseColor = MaterialColor.white loginButton.addTarget(self, action: #selector(handleLoginButton), forControlEvents: .TouchUpInside) view.addSubview(loginButton) } func handleLoginButton() { if let password = passwordTextField.text { FIRAuth.auth()?.signInWithEmail(email, password: password) { (user, error) in if error != nil { print(error) } else { print(user) } } } } }
mit
cd7d1ff9ecff3c125d0b601d0b829510
30.712121
109
0.648352
5.193548
false
false
false
false
oNguyenVanHung/TODO-App
TO-DO-APP/AppDelegate.swift
1
3321
// // AppDelegate.swift // TO-DO-APP // // Created by ha.van.duc on 7/28/17. // Copyright © 2017 framgia. All rights reserved. // import UIKit import CoreData import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { var window: UIWindow? let databaseManager = DatabaseManager.shared func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let sharedNotification = NotificationManager.shared UIApplication.shared.applicationIconBadgeNumber = sharedNotification.getNumberBadge() UNUserNotificationCenter.current().delegate = self // window = UIWindow.init(frame: UIScreen.main.bounds) // // // Set Background Color of window // window?.backgroundColor = UIColor.white // // // Allocate memory for an instance of the 'MainViewController' class // let mainViewController = TimelineViewController() // // // Set the root view controller of the app's window // window!.rootViewController = mainViewController // // // Make the window visible // window!.makeKeyAndVisible() return true } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { UIApplication.shared.applicationIconBadgeNumber = NotificationManager.shared.updateBadge() } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. databaseManager.saveContext() } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. databaseManager.saveContext() } }
mit
d8047845db4e53e0c667fa0a0fe0fa7d
46.428571
285
0.738253
5.704467
false
false
false
false
KaiCode2/ResearchKit
samples/ORKSample/ORKSample/HealthDataStep.swift
10
3516
/* Copyright (c) 2015, Apple Inc. 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. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import ResearchKit import HealthKit class HealthDataStep: ORKInstructionStep { // MARK: Properties let healthDataItemsToRead: Set<HKObjectType> = [ HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)! ] let healthDataItemsToWrite: Set<HKSampleType> = [ HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!, HKObjectType.workoutType() ] // MARK: Initialization override init(identifier: String) { super.init(identifier: identifier) title = NSLocalizedString("Health Data", comment: "") text = NSLocalizedString("On the next screen, you will be prompted to grant access to read and write some of your general and health information, such as height, weight, and steps taken so you don't have to enter it again.", comment: "") } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Convenience func getHealthAuthorization(completion: (success: Bool, error: NSError?) -> Void) { guard HKHealthStore.isHealthDataAvailable() else { let error = NSError(domain: "com.example.apple-samplecode.ORKSample", code: 2, userInfo: [NSLocalizedDescriptionKey: "Health data is not available on this device."]) completion(success: false, error:error) return } // Get authorization to access the data HKHealthStore().requestAuthorizationToShareTypes(healthDataItemsToWrite, readTypes: healthDataItemsToRead) { (success, error) -> Void in completion(success:success, error:error) } } }
bsd-3-clause
6ea6e3bb86047a081cfdb894ba4d0b5c
44.662338
245
0.743174
5.255605
false
false
false
false
carnivalmobile/carnival-stream-examples
iOS/CarnivalSwiftStreamExamples/CarnivalSwiftStreamExamples/GraphicalCardTableViewCell.swift
1
1427
// // GraphicalCardTableViewCell.swift // CarnivalSwiftStreamExamples // // Created by Sam Jarman on 14/09/15. // Copyright (c) 2015 Carnival Mobile. All rights reserved. // import UIKit class GraphicalCardTableViewCell: TextCardTableViewCell { @IBOutlet weak var imgView: UIImageView! @IBOutlet weak var timeBackground: UIView! override class func cellIdentifier() -> String { return "GraphicalCardTableViewCell" } override func configureCell(message: CarnivalMessage) { super.configureCell(message: message) if message.imageURL != nil { self.imgView.sd_setImage(with: message.imageURL, placeholderImage: UIImage(named: "placeholder_image")) self.imgView.contentMode = UIView.ContentMode.scaleAspectFill self.imgView.clipsToBounds = true } self.timeBackground.layer.cornerRadius = 4.0 } override func setSelected(_ selected: Bool, animated: Bool) { let backgroundColor = self.unreadLabel.backgroundColor super.setSelected(selected, animated: animated) self.unreadLabel.backgroundColor = backgroundColor } override func setHighlighted(_ highlighted: Bool, animated: Bool) { let backgroundColor = self.unreadLabel.backgroundColor super.setHighlighted(isSelected, animated: animated) self.unreadLabel.backgroundColor = backgroundColor } }
apache-2.0
ce375b34a38499c46d0f4bc5be4a01be
34.675
115
0.702172
4.853741
false
false
false
false
javierlopeza/VerboAppiOS
Verbo Tabs/Verbo Tabs/CalendarioWebViewController.swift
1
1498
// // CalendarioWebViewController.swift // Verbo Tabs // // Created by Javier López Achondo on 05-01-16. // Copyright © 2016 Javier López Achondo. All rights reserved. // import UIKit class CalendarioWebViewController: UIViewController { @IBOutlet weak var CalendarioWebView: UIWebView! var url_string = String() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // Colores y estilo navigationController?.navigationBar.barTintColor = UIColor(red: 3/255.0, green: 120/255.0, blue: 63/255.0, alpha: 1.0) navigationController?.navigationBar.tintColor = UIColor.whiteColor() navigationController?.navigationBar.barStyle = .BlackTranslucent // Mostrar calendario let url = NSURL(string: url_string) let request = NSURLRequest(URL: url!) CalendarioWebView.loadRequest(request) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
cc0-1.0
6916e2a9bd4d51b629206202a945ad07
29.510204
126
0.674916
4.791667
false
false
false
false
andybest/SLisp
Sources/SLispCore/builtins/Core.swift
1
21171
/* MIT License Copyright (c) 2016 Andy Best 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 class Core: Builtins { override init(parser: Parser) { super.init(parser: parser) } override func namespaceName() -> String { return "core" } override func initBuiltins(environment: Environment) -> [String: BuiltinDef] { // MARK: print addBuiltin("print", docstring: """ print (x y ...) Prints the arguments to the console """) { args, parser, env throws in let strings = args.map { arg -> String in switch arg { case .string(let s): return s default: return String(describing: arg) } } print(strings.joined(separator: ",")) return .nil } // MARK: input addBuiltin("input", docstring: """ input (prompt) Gets a line of input from the user, printing the optional prompt """) { args, parser, env throws in if args.count > 1 { throw LispError.general(msg: "'input' expects 0 or 1 argument") } if args.count == 1 { guard case let .string(prompt) = args[0] else { throw LispError.general(msg: "'input' requires the argument to be a string") } Swift.print(prompt, terminator: "") } if let input: String = readLine(strippingNewline: true), input.characters.count > 0 { return .string(input) } return .nil } // MARK: read-string addBuiltin("read-string", docstring: """ read-string (x) Converts the string x to a SLisp form """) { args, parser, env throws in if args.count != 1 { throw LispError.general(msg: "'read-string' requires 1 string argument") } guard case let .string(input) = args[0] else { throw LispError.general(msg: "'read-string' requires the argument to be a string") } return try Reader.read(input) } // MARK: slurp addBuiltin("slurp", docstring: """ slurp (fileName) Reads the file at 'fileName' and returns it as a string """) { args, parser, env throws in if args.count != 1 { throw LispError.general(msg: "'slurp' requires 1 string argument") } guard case let .string(filename) = args[0] else { throw LispError.general(msg: "'slurp' requires the argument to be a string") } do { let fileContents = try String(contentsOfFile: filename) return .string(fileContents) } catch { print("File \(filename) not found.") return .nil } } // MARK: eval addBuiltin("eval", docstring: """ eval (x) Evaluates x """) { args, parser, env throws in if args.count != 1 { throw LispError.general(msg: "'eval' requires 1 argument") } return try self.parser.eval(args[0], environment: environment) } // MARK: str addBuiltin("str", docstring: """ str (x y ...) Converts all of the arguments to strings and concatenates them """) { args, parser, env throws in if args.count == 0 { throw LispError.general(msg: "'str' requires at least one argument") } let strings = args.map { arg -> String in if case let .string(s) = arg { return s } return String(describing: arg) } return .string(strings.joined()) } // MARK: string= addBuiltin("string=", docstring: """ string= (x y ...) Returns true if all of the string arguments are equal """) { args, parser, env throws in if args.count < 2 { throw LispError.general(msg: "'string=' requires at least 2 arguments.") } let strings = try args.map { arg -> String in if case let .string(s) = arg { return s } throw LispError.runtime(msg: "'string=' expects string arguments. Got \(String(describing: arg))") } let comp = strings[0] for s in strings { if s != comp { return .boolean(false) } } return .boolean(true) } // MARK: symbol addBuiltin("symbol", docstring: """ symbol (x) Converts the string argument to a symbol """) { args, parser, env throws in if args.count != 1 { throw LispError.general(msg: "'symbol' requires one argument") } guard case let .string(str) = args[0] else { throw LispError.runtime(msg: "'symbol' requires a string argument") } return .symbol(str) } // MARK: key addBuiltin("keyword", docstring: """ keyword (x) Converts the string, symbol or keyword argument to a keyword """) { args, parser, env throws in if args.count != 1 { throw LispError.general(msg: "'keyword' requires one argument") } switch args[0] { case .key(_): return args[0] case .string(let str): return .key(str) case .symbol(let sym): return .key(sym) default: throw LispError.runtime(msg: "'keyword' requires a string, symbol or keyword argument") } } // MARK: doc addBuiltin("doc", docstring: """ doc (f) Returns the docstring for the function """) { args, parser, env throws in if args.count != 1 { throw LispError.runtime(msg: "'doc' requires 1 argument") } guard case let .function(_, docstring, _, _) = args[0] else { throw LispError.runtime(msg: "'doc' requires the argument to be a function") } if docstring != nil { return .string(docstring!) } return .nil } // MARK: exit addBuiltin("exit", docstring: """ exit (val) Exits the process, returning an optional integer """) { args, parser, env throws in if args.count > 1 { throw LispError.runtime(msg: "'exit' accepts a maximum of 1 argument") } if args.count > 0 { guard case let .number(.integer(exitVal)) = args[0] else { throw LispError.runtime(msg: "'exit' expects an integer argument") } exit(Int32(exitVal)) } exit(0) } // MARK: throw addBuiltin("throw", docstring: "") { args, parser, env throws in if args.count == 0 || args.count > 2 { throw LispError.runtime(msg: "'throw' expects 1 or 2 arguments") } guard case let .key(errorKey) = args[0] else { throw LispError.runtime(msg: "'throw' expects the first argument to be a keyword") } var userInfo: LispType? = nil if args.count == 2 { userInfo = args[1] } throw LispError.lispError(errorKey: errorKey, userInfo: userInfo) } initCoreTypeBuiltins() initCoreCollectionBuiltins() initCoreMathBuiltins(environment: environment) initCoreNamespaceBuiltins() initStdioBuiltins() return builtins } func initCoreNamespaceBuiltins() { // MARK: in-ns addBuiltin("in-ns", docstring: """ in-ns (x) Move to the namespace indicated by the symbol x """) { args, parser, env throws in if args.count != 1 { throw LispError.runtime(msg: "'in-ns' expects one argument.") } guard case let .symbol(ns) = args[0] else { throw LispError.runtime(msg: "'in-ns' expects a symbol as an argument") } env.namespace = parser.createOrGetNamespace(ns) return .nil } // MARK: refer addBuiltin("refer", docstring: """ refer (namespace) Imports all symbols in namespace into the current namespace """) { args, parser, env throws in if args.count != 1 { throw LispError.runtime(msg: "'refer' expects one argument.") } guard case let .symbol(ns) = args[0] else { throw LispError.runtime(msg: "'refer' expects a symbol as an argument") } guard let namespace = parser.namespaces[ns] else { throw LispError.runtime(msg: "Unable to find namespace '\(ns)'") } parser.importNamespace(namespace, toNamespace: env.namespace) return .nil } // MARK: list-ns addBuiltin("list-ns", docstring: "") { args, parser, env throws in if args.count != 1 { throw LispError.runtime(msg: "'in-ns' expects one argument.") } guard case let .symbol(ns) = args[0] else { throw LispError.runtime(msg: "'in-ns' expects a symbol as an argument") } guard let namespace = parser.namespaces[ns] else { throw LispError.runtime(msg: "Unable to find namespace '\(ns)'") } var nsmap: [LispType: LispType] = [:] for (key, value) in namespace.rootBindings { nsmap[.symbol(key)] = value } return .dictionary(nsmap) } } func initCoreTypeBuiltins() { // MARK: list? addBuiltin("list?", docstring: """ list? (x) Returns true if x is a list """) { args, parser, env throws in try self.checkArgCount(funcName: "list", args: args, expectedNumArgs: 1) for arg in args { guard case .list(_) = arg else { return .boolean(false) } } return .boolean(true) } // MARK: symbol? addBuiltin("symbol?", docstring: """ symbol? (x) Returns true is x is a symbol """) { args, parser, env throws in try self.checkArgCount(funcName: "symbol?", args: args, expectedNumArgs: 1) for arg in args { guard case .symbol(_) = arg else { return .boolean(false) } } return .boolean(true) } // MARK: string? addBuiltin("string?", docstring: """ string? (x) Returns true if x is a string """) { args, parser, env throws in try self.checkArgCount(funcName: "string?", args: args, expectedNumArgs: 1) for arg in args { guard case .string(_) = arg else { return .boolean(false) } } return .boolean(true) } // MARK: number? addBuiltin("number?", docstring: """ number? (x) Returns true if x is a number """) { args, parser, env throws in try self.checkArgCount(funcName: "number?", args: args, expectedNumArgs: 1) for arg in args { guard case .number(_) = arg else { return .boolean(false) } } return .boolean(true) } // MARK: float? addBuiltin("float?", docstring: """ float? (x) Returns true if x is a float """) { args, parser, env throws in try self.checkArgCount(funcName: "float?", args: args, expectedNumArgs: 1) for arg in args { guard case .number(let n) = arg else { return .boolean(false) } if n.isInteger { return .boolean(false) } } return .boolean(true) } // MARK: integer? addBuiltin("integer?", docstring: """ integer? (x) Returns true if x is an integer """) { args, parser, env throws in try self.checkArgCount(funcName: "integer?", args: args, expectedNumArgs: 1) for arg in args { guard case .number(let n) = arg else { return .boolean(false) } if n.isFloat { return .boolean(false) } } return .boolean(true) } // MARK: function? addBuiltin("function?", docstring: """ function? (x) Returns true if x is a function """) { args, parser, env throws in try self.checkArgCount(funcName: "function?", args: args, expectedNumArgs: 1) for arg in args { guard case .function(_) = arg else { return .boolean(false) } } return .boolean(true) } // MARK: nil? addBuiltin("nil?", docstring: """ nil? (x) Returns true if x is nil """) { args, parser, env throws in try self.checkArgCount(funcName: "nil?", args: args, expectedNumArgs: 1) for arg in args { guard case .nil = arg else { return .boolean(false) } } return .boolean(true) } } func initCoreMathBuiltins(environment: Environment) { // MARK: + addBuiltin("+", docstring: """ + (x y ...) Adds the arguments together """) { args, parser, env throws in return try self.doArithmeticOperation(args, environment: environment, body: LispNumber.add) } // MARK: subtract addBuiltin("-", docstring: """ - (x y ...) Subtracts the arguments from each other """) { args, parser, env throws in if args.count == 1 { return try self.doSingleArgArithmeticOperation(args, name: "-", environment: environment, body: LispNumber.negate) } else { return try self.doArithmeticOperation(args, environment: environment, body: LispNumber.subtract) } } // MARK: * addBuiltin("*", docstring: """ * (x y ...) Multiplies the arguments together """) { args, parser, env throws in return try self.doArithmeticOperation(args, environment: environment, body: LispNumber.multiply) } // MARK: / addBuiltin("/", docstring: """ / (x y ...) Divides the arguments """) { args, parser, env throws in return try self.doArithmeticOperation(args, environment: environment, body: LispNumber.divide) } // MARK: mod addBuiltin("mod", docstring: """ mod (x y ...) Perfoms a modulo on the arguments """) { args, parser, env throws in return try self.doArithmeticOperation(args, environment: environment, body: LispNumber.mod) } // MARK: > addBuiltin(">", docstring: """ > (x y ...) Returns true if x is greater than all of the arguments """) { args, parser, env throws in return try self.doBooleanArithmeticOperation(args, environment: environment, body: LispNumber.greaterThan) } // MARK: < addBuiltin("<", docstring: """ < (x y ...) Returns true if x is less than all of the arguments """) { args, parser, env throws in return try self.doBooleanArithmeticOperation(args, environment: environment, body: LispNumber.lessThan) } // MARK: == addBuiltin("==", docstring: """ == (x y ...) Returns true if all of the arguments are equal """) { args, parser, env throws in if args.count < 2 { throw LispError.runtime(msg: "'==' requires at least 2 arguments") } let comp = args[0] for arg in args.dropFirst() { if arg != comp { return .boolean(false) } } return .boolean(true) } // MARK: && addBuiltin("&&", docstring: """ && (x y ...) Performs a logical AND on all of the arguments """) { args, parser, env throws in return try self.doBooleanOperation(args, environment: environment) { (x: Bool, y: Bool) -> Bool in return x && y } } // MARK: || addBuiltin("||", docstring: """ || (x y ...) Performs a logical OR on all of the arguments """) { args, parser, env throws in return try self.doBooleanOperation(args, environment: environment) { (x: Bool, y: Bool) -> Bool in return x || y } } // MARK: ! addBuiltin("!", docstring: """ ! (x) Performs a logical NOT on the argument """) { args, parser, env throws in return try self.doSingleBooleanOperation(args, environment: environment) { (x: Bool) -> Bool in return !x } } // MARK: integer addBuiltin("integer", docstring: "") { args, parser, env throws in if args.count != 1 { throw LispError.runtime(msg: "'integer' expects 1 argument.") } switch args[0] { case .number(let num): return .number(.integer(num.intValue())) case .string(let str): let v = Int(str) if v != nil { return .number(.integer(v!)) } else { return .nil } default: throw LispError.runtime(msg: "'integer' expects a number or string argument.") } } } }
mit
958074fe0287278b0813c35d0334105e
30.133824
130
0.471352
5.026353
false
false
false
false
gregomni/swift
SwiftCompilerSources/Sources/Optimizer/InstructionPasses/SimplifyStrongRetainRelease.swift
2
4407
//===--- SimplifyStrongRetainRelease.swift - strong_retain/release opt ----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SIL let simplifyStrongRetainPass = InstructionPass<StrongRetainInst>( name: "simplify-strong_retain", { (retain: StrongRetainInst, context: PassContext) in if isNotReferenceCounted(value: retain.operand, context: context) { context.erase(instruction: retain) return } // Sometimes in the stdlib due to hand offs, we will see code like: // // strong_release %0 // strong_retain %0 // // with the matching strong_retain to the strong_release in a predecessor // basic block and the matching strong_release for the strong_retain in a // successor basic block. // // Due to the matching pairs being in different basic blocks, the ARC // Optimizer (which is currently local to one basic block does not handle // it). But that does not mean that we cannot eliminate this pair with a // peephole. if let prev = retain.previous { if let release = prev as? StrongReleaseInst { if release.operand == retain.operand { context.erase(instruction: retain) context.erase(instruction: release) return } } } }) let simplifyStrongReleasePass = InstructionPass<StrongReleaseInst>( name: "simplify-strong_release", { (release: StrongReleaseInst, context: PassContext) in let op = release.operand if isNotReferenceCounted(value: op, context: context) { context.erase(instruction: release) return } // Release of a classbound existential converted from a class is just a // release of the class, squish the conversion. if let ier = op as? InitExistentialRefInst { if ier.uses.isSingleUse { context.setOperand(of: release, at: 0, to: ier.operand) context.erase(instruction: ier) return } } }) /// Returns true if \p value is something where reference counting instructions /// don't have any effect. private func isNotReferenceCounted(value: Value, context: PassContext) -> Bool { switch value { case let cfi as ConvertFunctionInst: return isNotReferenceCounted(value: cfi.operand, context: context) case let uci as UpcastInst: return isNotReferenceCounted(value: uci.operand, context: context) case let urc as UncheckedRefCastInst: return isNotReferenceCounted(value: urc.operand, context: context) case let gvi as GlobalValueInst: // Since Swift 5.1, statically allocated objects have "immortal" reference // counts. Therefore we can safely eliminate unbalaced retains and // releases, because they are no-ops on immortal objects. // Note that the `simplifyGlobalValuePass` pass is deleting balanced // retains/releases, which doesn't require a Swift 5.1 minimum deployment // targert. return gvi.function.isSwift51RuntimeAvailable case let rptr as RawPointerToRefInst: // Like `global_value` but for the empty collection singletons from the // stdlib, e.g. the empty Array singleton. if rptr.function.isSwift51RuntimeAvailable { // The pattern generated for empty collection singletons is: // %0 = global_addr @_swiftEmptyArrayStorage // %1 = address_to_pointer %0 // %2 = raw_pointer_to_ref %1 if let atp = rptr.operand as? AddressToPointerInst { return atp.operand is GlobalAddrInst } } return false case // Thin functions are not reference counted. is ThinToThickFunctionInst, // The same for meta types. is ObjCExistentialMetatypeToObjectInst, is ObjCMetatypeToObjectInst, // Retain and Release of tagged strings is a no-op. // The builtin code pattern to find tagged strings is: // builtin "stringObjectOr_Int64" (or to tag the string) // value_to_bridge_object (cast the UInt to bridge object) is ValueToBridgeObjectInst: return true default: return false } }
apache-2.0
f51514f7d7876c9ef02e53245bad1b70
37.657895
80
0.682777
4.316357
false
false
false
false
kickstarter/Kickstarter-Prelude
Prelude.playground/Pages/06-Traits.xcplaygroundpage/Contents.swift
1
2148
import Prelude import Prelude_UIKit import UIKit import PlaygroundSupport /*: The prelude provides special functions for tapping into a UI transformation pipeline and providing custom styling based on `UITraitCollection` attributes. For example, one can provide different values of margins depending on whether the interface idiom is iPhone or iPad. The way you tap into the transformation pipeline is to use a new variation of the `%~` operator. It takes a closure that takes both the whole and part being operated on, which allows you to inspect the current traits in order to provide custom styling. For example, here is a transformation of `UIButton`s that that uses the button's interface idiom in order to set content edge insets, font and corner radius: */ let buttonStyle = UIButton.lens.contentEdgeInsets %~~ { $1.traitCollection.userInterfaceIdiom == .phone ? .init(all: 8) : .init(all: 16) } <> UIButton.lens.titleLabel.font %~~ { $1.traitCollection.userInterfaceIdiom == .phone ? .preferredFont(forTextStyle: .callout) : .preferredFont(forTextStyle: .title2) } <> UIButton.lens.layer.cornerRadius %~~ { if $1.traitCollection.userInterfaceIdiom == .phone { return 3.0 } return 8.0 } /*: In order to use that we need to set up a view controller with some specified traits. We have a helper function called `traitsController` that creates a parent and child controller with a specified set of traits. We can then create a button and add it to the child controller's view: */ let (parent, child) = playgroundControllers(device: .phone4inch, orientation: .portrait) PlaygroundPage.current.liveView = parent.view let button = UIButton() /*: With that set up we can now perform a styling for a button: */ button |> UIButton.lens.title(for: .normal) .~ "Hello world" |> UIButton.lens.frame.origin .~ .init(x: 50, y: 50) |> UIButton.lens.titleColor(for: .normal) .~ .white |> UIButton.lens.backgroundColor(for: .normal) .~ .red |> UIButton.lens.layer.masksToBounds .~ true |> buttonStyle button.sizeToFit() child.view.addSubview(button)
apache-2.0
f2342312fd1c17c032f83269dfe73e3f
36.034483
102
0.728585
4.203523
false
false
false
false
kujenga/CoreDataIssue
Entity/AppDelegate.swift
1
7624
// // AppDelegate.swift // Entity // // Created by Aaron Taylor on 3/27/15. // Copyright (c) 2015 Aaron Taylor. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } // 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.rastech.Entity" in the user's Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask) let appSupportURL = urls[urls.count - 1] as NSURL return appSupportURL.URLByAppendingPathComponent("com.rastech.Entity") }() 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("Entity", 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. (The directory for the store is created, if necessary.) This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. let fileManager = NSFileManager.defaultManager() var shouldFail = false var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." // Make sure the application files directory is there let propertiesOpt = self.applicationDocumentsDirectory.resourceValuesForKeys([NSURLIsDirectoryKey], error: &error) if let properties = propertiesOpt { if !properties[NSURLIsDirectoryKey]!.boolValue { failureReason = "Expected a folder to store application data, found a file \(self.applicationDocumentsDirectory.path)." shouldFail = true } } else if error!.code == NSFileReadNoSuchFileError { error = nil fileManager.createDirectoryAtPath(self.applicationDocumentsDirectory.path!, withIntermediateDirectories: true, attributes: nil, error: &error) } // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? if !shouldFail && (error == nil) { coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Entity.storedata") if coordinator!.addPersistentStoreWithType(NSXMLStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil } } if shouldFail || (error != nil) { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason if error != nil { dict[NSUnderlyingErrorKey] = error } error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) NSApplication.sharedApplication().presentError(error!) return nil } else { 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 }() // MARK: - Core Data Saving and Undo support @IBAction func saveAction(sender: AnyObject!) { // Performs the save action for the application, which is to send the save: message to the application's managed object context. Any encountered errors are presented to the user. if let moc = self.managedObjectContext { if !moc.commitEditing() { NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing before saving") } var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { NSApplication.sharedApplication().presentError(error!) } } } func windowWillReturnUndoManager(window: NSWindow) -> NSUndoManager? { // Returns the NSUndoManager for the application. In this case, the manager returned is that of the managed object context for the application. if let moc = self.managedObjectContext { return moc.undoManager } else { return nil } } func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply { // Save changes in the application's managed object context before the application terminates. if let moc = managedObjectContext { if !moc.commitEditing() { NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing to terminate") return .TerminateCancel } if !moc.hasChanges { return .TerminateNow } var error: NSError? = nil if !moc.save(&error) { // Customize this code block to include application-specific recovery steps. let result = sender.presentError(error!) if (result) { return .TerminateCancel } let question = NSLocalizedString("Could not save changes while quitting. Quit anyway?", comment: "Quit without saves error question message") let info = NSLocalizedString("Quitting now will lose any changes you have made since the last successful save", comment: "Quit without saves error question info"); let quitButton = NSLocalizedString("Quit anyway", comment: "Quit anyway button title") let cancelButton = NSLocalizedString("Cancel", comment: "Cancel button title") let alert = NSAlert() alert.messageText = question alert.informativeText = info alert.addButtonWithTitle(quitButton) alert.addButtonWithTitle(cancelButton) let answer = alert.runModal() if answer == NSAlertFirstButtonReturn { return .TerminateCancel } } } // If we got here, it is time to quit. return .TerminateNow } }
mit
5c630f828a876ee5ad170f7c4df37367
46.354037
346
0.649921
5.933074
false
false
false
false
Yummypets/YPImagePicker
Source/Models/YPMediaItem.swift
1
2144
// // YPMediaItem.swift // YPImagePicker // // Created by Nik Kov || nik-kov.com on 09.04.18. // Copyright © 2018 Yummypets. All rights reserved. // import UIKit import Foundation import AVFoundation import Photos public class YPMediaPhoto { public var image: UIImage { return modifiedImage ?? originalImage } public let originalImage: UIImage public var modifiedImage: UIImage? public let fromCamera: Bool public let exifMeta: [String: Any]? public var asset: PHAsset? public var url: URL? public init(image: UIImage, exifMeta: [String: Any]? = nil, fromCamera: Bool = false, asset: PHAsset? = nil, url: URL? = nil) { self.originalImage = image self.modifiedImage = nil self.fromCamera = fromCamera self.exifMeta = exifMeta self.asset = asset self.url = url } } public class YPMediaVideo { public var thumbnail: UIImage public var url: URL public let fromCamera: Bool public var asset: PHAsset? public init(thumbnail: UIImage, videoURL: URL, fromCamera: Bool = false, asset: PHAsset? = nil) { self.thumbnail = thumbnail self.url = videoURL self.fromCamera = fromCamera self.asset = asset } } public enum YPMediaItem { case photo(p: YPMediaPhoto) case video(v: YPMediaVideo) } // MARK: - Compression public extension YPMediaVideo { /// Fetches a video data with selected compression in YPImagePickerConfiguration func fetchData(completion: (_ videoData: Data) -> Void) { // TODO: place here a compression code. Use YPConfig.videoCompression // and YPConfig.videoExtension completion(Data()) } } // MARK: - Easy access public extension Array where Element == YPMediaItem { var singlePhoto: YPMediaPhoto? { if let f = first, case let .photo(p) = f { return p } return nil } var singleVideo: YPMediaVideo? { if let f = first, case let .video(v) = f { return v } return nil } }
mit
7ef721bba20f8b63f0c869ee5b6ebf71
24.211765
101
0.618292
4.243564
false
false
false
false
mud/LiluCam
LiluCamTV/TVCameraViewController.swift
1
5945
// // TVCameraViewController.swift // LiluCamTV // // Created by Takashi Okamoto on 10/21/15. // Copyright © 2015 Takashi Okamoto. All rights reserved. // import UIKit class TVCameraViewController: UIViewController, FFFrameExtractorDelegate { @IBOutlet weak var imageView: UIImageView! private var playing:Bool = false var username:String? var password:String? var urlPath:String? var cgiURLPath:String? var frameExtractor:FFFrameExtractor? var cameraController:FoscamCGIController? var playTimer:NSTimer? var opQueue:NSOperationQueue? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults() if let username = defaults.objectForKey("username") { self.username = username as? String } if let password = defaults.objectForKey("password") { self.password = password as? String } if let url = defaults.objectForKey("url") { self.urlPath = url as? String } cameraController = FoscamCGIController.init(CGIPath: self.cgiURL(), username: self.username!, password: self.password!) if let url = self.rtspURL() { frameExtractor = FFFrameExtractor.init(inputPath: url) frameExtractor?.imageOrientation = UIImageOrientation.Up } if let backgroundImage:UIImage? = UIImage.init(named: "cam-background.png") { self.imageView.image = backgroundImage } opQueue = NSOperationQueue.init() opQueue?.maxConcurrentOperationCount = 1 // Add notifications // [[NSNotificationCenter defaultCenter] addObserver: self // selector: @selector(handleEnteredBackground:) // name: UIApplicationDidEnterBackgroundNotification // object: nil]; NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleEnteredBackground", name: UIApplicationDidEnterBackgroundNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleReactivate", name: UIApplicationDidBecomeActiveNotification, object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func viewDidDisappear(animated: Bool) { print("viewDidDisappear was called") self.cancelDisplayNextFrame() frameExtractor?.stop() super.viewDidDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Play Methods func play() { if !playing { playing = true UIApplication.sharedApplication().idleTimerDisabled = true opQueue?.addOperationWithBlock({ () -> Void in if let frame = self.frameExtractor { if frame.start() { dispatch_async(dispatch_get_main_queue(), { () -> Void in self.playTimer = NSTimer.scheduledTimerWithTimeInterval(1.0/30.0, target: self, selector: "displayNextFrame:", userInfo: nil, repeats: true) }) } else { dispatch_async(dispatch_get_main_queue(), { () -> Void in }) } } }) } } func pause() { if playing { self.cancelDisplayNextFrame() playing = false } } func toggle() { if playing { pause() } else { play() } } // MARK: - FFFrameExtractorDelegate func updateWithCurrentUIImage(image: UIImage!) { if image != nil { self.imageView.image = image } } // MARK: - Private Methods func rtspURL() -> String? { if username == nil || password == nil || urlPath == nil { return nil } let standardUserDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults() if standardUserDefaults.boolForKey("wifi_preference") { return "rtsp://\(username!):\(password!)@\(urlPath!)/videoMain" } return "rtsp://\(username!):\(password!)@\(urlPath!)/videoSub" } func cgiURL() -> String { return "\(urlPath)/cgi-bin/CGIProxy.fcgi" } func displayNextFrame(timer: NSTimer) { if UIApplication.sharedApplication().applicationState == UIApplicationState.Active { opQueue?.addOperationWithBlock({ () -> Void in if self.frameExtractor!.delegate == nil { self.frameExtractor!.delegate = self } self.frameExtractor!.processNextFrame() }) } } func cancelDisplayNextFrame() { UIApplication.sharedApplication().idleTimerDisabled = false frameExtractor?.delegate = nil playTimer?.invalidate() opQueue?.cancelAllOperations() opQueue?.addOperationWithBlock({ () -> Void in self.frameExtractor?.stop() }) } // MARK: - Notifications func handleEnteredBackground() { print("entered background") self.pause() } func handleReactivate() { print("reactivated") if self.username == nil || self.password == nil || self.urlPath == nil { print("Need to specify username, password, url") } else { print("Yes, lets continue") self.play() } } }
mit
590ddd18746eedfa9b7f47d214b78dc6
29.958333
168
0.574024
5.354955
false
false
false
false
hebertialmeida/ModelGen
Sources/ModelGenKit/Filters.swift
1
1969
// // Filters.swift // ModelGen // // Created by Heberti Almeida on 2017-05-15. // Copyright © 2017 ModelGen. All rights reserved. // import Foundation /// Convert string to TitleCase /// /// - Parameter string: Input string /// - Returns: Transformed string func titlecase(_ string: String) -> String { guard let first = string.unicodeScalars.first else { return string } return String(first).uppercased() + String(string.unicodeScalars.dropFirst()) } /// Generates/fixes a variable name in sentence case with the first letter as lowercase. /// Replaces invalid names and swift keywords. /// Ensures all caps are maintained if previously set in the name. /// /// - Parameter variableName: Name of the variable in the JSON. /// - Returns: A generated string representation of the variable name. func fixVariableName(_ variableName: String) -> String { var name = replaceKeywords(variableName) name.replaceOccurrencesOfStringsWithString(["-", "_"], " ") name.trim() var finalVariableName = "" for (index, var element) in name.components(separatedBy: " ").enumerated() { element = index == 0 ? element.lowerCaseFirst() : element.uppercaseFirst() finalVariableName.append(element) } return finalVariableName } /// Cross checks the current name against a possible set of keywords, this list is no where /// extensive, but it is not meant to be, user should be able to do this in the unlikely /// case it happens. /// /// - Parameter currentName: The current name which has to be checked. /// - Returns: New name for the variable. func replaceKeywords(_ currentName: String) -> String { let keywordsWithReplacements = [ "class": "classProperty", "struct": "structProperty", "enum": "enumProperty", "internal": "internalProperty", "default": "defaultValue"] if let value = keywordsWithReplacements[currentName] { return value } return currentName }
mit
b9ffb66196a4255053ae659746198fcf
34.142857
91
0.693089
4.422472
false
false
false
false
jokechat/swift3-novel
swift_novels/Pods/NVActivityIndicatorView/NVActivityIndicatorView/NVActivityIndicatorViewable.swift
7
2166
// // NVActivityIndicatorViewable.swift // NVActivityIndicatorViewDemo // // Created by Basem Emara on 5/26/16. // Copyright © 2016 Nguyen Vinh. All rights reserved. // import UIKit /** * UIViewController conforms this protocol to be able to display NVActivityIndicatorView as UI blocker. * * This extends abilities of UIViewController to display and remove UI blocker. */ public protocol NVActivityIndicatorViewable { } public extension NVActivityIndicatorViewable where Self: UIViewController { /** Display UI blocker. Appropriate NVActivityIndicatorView.DEFAULT_* values are used for omitted params. - parameter size: size of activity indicator view. - parameter message: message displayed under activity indicator view. - parameter type: animation type. - parameter color: color of activity indicator view. - parameter padding: padding of activity indicator view. - parameter displayTimeThreshold: display time threshold to actually display UI blocker. - parameter minimumDisplayTime: minimum display time of UI blocker. */ public func startAnimating( _ size: CGSize? = nil, message: String? = nil, type: NVActivityIndicatorType? = nil, color: UIColor? = nil, padding: CGFloat? = nil, displayTimeThreshold: Int? = nil, minimumDisplayTime: Int? = nil) { let activityData = ActivityData(size: size, message: message, type: type, color: color, padding: padding, displayTimeThreshold: displayTimeThreshold, minimumDisplayTime: minimumDisplayTime) NVActivityIndicatorPresenter.sharedInstance.startAnimating(activityData) } /** Remove UI blocker. */ public func stopAnimating() { NVActivityIndicatorPresenter.sharedInstance.stopAnimating() } }
apache-2.0
286bacc1d57762603bf1632bc722fdcc
36.327586
104
0.604157
5.964187
false
false
false
false
Drusy/auvergne-webcams-ios
Carthage/Checkouts/realm-cocoa/Realm/Swift/RLMSupport.swift
3
5338
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm 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 Realm extension RLMRealm { @nonobjc public class func schemaVersion(at url: URL, usingEncryptionKey key: Data? = nil) throws -> UInt64 { var error: NSError? let version = __schemaVersion(at: url, encryptionKey: key, error: &error) guard version != RLMNotVersioned else { throw error! } return version } @nonobjc public func resolve<Confined>(reference: RLMThreadSafeReference<Confined>) -> Confined? { return __resolve(reference as! RLMThreadSafeReference<RLMThreadConfined>) as! Confined? } } extension RLMObject { // Swift query convenience functions public class func objects(where predicateFormat: String, _ args: CVarArg...) -> RLMResults<RLMObject> { return objects(with: NSPredicate(format: predicateFormat, arguments: getVaList(args))) as! RLMResults<RLMObject> } public class func objects(in realm: RLMRealm, where predicateFormat: String, _ args: CVarArg...) -> RLMResults<RLMObject> { return objects(in: realm, with: NSPredicate(format: predicateFormat, arguments: getVaList(args))) as! RLMResults<RLMObject> } } public struct RLMIterator<T>: IteratorProtocol { private var iteratorBase: NSFastEnumerationIterator internal init(collection: RLMCollection) { iteratorBase = NSFastEnumerationIterator(collection) } public mutating func next() -> T? { return iteratorBase.next() as! T? } } // Sequence conformance for RLMArray and RLMResults is provided by RLMCollection's // `makeIterator()` implementation. extension RLMArray: Sequence {} extension RLMResults: Sequence {} extension RLMCollection { // Support Sequence-style enumeration public func makeIterator() -> RLMIterator<RLMObject> { return RLMIterator(collection: self) } } extension RLMCollection { // Swift query convenience functions public func indexOfObject(where predicateFormat: String, _ args: CVarArg...) -> UInt { return indexOfObject(with: NSPredicate(format: predicateFormat, arguments: getVaList(args))) } public func objects(where predicateFormat: String, _ args: CVarArg...) -> RLMResults<NSObject> { return objects(with: NSPredicate(format: predicateFormat, arguments: getVaList(args))) as! RLMResults<NSObject> } } // MARK: - Sync-related #if REALM_ENABLE_SYNC extension RLMSyncManager { public static var shared: RLMSyncManager { return __shared() } } extension RLMSyncUser { public static var current: RLMSyncUser? { return __current() } public static var all: [String: RLMSyncUser] { return __allUsers() } @nonobjc public var errorHandler: RLMUserErrorReportingBlock? { get { return __errorHandler } set { __errorHandler = newValue } } public static func logIn(with credentials: RLMSyncCredentials, server authServerURL: URL, timeout: TimeInterval = 30, callbackQueue queue: DispatchQueue = DispatchQueue.main, onCompletion completion: @escaping RLMUserCompletionBlock) { return __logIn(with: credentials, authServerURL: authServerURL, timeout: timeout, callbackQueue: queue, onCompletion: completion) } public func configuration(realmURL: URL? = nil, fullSynchronization: Bool = false, enableSSLValidation: Bool = true, urlPrefix: String? = nil) -> RLMRealmConfiguration { return self.__configuration(with: realmURL, fullSynchronization: fullSynchronization, enableSSLValidation: enableSSLValidation, urlPrefix: urlPrefix) } } extension RLMSyncSession { public func addProgressNotification(for direction: RLMSyncProgressDirection, mode: RLMSyncProgressMode, block: @escaping RLMProgressNotificationBlock) -> RLMProgressNotificationToken? { return __addProgressNotification(for: direction, mode: mode, block: block) } } #endif extension RLMNotificationToken { @available(*, unavailable, renamed: "invalidate()") @nonobjc public func stop() { fatalError() } }
apache-2.0
a4c322c409fe60d375d3c170827b82bb
36.069444
131
0.618584
5.338
false
false
false
false
kevinkang88/timeblocker
TimeBlocker/ViewController.swift
1
1058
// // ViewController.swift // TimeBlocker // // Created by dong yoon kang on 8/3/15. // Copyright (c) 2015 yoon kevin kang. All rights reserved. // import UIKit class ViewController: UIViewController { var timer = NSTimer() var count = 0 func updateTime(){ count++ timeLabel.text = "\(count)" } @IBOutlet var timeLabel: UILabel! @IBAction func pauseTapped(sender: AnyObject) { timer.invalidate() } @IBAction func playTapped(sender: AnyObject) { timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true) } @IBAction func stopTapped(sender: AnyObject) { timer.invalidate() count = 0 timeLabel.text = "0" } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
831a403cd1b86e60706a784c8bdddff6
20.16
135
0.60397
4.580087
false
false
false
false
Prince2k3/CollectionViewDataSource
Example Project Swift/Example Project Swift/ViewController3.swift
1
1541
// // ViewController3.swift // Example Project Swift // // Created by Prince Ugwuh on 10/12/16. // Copyright © 2016 MFX Studios. All rights reserved. // import UIKit class ViewController3: UIViewController, CollectionViewDataSourceDelegate { @IBOutlet weak var collectionView: UICollectionView! var sectionDataSource: CollectionViewSectionDataSource? override func viewDidLoad() { super.viewDidLoad() self.collectionView.register(TestCell.self, forCellWithReuseIdentifier: TestCell.identifier) build() } func build() { var dataSources = [CollectionViewDataSource]() for i in 0..<3 { var items = [Int]() for j in 0..<10 { items.append(j) } let dataSource = CollectionViewDataSource(cellIdentifier: TestCell.identifier, items: items) dataSource.title = "Section \(i)" dataSources.append(dataSource) } self.sectionDataSource = CollectionViewSectionDataSource(dataSources: dataSources) self.sectionDataSource?.delegate = self self.collectionView.dataSource = self.sectionDataSource } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func didConfigure(_ cell: CollectionReusableViewDataSource, at indexPath: IndexPath) { } }
mit
966bccac79efb6d4342ee587155654bd
27
104
0.619481
5.682657
false
true
false
false
kosicki123/eidolon
Kiosk/Bid Fulfillment/ConfirmYourBidViewController.swift
1
4989
import UIKit import ECPhoneNumberFormatter import Moya public class ConfirmYourBidViewController: UIViewController { dynamic var number: String = "" let phoneNumberFormatter = ECPhoneNumberFormatter() @IBOutlet public var bidDetailsPreviewView: BidDetailsPreviewView! @IBOutlet public var numberAmountTextField: TextField! @IBOutlet public var cursor: CursorView! @IBOutlet public var keypadContainer: KeypadContainerView! @IBOutlet public var enterButton: UIButton! @IBOutlet public var useArtsyLoginButton: UIButton! public lazy var keypadSignal:RACSignal! = self.keypadContainer.keypad?.keypadSignal public lazy var clearSignal:RACSignal! = self.keypadContainer.keypad?.rightSignal public lazy var deleteSignal:RACSignal! = self.keypadContainer.keypad?.leftSignal public lazy var provider:ReactiveMoyaProvider<ArtsyAPI> = Provider.sharedProvider public class func instantiateFromStoryboard() -> ConfirmYourBidViewController { return UIStoryboard.fulfillment().viewControllerWithID(.ConfirmYourBid) as ConfirmYourBidViewController } override public func viewDidLoad() { super.viewDidLoad() let titleString = useArtsyLoginButton.titleForState(useArtsyLoginButton.state)! ?? "" var attributes = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue, NSFontAttributeName: useArtsyLoginButton.titleLabel!.font]; let attrTitle = NSAttributedString(string: titleString, attributes:attributes) useArtsyLoginButton.setAttributedTitle(attrTitle, forState:useArtsyLoginButton.state) RAC(numberAmountTextField, "text") <~ RACObserve(self, "number").map(toPhoneNumberString) keypadSignal.subscribeNext(addDigitToNumber) deleteSignal.subscribeNext(deleteDigitFromNumber) clearSignal.subscribeNext(clearNumber) let nav = self.fulfillmentNav() RAC(nav.bidDetails.newUser, "phoneNumber") <~ RACObserve(self, "number") RAC(nav.bidDetails, "paddleNumber") <~ RACObserve(self, "number") bidDetailsPreviewView.bidDetails = nav.bidDetails // Does a bidder exist for this phone number? // if so forward to PIN input VC // else send to enter email if let nav = self.navigationController as? FulfillmentNavigationController { let numberIsZeroLengthSignal = RACObserve(self, "number").map(isZeroLengthString) enterButton.rac_command = RACCommand(enabled: numberIsZeroLengthSignal.not()) { [weak self] _ in if (self == nil) { return RACSignal.empty() } let endpoint: ArtsyAPI = ArtsyAPI.FindBidderRegistration(auctionID: nav.auctionID!, phone: self!.number) return XAppRequest(endpoint, provider:self!.provider, parameters:endpoint.defaultParameters).filterStatusCode(400).doError { (error) -> Void in // Due to AlamoFire restrictions we can't stop HTTP redirects // so to figure out if we got 302'd we have to introspect the // error to see if it's the original URL to know if the // request suceedded let moyaResponse = error.userInfo?["data"] as? MoyaResponse let responseURL = moyaResponse?.response?.URL?.absoluteString? if let responseURL = responseURL { if (responseURL as NSString).containsString("v1/bidder/") { self?.performSegue(.ConfirmyourBidBidderFound) return } } self?.performSegue(.ConfirmyourBidBidderNotFound) return } } } } func addDigitToNumber(input:AnyObject!) -> Void { self.number = "\(self.number)\(input)" } func deleteDigitFromNumber(input:AnyObject!) -> Void { self.number = dropLast(self.number) } func clearNumber(input:AnyObject!) -> Void { self.number = "" } func toOpeningBidString(cents:AnyObject!) -> AnyObject! { if let dollars = NSNumberFormatter.currencyStringForCents(cents as? Int) { return "Enter \(dollars) or more" } return "" } func toPhoneNumberString(number:AnyObject!) -> AnyObject! { let numberString = number as String if countElements(numberString) >= 7 { return self.phoneNumberFormatter.stringForObjectValue(numberString) } else { return numberString } } } private extension ConfirmYourBidViewController { @IBAction func dev_noPhoneNumberFoundTapped(sender: AnyObject) { self.performSegue(.ConfirmyourBidArtsyLogin ) } @IBAction func dev_phoneNumberFoundTapped(sender: AnyObject) { self.performSegue(.ConfirmyourBidBidderFound) } }
mit
5595198c231c2e7f2dea08573474bc75
38.595238
159
0.660854
5.284958
false
false
false
false
onekiloparsec/KPCTabsControl
KPCTabsControl/Helpers.swift
1
2050
// // Helpers.swift // KPCTabsControl // // Created by Cédric Foellmi on 03/09/16. // Licensed under the MIT License (see LICENSE file) // import Foundation /// Offset is a simple NSPoint typealias to increase readability. public typealias Offset = NSPoint extension Offset { public init(x: CGFloat) { self.init() self.x = x self.y = 0 } public init(y: CGFloat) { self.init() self.x = 0 self.y = y } } /** Addition operator for NSPoints and Offsets. - parameter lhs: lef-hand side point - parameter rhs: right-hand side offset to be added to the point. - returns: A new and offset NSPoint. */ public func +(lhs: NSPoint, rhs: Offset) -> NSPoint { return NSPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } /** A convenience extension to easily shrink a NSRect */ extension NSRect { /// Change width and height by `-dx` and `-dy`. public func shrinkBy(dx: CGFloat, dy: CGFloat) -> NSRect { var result = self result.size = CGSize(width: result.size.width - dx, height: result.size.height - dy) return result } } /** Convenience function to easily compare tab widths. - parameter t1: The first tab width - parameter t2: The second tab width - returns: A boolean to indicate whether the tab widths are identical or not. */ func ==(t1: TabWidth, t2: TabWidth) -> Bool { return String(describing: t1) == String(describing: t2) } /// Helper functions to let compare optionals func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l >= r default: return !(lhs < rhs) } } func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } }
mit
d7a230754d126a62a9530c8f00e3a74c
20.123711
92
0.591996
3.544983
false
false
false
false
seuzl/iHerald
Herald/API.swift
1
6029
// // API.swift // Herald // // Created by lizhuoli on 15/5/9. // Copyright (c) 2015年 WangShuo. All rights reserved. // import Foundation protocol APIGetter{ func getResult(APIName:String, results:JSON) func getError(APIName:String, statusCode:Int) } class HeraldAPI{ //先声公开API的appid let appid = "9f9ce5c3605178daadc2d85ce9f8e064" //代理模式,在VC使用的时候实例化一个代理,即let API = HeraldAPI(); API.delegate = self var delegate:APIGetter? //manager是AFNetworking的一个管理者,需要首先初始化一个 var manager = AFHTTPRequestOperationManager() //plist是APIList.plist的根字典 var plist:NSDictionary? //apiList是从APIList.plist中API List的字典,存储API的URL,Query等记录 var apiList:NSDictionary? init(){ let file = NSFileManager.defaultManager() var plistPath = Tool.libraryPath + "APIList.plist" if !file.fileExistsAtPath(plistPath) { let bundle = NSBundle.mainBundle() plistPath = bundle.pathForResource("APIList", ofType: "plist") ?? "" } if let plistContent = NSDictionary(contentsOfFile: plistPath){ plist = plistContent apiList = plistContent["API List"] as? NSDictionary } } //单独获取属性表的根路径下的Key对应的值 func getValue(key:String) -> String? { return plist?[key] as? String ?? nil } func sendAPI(APIName:String, APIParameter:String...){ //发送API,要确保APIParameter数组按照API Info.plist表中规定的先后顺序 if apiList == nil{ return; } let uuid = Config.UUID ?? "" if let apiName = apiList?[APIName] as? NSDictionary{ let apiURL = apiName["URL"] as? String ?? "" let apiParamArray = apiName["Param"] as? [String] ?? ["uuid"]//从API列表中读到的参数列表 var apiParameter = APIParameter//方法调用的传入参数列表 for param in apiParamArray{ if param == "uuid"{ apiParameter.append(uuid) break } if param == "appid"{ apiParameter.append(appid) break } } let apiParamDic = NSDictionary(objects: apiParameter, forKeys: apiParamArray)//将从plist属性表中的读取到的参数数的值作为key,将方法传入的参数作为value,传入要发送的参数字典 self.postRequest(apiURL, parameter: apiParamDic, tag: APIName) } } //对请求结果进行代理 func didReceiveResults(results: AnyObject, tag: String){ let json = JSON(results)//一个非常好的东西,能方便操作JSON,甚至对不是JSON格式(比如字符串,数组),保留了这个类型本身 self.delegate?.getResult(tag, results: json) } //对错误进行代理 func didReceiveError(code: Int, tag: String) { self.delegate?.getError(tag, statusCode: code) } //POST请求,接收MIME类型为text/html,只处理非JSON返回格式的数据 func postRequest(url:String,parameter:NSDictionary,tag:String) { print("\nRequest:\n\(parameter)\n***********\n") manager.responseSerializer = AFHTTPResponseSerializer()//使用自定义的Serializer,手动对返回数据进行判断 manager.POST(url, parameters: parameter, success: {(operation :AFHTTPRequestOperation!,responseObject :AnyObject!) ->Void in if let receiveData = responseObject as? NSData{ //按照NSDictionary -> NSArray -> NSString的顺序进行过滤 if let receiveDic = (try? NSJSONSerialization.JSONObjectWithData(receiveData, options: NSJSONReadingOptions.MutableContainers)) as? NSDictionary{ print("\nResponse(Dictionary):\n\(receiveDic)\n***********\n") if let statusCode = receiveDic["code"] as? Int {//部分API状态码虽然为200,但是返回content为空,code为500 if statusCode == 200{ self.didReceiveResults(receiveDic, tag: tag) } else{ self.didReceiveError(500, tag: tag) } } else{ self.didReceiveResults(receiveDic, tag: tag) } } else if let receiveArray = (try? NSJSONSerialization.JSONObjectWithData(receiveData, options: NSJSONReadingOptions.MutableContainers)) as? NSArray{ print("\nResponse(Array):\n\(receiveArray)\n***********\n") self.didReceiveResults(receiveArray, tag: tag) } else if let receiveString = NSString(data: receiveData,encoding: NSUTF8StringEncoding){ print("\nResponse(String):\n\(receiveString)\n***********\n") self.didReceiveResults(receiveString, tag: tag) }//默认使用UTF-8编码 else{ self.didReceiveError(500, tag: tag) } } }, failure: {(operation :AFHTTPRequestOperation?, error :NSError) ->Void in var codeStatue = 500//默认错误HTTP状态码为500 if let code = operation?.response?.statusCode { codeStatue = code } self.didReceiveError(codeStatue, tag: tag) print(error) } ) } //取消所有请求 func cancelAllRequest(){ manager.operationQueue.cancelAllOperations() } }
mit
d213a6666b3dc0b8f790d09cf604e8f1
37.211268
167
0.555207
4.517069
false
false
false
false
frootloops/swift
test/SILGen/objc_thunks.swift
1
29152
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -Xllvm -sil-print-debuginfo -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -emit-verbose-sil -enable-sil-ownership | %FileCheck %s // REQUIRES: objc_interop import gizmo import ansible class Hoozit : Gizmo { @objc func typical(_ x: Int, y: Gizmo) -> Gizmo { return y } // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytFTo : $@convention(objc_method) (Int, Gizmo, Hoozit) -> @autoreleased Gizmo { // CHECK: bb0([[X:%.*]] : @trivial $Int, [[Y:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[Y_COPY:%.*]] = copy_value [[Y]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref objc_thunks.Hoozit.typical // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytF : $@convention(method) (Int, @owned Gizmo, @guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[X]], [[Y_COPY]], [[BORROWED_THIS_COPY]]) {{.*}} line:[[@LINE-8]]:14:auto_gen // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] : $Hoozit // CHECK-NEXT: return [[RES]] : $Gizmo{{.*}} line:[[@LINE-11]]:14:auto_gen // CHECK-NEXT: } // end sil function '_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytFTo' // NS_CONSUMES_SELF by inheritance override func fork() { } // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC4forkyyFTo : $@convention(objc_method) (@owned Hoozit) -> () { // CHECK: bb0([[THIS:%.*]] : @owned $Hoozit): // CHECK-NEXT: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC4forkyyF : $@convention(method) (@guaranteed Hoozit) -> () // CHECK-NEXT: apply [[NATIVE]]([[BORROWED_THIS]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS]] from [[THIS]] // CHECK-NEXT: destroy_value [[THIS]] // CHECK-NEXT: return // CHECK-NEXT: } // NS_CONSUMED 'gizmo' argument by inheritance override class func consume(_ gizmo: Gizmo?) { } // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7consumeySo5GizmoCSgFZTo : $@convention(objc_method) (@owned Optional<Gizmo>, @objc_metatype Hoozit.Type) -> () { // CHECK: bb0([[GIZMO:%.*]] : @owned $Optional<Gizmo>, [[THIS:%.*]] : @trivial $@objc_metatype Hoozit.Type): // CHECK-NEXT: [[THICK_THIS:%[0-9]+]] = objc_to_thick_metatype [[THIS]] : $@objc_metatype Hoozit.Type to $@thick Hoozit.Type // CHECK: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7consumeySo5GizmoCSgFZ : $@convention(method) (@owned Optional<Gizmo>, @thick Hoozit.Type) -> () // CHECK-NEXT: apply [[NATIVE]]([[GIZMO]], [[THICK_THIS]]) // CHECK-NEXT: return // CHECK-NEXT: } // NS_RETURNS_RETAINED by family (-copy) @objc func copyFoo() -> Gizmo { return self } // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7copyFooSo5GizmoCyFTo : $@convention(objc_method) (Hoozit) -> @owned Gizmo // CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7copyFooSo5GizmoCyF : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } // Override the normal family conventions to make this non-consuming and // returning at +0. @objc func initFoo() -> Gizmo { return self } // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7initFooSo5GizmoCyFTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo // CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7initFooSo5GizmoCyF : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } @objc var typicalProperty: Gizmo // -- getter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo { // CHECK: bb0([[SELF:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref objc_thunks.Hoozit.typicalProperty.getter // CHECK-NEXT: [[GETIMPL:%.*]] = function_ref @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvg // CHECK-NEXT: [[RES:%.*]] = apply [[GETIMPL]]([[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return [[RES]] : $Gizmo // CHECK-NEXT: } // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK: bb0(%0 : @guaranteed $Hoozit): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Hoozit.typicalProperty // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Gizmo // CHECK-NEXT: [[RES:%.*]] = load [copy] [[READ]] {{.*}} // CHECK-NEXT: end_access [[READ]] : $*Gizmo // CHECK-NEXT: return [[RES]] // -- setter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit): // CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $Gizmo // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] : $Hoozit // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: // function_ref objc_thunks.Hoozit.typicalProperty.setter // CHECK: [[FR:%.*]] = function_ref @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvs // CHECK: [[RES:%.*]] = apply [[FR]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: return [[RES]] : $(), loc {{.*}}, scope {{.*}} // id: {{.*}} line:[[@LINE-34]]:13:auto_gen // CHECK: } // end sil function '_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvsTo' // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvs // CHECK: bb0([[ARG0:%.*]] : @owned $Gizmo, [[ARG1:%.*]] : @guaranteed $Hoozit): // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: [[ARG0_COPY:%.*]] = copy_value [[BORROWED_ARG0]] // CHECK: [[ADDR:%.*]] = ref_element_addr [[ARG1]] : {{.*}}, #Hoozit.typicalProperty // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Gizmo // CHECK: assign [[ARG0_COPY]] to [[WRITE]] : $*Gizmo // CHECK: end_access [[WRITE]] : $*Gizmo // CHECK: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK: destroy_value [[ARG0]] // CHECK: } // end sil function '_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvs' // NS_RETURNS_RETAINED getter by family (-copy) @objc var copyProperty: Gizmo // -- getter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @owned Gizmo { // CHECK: bb0([[SELF:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref objc_thunks.Hoozit.copyProperty.getter // CHECK-NEXT: [[FR:%.*]] = function_ref @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvg // CHECK-NEXT: [[RES:%.*]] = apply [[FR]]([[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvg // CHECK: bb0(%0 : @guaranteed $Hoozit): // CHECK: [[ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Hoozit.copyProperty // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Gizmo // CHECK-NEXT: [[RES:%.*]] = load [copy] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Gizmo // CHECK-NEXT: return [[RES]] // -- setter is normal // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref objc_thunks.Hoozit.copyProperty.setter // CHECK-NEXT: [[FR:%.*]] = function_ref @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvs // CHECK-NEXT: [[RES:%.*]] = apply [[FR]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvs // CHECK: bb0([[ARG1:%.*]] : @owned $Gizmo, [[SELF:%.*]] : @guaranteed $Hoozit): // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]] // CHECK: [[ARG1_COPY:%.*]] = copy_value [[BORROWED_ARG1]] // CHECK: [[ADDR:%.*]] = ref_element_addr [[SELF]] : {{.*}}, #Hoozit.copyProperty // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Gizmo // CHECK: assign [[ARG1_COPY]] to [[WRITE]] // CHECK: end_access [[WRITE]] : $*Gizmo // CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]] // CHECK: destroy_value [[ARG1]] // CHECK: } // end sil function '_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvs' @objc var roProperty: Gizmo { return self } // -- getter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC10roPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo { // CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC10roPropertySo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] : $Hoozit // CHECK-NEXT: return [[RES]] : $Gizmo // CHECK-NEXT: } // end sil function '_T011objc_thunks6HoozitC10roPropertySo5GizmoCvgTo' // -- no setter // CHECK-NOT: sil hidden [thunk] @_T011objc_thunks6HoozitC10roPropertySo5GizmoCvsTo @objc var rwProperty: Gizmo { get { return self } set {} } // -- getter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC10rwPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo // -- setter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC10rwPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC10rwPropertySo5GizmoCvs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> () // CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return // CHECK-NEXT: } @objc var copyRWProperty: Gizmo { get { return self } set {} } // -- getter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @owned Gizmo { // CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NOT: return // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } // -- setter is normal // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCvs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> () // CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return // CHECK-NEXT: } @objc var initProperty: Gizmo // -- getter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12initPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo { // CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12initPropertySo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } // -- setter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12initPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12initPropertySo5GizmoCvs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> () // CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return // CHECK-NEXT: } @objc var propComputed: Gizmo { @objc(initPropComputedGetter) get { return self } @objc(initPropComputedSetter:) set {} } // -- getter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12propComputedSo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo { // CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12propComputedSo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } // -- setter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12propComputedSo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12propComputedSo5GizmoCvs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> () // CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return // CHECK-NEXT: } // Don't export generics to ObjC yet func generic<T>(_ x: T) {} // CHECK-NOT: sil hidden [thunk] @_TToFC11objc_thunks6Hoozit7generic{{.*}} // Constructor. // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitCACSi7bellsOn_tcfc : $@convention(method) (Int, @owned Hoozit) -> @owned Hoozit { // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Hoozit } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[GIZMO:%[0-9]+]] = upcast [[SELF:%[0-9]+]] : $Hoozit to $Gizmo // CHECK: [[BORROWED_GIZMO:%.*]] = begin_borrow [[GIZMO]] // CHECK: [[CAST_BORROWED_GIZMO:%.*]] = unchecked_ref_cast [[BORROWED_GIZMO]] : $Gizmo to $Hoozit // CHECK: [[SUPERMETHOD:%[0-9]+]] = objc_super_method [[CAST_BORROWED_GIZMO]] : $Hoozit, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> (Int) -> Gizmo!, $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo> // CHECK-NEXT: end_borrow [[BORROWED_GIZMO]] from [[GIZMO]] // CHECK-NEXT: [[SELF_REPLACED:%[0-9]+]] = apply [[SUPERMETHOD]](%0, [[X:%[0-9]+]]) : $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo> // CHECK-NOT: unconditional_checked_cast downcast [[SELF_REPLACED]] : $Gizmo to $Hoozit // CHECK: unchecked_ref_cast // CHECK: return override init(bellsOn x : Int) { super.init(bellsOn: x) other() } // Subscript @objc subscript (i: Int) -> Hoozit { // Getter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCACSicigTo : $@convention(objc_method) (Int, Hoozit) -> @autoreleased Hoozit // CHECK: bb0([[I:%[0-9]+]] : @trivial $Int, [[SELF:%[0-9]+]] : @unowned $Hoozit): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Hoozit // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%[0-9]+]] = function_ref @_T011objc_thunks6HoozitCACSicig : $@convention(method) (Int, @guaranteed Hoozit) -> @owned Hoozit // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[NATIVE]]([[I]], [[BORROWED_SELF_COPY]]) : $@convention(method) (Int, @guaranteed Hoozit) -> @owned Hoozit // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return [[RESULT]] : $Hoozit get { return self } // Setter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCACSicisTo : $@convention(objc_method) (Hoozit, Int, Hoozit) -> () // CHECK: bb0([[VALUE:%[0-9]+]] : @unowned $Hoozit, [[I:%[0-9]+]] : @trivial $Int, [[SELF:%[0-9]+]] : @unowned $Hoozit): // CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $Hoozit // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Hoozit // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE:%[0-9]+]] = function_ref @_T011objc_thunks6HoozitCACSicis : $@convention(method) (@owned Hoozit, Int, @guaranteed Hoozit) -> () // CHECK: [[RESULT:%[0-9]+]] = apply [[NATIVE]]([[VALUE_COPY]], [[I]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Hoozit, Int, @guaranteed Hoozit) -> () // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: return [[RESULT]] : $() // CHECK: } // end sil function '_T011objc_thunks6HoozitCACSicisTo' set {} } } class Wotsit<T> : Gizmo { // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitC5plainyyFTo : $@convention(objc_method) <T> (Wotsit<T>) -> () { // CHECK: bb0([[SELF:%.*]] : @unowned $Wotsit<T>): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Wotsit<T> // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6WotsitC5plainyyF : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> () // CHECK-NEXT: [[RESULT:%.*]] = apply [[NATIVE]]<T>([[BORROWED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> () // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] : $Wotsit<T> // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } @objc func plain() { } func generic<U>(_ x: U) {} var property : T init(t: T) { self.property = t super.init() } // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitC11descriptionSSvgTo : $@convention(objc_method) <T> (Wotsit<T>) -> @autoreleased NSString { // CHECK: bb0([[SELF:%.*]] : @unowned $Wotsit<T>): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Wotsit<T> // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6WotsitC11descriptionSSvg : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> @owned String // CHECK-NEXT: [[RESULT:%.*]] = apply [[NATIVE:%.*]]<T>([[BORROWED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> @owned String // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] : $Wotsit<T> // CHECK-NEXT: // function_ref // CHECK-NEXT: [[BRIDGE:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK-NEXT: [[BORROWED_RESULT:%.*]] = begin_borrow [[RESULT]] // CHECK-NEXT: [[NSRESULT:%.*]] = apply [[BRIDGE]]([[BORROWED_RESULT]]) : $@convention(method) (@guaranteed String) -> @owned NSString // CHECK-NEXT: end_borrow [[BORROWED_RESULT]] from [[RESULT]] // CHECK-NEXT: destroy_value [[RESULT]] // CHECK-NEXT: return [[NSRESULT]] : $NSString // CHECK-NEXT: } override var description : String { return "Hello, world." } // Ivar destroyer // CHECK: sil hidden @_T011objc_thunks6WotsitCfETo // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitCSQyACyxGGycfcTo : $@convention(objc_method) <T> (@owned Wotsit<T>) -> @owned Optional<Wotsit<T>> // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitCSQyACyxGGSi7bellsOn_tcfcTo : $@convention(objc_method) <T> (Int, @owned Wotsit<T>) -> @owned Optional<Wotsit<T>> } // CHECK-NOT: sil hidden [thunk] @_TToF{{.*}}Wotsit{{.*}} // Extension initializers, properties and methods need thunks too. extension Hoozit { // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCACSi3int_tcfcTo : $@convention(objc_method) (Int, @owned Hoozit) -> @owned Hoozit @objc dynamic convenience init(int i: Int) { self.init(bellsOn: i) } // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitCACSd6double_tcfc : $@convention(method) (Double, @owned Hoozit) -> @owned Hoozit convenience init(double d: Double) { // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Hoozit } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[X_BOX:%[0-9]+]] = alloc_box ${ var X } var x = X() // CHECK: [[CTOR:%[0-9]+]] = objc_method [[SELF:%[0-9]+]] : $Hoozit, #Hoozit.init!initializer.1.foreign : (Hoozit.Type) -> (Int) -> Hoozit, $@convention(objc_method) (Int, @owned Hoozit) -> @owned Hoozit // CHECK: [[NEW_SELF:%[0-9]+]] = apply [[CTOR]] // CHECK: store [[NEW_SELF]] to [init] [[PB_BOX]] : $*Hoozit // CHECK: return self.init(int:Int(d)) other() } func foof() {} // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC4foofyyFTo : $@convention(objc_method) (Hoozit) -> () { var extensionProperty: Int { return 0 } // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC17extensionPropertySivg : $@convention(method) (@guaranteed Hoozit) -> Int } // Calling objc methods of subclass should go through native entry points func useHoozit(_ h: Hoozit) { // sil @_T011objc_thunks9useHoozityAA0D0C1h_tF // In the class decl, overrides importd method, 'dynamic' was inferred h.fork() // CHECK: objc_method {{%.*}} : {{.*}}, #Hoozit.fork!1.foreign // In an extension, 'dynamic' was inferred. h.foof() // CHECK: objc_method {{%.*}} : {{.*}}, #Hoozit.foof!1.foreign } func useWotsit(_ w: Wotsit<String>) { // sil @_T011objc_thunks9useWotsitySo0D0CySSG1w_tF w.plain() // CHECK: class_method {{%.*}} : {{.*}}, #Wotsit.plain!1 : w.generic(2) // CHECK: class_method {{%.*}} : {{.*}}, #Wotsit.generic!1 : // Inherited methods only have objc entry points w.clone() // CHECK: objc_method {{%.*}} : {{.*}}, #Gizmo.clone!1.foreign } func other() { } class X { } // CHECK-LABEL: sil hidden @_T011objc_thunks8propertySiSo5GizmoCF func property(_ g: Gizmo) -> Int { // CHECK: bb0([[ARG:%.*]] : @owned $Gizmo): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: objc_method [[BORROWED_ARG]] : $Gizmo, #Gizmo.count!getter.1.foreign return g.count } // CHECK-LABEL: sil hidden @_T011objc_thunks13blockPropertyySo5GizmoCF func blockProperty(_ g: Gizmo) { // CHECK: bb0([[ARG:%.*]] : @owned $Gizmo): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: objc_method [[BORROWED_ARG]] : $Gizmo, #Gizmo.block!setter.1.foreign g.block = { } // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: objc_method [[BORROWED_ARG]] : $Gizmo, #Gizmo.block!getter.1.foreign g.block() } class DesignatedStubs : Gizmo { var i: Int override init() { i = 5 } // CHECK-LABEL: sil hidden @_T011objc_thunks15DesignatedStubsCSQyACGSi7bellsOn_tcfc // CHECK: string_literal utf8 "objc_thunks.DesignatedStubs" // CHECK: string_literal utf8 "init(bellsOn:)" // CHECK: string_literal utf8 "{{.*}}objc_thunks.swift" // CHECK: function_ref @_T0s25_unimplementedInitializers5NeverOs12StaticStringV9className_AE04initG0AE4fileSu4lineSu6columntF // CHECK: return // CHECK-NOT: sil hidden @_TFCSo15DesignatedStubsc{{.*}} } class DesignatedOverrides : Gizmo { var i: Int = 5 // CHECK-LABEL: sil hidden @_T011objc_thunks19DesignatedOverridesCSQyACGycfc // CHECK-NOT: return // CHECK: function_ref @_T011objc_thunks19DesignatedOverridesC1iSivpfi : $@convention(thin) () -> Int // CHECK: objc_super_method [[SELF:%[0-9]+]] : $DesignatedOverrides, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> () -> Gizmo!, $@convention(objc_method) (@owned Gizmo) -> @owned Optional<Gizmo> // CHECK: return // CHECK-LABEL: sil hidden @_T011objc_thunks19DesignatedOverridesCSQyACGSi7bellsOn_tcfc // CHECK: function_ref @_T011objc_thunks19DesignatedOverridesC1iSivpfi : $@convention(thin) () -> Int // CHECK: objc_super_method [[SELF:%[0-9]+]] : $DesignatedOverrides, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> (Int) -> Gizmo!, $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo> // CHECK: return } // Make sure we copy blocks passed in as IUOs - <rdar://problem/22471309> func registerAnsible() { // CHECK: function_ref @_T011objc_thunks15registerAnsibleyyFyyycSgcfU_ Ansible.anseAsync({ completion in completion!() }) }
apache-2.0
5d84943484bbd2074f244936fab57bbc
54.618321
231
0.627917
3.351811
false
false
false
false
adrfer/swift
test/IRGen/objc_structs.swift
12
3720
// RUN: rm -rf %t && mkdir %t // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir | FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import Foundation import gizmo // CHECK: [[NSRECT:%VSC6NSRect]] = type <{ [[NSPOINT:%VSC7NSPoint]], [[NSSIZE:%VSC6NSSize]] }> // CHECK: [[NSPOINT]] = type <{ [[DOUBLE:%Sd]], [[DOUBLE]] }> // CHECK: [[DOUBLE]] = type <{ double }> // CHECK: [[NSSIZE]] = type <{ [[DOUBLE]], [[DOUBLE]] }> // CHECK: [[GIZMO:%CSo5Gizmo]] = type opaque // CHECK: [[NSSTRING:%CSo8NSString]] = type opaque // CHECK: [[NSVIEW:%CSo6NSView]] = type opaque // CHECK: define hidden void @_TF12objc_structs8getFrame{{.*}}([[NSRECT]]* noalias nocapture sret, [[GIZMO]]*) {{.*}} { func getFrame(g: Gizmo) -> NSRect { // CHECK: load i8*, i8** @"\01L_selector(frame)" // CHECK: call void bitcast (void ()* @objc_msgSend_stret to void ([[NSRECT]]*, [[OPAQUE0:.*]]*, i8*)*)([[NSRECT]]* noalias nocapture sret {{.*}}, [[OPAQUE0:.*]]* {{.*}}, i8* {{.*}}) return g.frame() } // CHECK: } // CHECK: define hidden void @_TF12objc_structs8setFrame{{.*}}(%CSo5Gizmo*, %VSC6NSRect* noalias nocapture dereferenceable({{.*}})) {{.*}} { func setFrame(g: Gizmo, frame: NSRect) { // CHECK: load i8*, i8** @"\01L_selector(setFrame:)" // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OPAQUE0:.*]]*, i8*, [[NSRECT]]*)*)([[OPAQUE0:.*]]* {{.*}}, i8* {{.*}}, [[NSRECT]]* byval align 8 {{.*}}) g.setFrame(frame) } // CHECK: } // CHECK: define hidden void @_TF12objc_structs8makeRect{{.*}}([[NSRECT]]* noalias nocapture sret, double, double, double, double) func makeRect(a: Double, b: Double, c: Double, d: Double) -> NSRect { // CHECK: call void @NSMakeRect([[NSRECT]]* noalias nocapture sret {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}) return NSMakeRect(a,b,c,d) } // CHECK: } // CHECK: define hidden [[stringLayout:[^@]*]] @_TF12objc_structs14stringFromRect{{.*}}(%VSC6NSRect* noalias nocapture dereferenceable({{.*}})) {{.*}} { func stringFromRect(r: NSRect) -> String { // CHECK: call [[OPAQUE0:.*]]* @NSStringFromRect([[NSRECT]]* byval align 8 {{.*}}) return NSStringFromRect(r) } // CHECK: } // CHECK: define hidden void @_TF12objc_structs9insetRect{{.*}}([[NSRECT]]* noalias nocapture sret, %VSC6NSRect* noalias nocapture dereferenceable({{.*}}), double, double) func insetRect(r: NSRect, x: Double, y: Double) -> NSRect { // CHECK: call void @NSInsetRect([[NSRECT]]* noalias nocapture sret {{.*}}, [[NSRECT]]* byval align 8 {{.*}}, double {{.*}}, double {{.*}}) return NSInsetRect(r, x, y) } // CHECK: } // CHECK: define hidden void @_TF12objc_structs19convertRectFromBase{{.*}}([[NSRECT]]* noalias nocapture sret, [[NSVIEW]]*, [[NSRECT]]* noalias nocapture dereferenceable({{.*}})) func convertRectFromBase(v: NSView, r: NSRect) -> NSRect { // CHECK: load i8*, i8** @"\01L_selector(convertRectFromBase:)", align 8 // CHECK: call void bitcast (void ()* @objc_msgSend_stret to void ([[NSRECT]]*, [[OPAQUE0:.*]]*, i8*, [[NSRECT]]*)*)([[NSRECT]]* noalias nocapture sret {{.*}}, [[OPAQUE0:.*]]* {{.*}}, i8* {{.*}}, [[NSRECT]]* byval align 8 {{.*}}) return v.convertRectFromBase(r) } // CHECK: } // CHECK: define hidden void @_TF12objc_structs20useStructOfNSStringsFVSC17StructOfNSStringsS0_(%VSC17StructOfNSStrings* noalias nocapture sret, %VSC17StructOfNSStrings* noalias nocapture dereferenceable({{.*}})) // CHECK: call void @useStructOfNSStringsInObjC(%VSC17StructOfNSStrings* noalias nocapture sret {{%.*}}, %VSC17StructOfNSStrings* byval align 8 {{%.*}}) func useStructOfNSStrings(s: StructOfNSStrings) -> StructOfNSStrings { return useStructOfNSStringsInObjC(s) }
apache-2.0
6e38982439ce2b2570e7d96786a0f065
53.705882
231
0.637366
3.839009
false
false
false
false
nghialv/MaterialKit
Source/MKCardView.swift
2
4662
// // The MIT License (MIT) // // Copyright (c) 2014 Andrew Clissold // // 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 @IBDesignable public class MKCardView: UIControl { @IBInspectable public var elevation: CGFloat = 2 { didSet { mkLayer.elevation = elevation } } @IBInspectable public var cornerRadius: CGFloat = 0 { didSet { self.layer.cornerRadius = cornerRadius mkLayer.superLayerDidResize() } } @IBInspectable public var shadowOffset: CGSize = CGSizeZero { didSet { mkLayer.shadowOffset = shadowOffset } } @IBInspectable public var roundingCorners: UIRectCorner = UIRectCorner.AllCorners { didSet { mkLayer.roundingCorners = roundingCorners } } @IBInspectable public var maskEnabled: Bool = true { didSet { mkLayer.maskEnabled = maskEnabled } } @IBInspectable public var rippleScaleRatio: CGFloat = 1.0 { didSet { mkLayer.rippleScaleRatio = rippleScaleRatio } } @IBInspectable public var rippleDuration: CFTimeInterval = 0.35 { didSet { mkLayer.rippleDuration = rippleDuration } } @IBInspectable public var rippleEnabled: Bool = true { didSet { mkLayer.rippleEnabled = rippleEnabled } } @IBInspectable public var rippleLayerColor: UIColor = UIColor(hex: 0xEEEEEE) { didSet { mkLayer.setRippleColor(rippleLayerColor) } } @IBInspectable public var backgroundAnimationEnabled: Bool = true { didSet { mkLayer.backgroundAnimationEnabled = backgroundAnimationEnabled } } override public var bounds: CGRect { didSet { mkLayer.superLayerDidResize() } } public lazy var mkLayer: MKLayer = MKLayer(withView: self) override public init(frame: CGRect) { super.init(frame: frame) setupLayer() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupLayer() } private func setupLayer() { mkLayer.elevation = self.elevation self.layer.cornerRadius = self.cornerRadius mkLayer.elevationOffset = self.shadowOffset mkLayer.roundingCorners = self.roundingCorners mkLayer.maskEnabled = self.maskEnabled mkLayer.rippleScaleRatio = self.rippleScaleRatio mkLayer.rippleDuration = self.rippleDuration mkLayer.rippleEnabled = self.rippleEnabled mkLayer.backgroundAnimationEnabled = self.backgroundAnimationEnabled mkLayer.setRippleColor(self.rippleLayerColor) } public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) mkLayer.touchesBegan(touches, withEvent: event) } public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesEnded(touches, withEvent: event) mkLayer.touchesEnded(touches, withEvent: event) } public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { super.touchesCancelled(touches, withEvent: event) mkLayer.touchesCancelled(touches, withEvent: event) } public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesMoved(touches, withEvent: event) mkLayer.touchesMoved(touches, withEvent: event) } }
mit
1d25e3ab13105d8fac8f3977dbfa5bf4
34.325758
94
0.670313
5.174251
false
false
false
false
evering7/iSpeak8
Pods/FeedKit/Sources/FeedKit/Models/RSS/RSSFeedItemEnclosure.swift
2
3469
// // RSSFeedItemEnclosure.swift // // Copyright (c) 2017 Nuno Manuel Dias // // 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 /// Describes a media object that is attached to the item. /// /// <enclosure> is an optional sub-element of <item>. /// /// It has three required attributes. url says where the enclosure is located, /// length says how big it is in bytes, and type says what its type is, a /// standard MIME type. /// /// The url must be an http url. /// /// <enclosure url="http://www.scripting.com/mp3s/weatherReportSuite.mp3" /// length="12216320" type="audio/mpeg" /> public class RSSFeedItemEnclosure { /// The element's attributes. public class Attributes { /// Where the enclosure is located. /// /// Example: http://www.scripting.com/mp3s/weatherReportSuite.mp3 public var url: String? /// How big the media object is in bytes. /// /// Example: 12216320 public var length: Int64? /// Standard MIME type. /// /// Example: audio/mpeg public var type: String? } /// The element's attributes. public var attributes: Attributes? } // MARK: - Initializers extension RSSFeedItemEnclosure { convenience init(attributes attributeDict: [String : String]) { self.init() self.attributes = RSSFeedItemEnclosure.Attributes(attributes: attributeDict) } } extension RSSFeedItemEnclosure.Attributes { convenience init?(attributes attributeDict: [String : String]) { if attributeDict.isEmpty { return nil } self.init() self.url = attributeDict["url"] self.type = attributeDict["type"] self.length = Int64(attributeDict["length"] ?? "") } } // MARK: - Equatable extension RSSFeedItemEnclosure: Equatable { public static func ==(lhs: RSSFeedItemEnclosure, rhs: RSSFeedItemEnclosure) -> Bool { return lhs.attributes == rhs.attributes } } extension RSSFeedItemEnclosure.Attributes: Equatable { public static func ==(lhs: RSSFeedItemEnclosure.Attributes, rhs: RSSFeedItemEnclosure.Attributes) -> Bool { return lhs.url == rhs.url && lhs.type == rhs.type && lhs.length == rhs.length } }
mit
aceb1afc5d18b7399e48c1eb05369dd0
29.429825
111
0.650043
4.352572
false
false
false
false
SkywellDevelopers/SWSkelethon
SWSkelethon/Classes/Core/Network/RestApiClient/APIResponseParser.swift
1
2160
// // APIResponseParser.swift // TemplateProject // // Created by Krizhanovskii on 3/3/17. // Copyright © 2017 skywell.com.ua. All rights reserved. // import Foundation import Alamofire /// Response parser protocol public protocol ResponseParserProtocol { /// typealiace for parse Error from JSON associatedtype ErrorParser : ErrorParserProtocol /// parse Response static func parseResponse<T: APIRequestProtocol>(response: DataResponse<Any>, request: T, success: ((T.Response) -> Void)?, failure: ResponseHandler?) } //EXAMPLE: /* class ResponseParser: ResponseParserProtocol { typealias ErrorParser = ErrorParserHandler static func parseResponse<T: APIRequestProtocol>(response: DataResponse<Any>, request: T, success: ((T.Response) -> Void)?, failure: ResponseHandler?) { switch response.result { case .failure(let error): let err = error as NSError failure?( ErrorParser( StatusCode(rawValue: err.code) ?? .badRequest, message: (response.result.value as? DictionaryAlias)?["message"] as? String ?? err.localizedDescription ) ) return default: break } guard let JSON = response.result.value as AnyObject? else { return } if let statusCode = response.response?.statusCode , 200..<300 ~= statusCode { if let dict = JSON as? DictionaryAlias { success?(T.Response(JSON: dict)) } else if let arrOfDict = JSON as? ArrayOfDictionaries { success?(T.Response(JSON: ["data":arrOfDict])) } else { success?(T.Response(JSON: [:])) } } else { failure?(ErrorParser.parseError(JSON)) } } } */
mit
b9c2a8ea8149d3b9d44343dac255c853
30.289855
123
0.514127
5.424623
false
false
false
false
gajjartejas/SMDImagePicker
SMDImagePicker/SMDMedia.swift
1
3938
// // SMDMedia.swift // SMDImagePicker // // Created by Tejas on 15/10/17. // Copyright © 2017 Gajjar Tejas. All rights reserved. // import UIKit import Photos open class SMDMedia: NSObject { /// The value for this key is an NSString object containing a type code such as kUTTypeImage or kUTTypeMovie.(UIImagePickerControllerMediaType) public var mediaType: String? /// The value for this key is a UIImage object.(UIImagePickerControllerOriginalImage) public var originalImage: UIImage? /// The value of this key is a NSURL that you can use to retrieve the image file. The image in this file matches the image found in the UIImagePickerControllerOriginalImage key of the dictionary.(UIImagePickerControllerImageURL) public var imageURL: NSURL? /// The value for this key is a UIImage object.(UIImagePickerControllerEditedImage) public var editedImage: UIImage? /// The value for this key is an NSValue object containing a CGRect opaque type.(UIImagePickerControllerCropRect) public var cropRect: NSValue? /// The value for this key is an NSURL object.(UIImagePickerControllerMediaURL) public var mediaURL: NSURL? /// This key is valid only when using an image picker whose source type is set to camera, and applies only to still images. The value for this key is an NSDictionary object that contains the metadata of the photo that was just captured.(UIImagePickerControllerMediaMetadata) public var metadata: NSDictionary? // TODO: Handel for iOS 9 /// When the user picks or captures a Live Photo, the editingInfo dictionary contains the UIImagePickerControllerLivePhoto key, with a PHLivePhoto representation of the photo as the corresponding value.(UIImagePickerControllerLivePhoto) //var livePhoto: PHLivePhoto? /// The value of this key is a PHAsset object.(UIImagePickerControllerPHAsset) public var phAsset: PHAsset? init(fromDictionary dictionary: [String:Any]) { mediaType = dictionary[UIImagePickerControllerMediaType] as? String originalImage = dictionary[UIImagePickerControllerOriginalImage] as? UIImage if #available(iOS 11.0, *) { imageURL = dictionary[UIImagePickerControllerImageURL] as? NSURL } else { // Fallback on earlier versions } editedImage = dictionary[UIImagePickerControllerEditedImage] as? UIImage cropRect = dictionary[UIImagePickerControllerCropRect] as? NSValue mediaURL = dictionary[UIImagePickerControllerMediaURL] as? NSURL metadata = dictionary[UIImagePickerControllerMediaMetadata] as? NSDictionary if #available(iOS 11.0, *) { phAsset = dictionary[UIImagePickerControllerPHAsset] as? PHAsset } else { // Fallback on earlier versions } } } extension SMDMedia { public var videoThumb: UIImage? { get { guard let url = mediaURL else { return nil } let videoThumb = getThumbnailFrom(path: url as URL) return videoThumb } } func getThumbnailFrom(path: URL) -> UIImage? { do { let asset = AVURLAsset(url: path , options: nil) let imgGenerator = AVAssetImageGenerator(asset: asset) imgGenerator.appliesPreferredTrackTransform = true let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil) let thumbnail = UIImage(cgImage: cgImage) return thumbnail } catch let error { print("*** Error generating thumbnail: \(error.localizedDescription)") return nil } } }
gpl-3.0
0f3e376d429d57abf12bda5af11c7b56
35.794393
278
0.651765
5.764275
false
false
false
false
flypaper0/ethereum-wallet
ethereum-wallet/Classes/PresentationLayer/Start/Import/View/ImportViewController.swift
1
3230
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import UIKit class ImportViewController: UIViewController { @IBOutlet var titleLabel: UILabel! @IBOutlet var inputTextView: DefaultTextField! @IBOutlet var icloudButton: UIButton! @IBOutlet var confirmButton: UIButton! @IBOutlet var bottomConstraint: NSLayoutConstraint! var output: ImportViewOutput! // MARK: Life cycle override func viewDidLoad() { super.viewDidLoad() inputTextView.textField.delegate = self setupKeyboardNotifications() localize() output.viewIsReady() } // MARK: Privates private func localize() { titleLabel.text = Localized.importTitle() icloudButton.setTitle(Localized.importIcloudTitle(), for: .normal) confirmButton.setTitle(Localized.importConfirmTitle(), for: .normal) } private func setupKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc func keyboardWillShow(notification: Notification){ let userInfo = notification.userInfo! let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue bottomConstraint.constant = keyboardFrame.size.height + 16 view.layoutIfNeeded() } @objc func keyboardWillHide(notification: Notification){ bottomConstraint.constant = 16 view.layoutIfNeeded() } // MARK: Action @IBAction func icloudPressed(_ sender: UIButton) { let documentPicker = UIDocumentPickerViewController(documentTypes: ["public.text"], in: .import) documentPicker.delegate = self present(documentPicker, animated: true, completion: nil) } @IBAction func confirmPressed(_ sender: UIButton) { output.didConfirmKey(inputTextView.textField.text!) } } // MARK: - ImportViewInput extension ImportViewController: ImportViewInput { func setupInitialState() { } func setState(_ state: ImportStateProtocol) { inputTextView.placeholder = state.placeholder icloudButton.isHidden = !state.iCloudImportEnabled } } // MARK: - UITextFieldDelegate extension ImportViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let text = (textField.text! as NSString).replacingCharacters(in: range, with: string) confirmButton.isEnabled = !text.isEmpty return true } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { confirmPressed(confirmButton) return true } } // MARK: UIDocumentPickerDelegate extension ImportViewController: UIDocumentPickerDelegate { func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { if let url = urls.first, let text = try? String(contentsOfFile: url.path) { output.didConfirmKey(text) } } }
gpl-3.0
9ffc34a78d4211c5dceece7bf3b5bd5b
27.078261
148
0.741716
5.029595
false
false
false
false
xudesheng/ThumbExpense
ThumbExpense/ThumbView.swift
1
2769
// // ThumbView.swift // ThumbExpense // // Created by Desheng Xu on 12/21/15. // Copyright © 2015 Desheng Xu. All rights reserved. // import UIKit class ThumbView: UIView { /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation.*/ override func drawRect(rect: CGRect) { // Drawing code //print("current View has width with var: \(radius)") let deltaAngle : Double = 90.0 / Double(numberOfCommand) let context = UIGraphicsGetCurrentContext() for index in 1...numberOfCommand{ let startAngle = (90 + Double((index-1)) * deltaAngle + ThumbScale.AngleStartBias) * M_PI / 180 let endAngle = (90 + Double(index) * deltaAngle - ThumbScale.AngleEndBias) * M_PI / 180 print("Start Angle:\(startAngle) and End Angle:\(endAngle)") let x0 = radius - ThumbScale.RadiusShortFactor * radius * sin(startAngle) let y0 = radius + ThumbScale.RadiusShortFactor * radius * cos(startAngle) let x1 = radius - ThumbScale.RadiusLongFactor * radius * sin(startAngle) let y1 = radius + ThumbScale.RadiusLongFactor * radius * cos(startAngle) let x2 = radius - ThumbScale.RadiusLongFactor * radius * sin(endAngle) let y2 = radius + ThumbScale.RadiusLongFactor * radius * cos(endAngle) let x3 = radius - ThumbScale.RadiusShortFactor * radius * sin(endAngle) let y3 = radius + ThumbScale.RadiusShortFactor * radius * cos(endAngle) var points = [CGPoint]() points.append(CGPoint(x: x0,y: y0)) points.append(CGPoint(x: x1,y: y1)) points.append(CGPoint(x: x2,y: y2)) points.append(CGPoint(x: x3,y: y3)) print("Points are:\(points)") CGContextAddLines(context, points, points.count) //let cgcolor = color.CGColor CGContextSetFillColorWithColor(context,UIColor.blueColor().CGColor) CGContextFillPath(context) } } private var radius: Double { return Double (bounds.size.width) } func showPoint(gesture: UITapGestureRecognizer){ if gesture.state == UIGestureRecognizerState.Ended { print("point:\(gesture.locationInView(self))") } } private struct ThumbScale { static let RadiusLongFactor = 0.95 static let RadiusShortFactor = 0.45 static let AngleStartBias = 2.0 static let AngleEndBias = 2.0 } var numberOfCommand = 4 //how many command this tool will draw }
mit
144cffc611984b98f4e79fa761be01bf
34.948052
107
0.599711
4.500813
false
false
false
false
jindulys/Leetcode_Solutions_Swift
Sources/Tree/655_PrintBinaryTree.swift
1
1541
// // 655_PrintBinaryTree.swift // LeetcodeSwift // // Created by yansong li on 2018-04-22. // Copyright © 2018 YANSONG LI. All rights reserved. // import Foundation /** Title: 655 Print Binary Tree URL: https://leetcode.com/problems/print-binary-tree Space: O(n) Time: O(n) */ class PrintBinaryTree { func printTree(_ root: TreeNode?) -> [[String]] { let (treeDepth, treeWidth) = findTreeDimension(root) var matrix = Array(repeatElement(Array(repeatElement("", count: treeWidth)), count: treeDepth)) fillNode(root, 0, 0, treeWidth, &matrix) return matrix } private func fillNode(_ node: TreeNode?, _ level: Int, _ startIndex: Int, _ endIndex: Int, _ matrix: inout [[String]]) { guard let vNode = node else { return } let middleIndex = startIndex + (endIndex - startIndex) / 2 matrix[level][middleIndex] = String(vNode.val) fillNode(vNode.left, level + 1, startIndex, middleIndex, &matrix) fillNode(vNode.right, level + 1, middleIndex + 1, endIndex, &matrix) } private func findTreeDimension(_ root: TreeNode?) -> (Int, Int) { guard let vRoot = root else { return (0, 0) } let (leftDepth, leftWidth) = findTreeDimension(vRoot.left) let (rightDepth, rightWidth) = findTreeDimension(vRoot.right) let childDepth = max(leftDepth, rightDepth) let childWidth = max(leftWidth, rightWidth) return (childDepth + 1, childWidth * 2 + 1) } }
mit
da69497f3973902acd5f0ef1c661b372
29.196078
90
0.624026
3.701923
false
false
false
false
xwu/swift
stdlib/public/core/MutableCollection.swift
1
17959
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A collection that supports subscript assignment. /// /// Collections that conform to `MutableCollection` gain the ability to /// change the value of their elements. This example shows how you can /// modify one of the names in an array of students. /// /// var students = ["Ben", "Ivy", "Jordell", "Maxime"] /// if let i = students.firstIndex(of: "Maxime") { /// students[i] = "Max" /// } /// print(students) /// // Prints "["Ben", "Ivy", "Jordell", "Max"]" /// /// In addition to changing the value of an individual element, you can also /// change the values of a slice of elements in a mutable collection. For /// example, you can sort *part* of a mutable collection by calling the /// mutable `sort()` method on a subscripted subsequence. Here's an /// example that sorts the first half of an array of integers: /// /// var numbers = [15, 40, 10, 30, 60, 25, 5, 100] /// numbers[0..<4].sort() /// print(numbers) /// // Prints "[10, 15, 30, 40, 60, 25, 5, 100]" /// /// The `MutableCollection` protocol allows changing the values of a /// collection's elements but not the length of the collection itself. For /// operations that require adding or removing elements, see the /// `RangeReplaceableCollection` protocol instead. /// /// Conforming to the MutableCollection Protocol /// ============================================ /// /// To add conformance to the `MutableCollection` protocol to your own /// custom collection, upgrade your type's subscript to support both read /// and write access. /// /// A value stored into a subscript of a `MutableCollection` instance must /// subsequently be accessible at that same position. That is, for a mutable /// collection instance `a`, index `i`, and value `x`, the two sets of /// assignments in the following code sample must be equivalent: /// /// a[i] = x /// let y = a[i] /// /// // Must be equivalent to: /// a[i] = x /// let y = x public protocol MutableCollection: Collection where SubSequence: MutableCollection { // FIXME: Associated type inference requires these. override associatedtype Element override associatedtype Index override associatedtype SubSequence /// Accesses the element at the specified position. /// /// For example, you can replace an element of an array by using its /// subscript. /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// streets[1] = "Butler" /// print(streets[1]) /// // Prints "Butler" /// /// You can subscript a collection with any valid index other than the /// collection's end index. The end index refers to the position one /// past the last element of a collection, so it doesn't correspond with an /// element. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. /// /// - Complexity: O(1) @_borrowed override subscript(position: Index) -> Element { get set } /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.firstIndex(of: "Evarts") // 4 /// streets[index!] = "Eustace" /// print(streets[index!]) /// // Prints "Eustace" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. /// /// - Complexity: O(1) override subscript(bounds: Range<Index>) -> SubSequence { get set } /// Reorders the elements of the collection such that all the elements /// that match the given predicate are after all the elements that don't /// match. /// /// After partitioning a collection, there is a pivot index `p` where /// no element before `p` satisfies the `belongsInSecondPartition` /// predicate and every element at or after `p` satisfies /// `belongsInSecondPartition`. This operation isn't guaranteed to be /// stable, so the relative ordering of elements within the partitions might /// change. /// /// In the following example, an array of numbers is partitioned by a /// predicate that matches elements greater than 30. /// /// var numbers = [30, 40, 20, 30, 30, 60, 10] /// let p = numbers.partition(by: { $0 > 30 }) /// // p == 5 /// // numbers == [30, 10, 20, 30, 30, 60, 40] /// /// The `numbers` array is now arranged in two partitions. The first /// partition, `numbers[..<p]`, is made up of the elements that /// are not greater than 30. The second partition, `numbers[p...]`, /// is made up of the elements that *are* greater than 30. /// /// let first = numbers[..<p] /// // first == [30, 10, 20, 30, 30] /// let second = numbers[p...] /// // second == [60, 40] /// /// Note that the order of elements in both partitions changed. /// That is, `40` appears before `60` in the original collection, /// but, after calling `partition(by:)`, `60` appears before `40`. /// /// - Parameter belongsInSecondPartition: A predicate used to partition /// the collection. All elements satisfying this predicate are ordered /// after all elements not satisfying it. /// - Returns: The index of the first element in the reordered collection /// that matches `belongsInSecondPartition`. If no elements in the /// collection match `belongsInSecondPartition`, the returned index is /// equal to the collection's `endIndex`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func partition( by belongsInSecondPartition: (Element) throws -> Bool ) rethrows -> Index /// Exchanges the values at the specified indices of the collection. /// /// Both parameters must be valid indices of the collection and not /// equal to `endIndex`. Passing the same index as both `i` and `j` has no /// effect. /// /// - Parameters: /// - i: The index of the first value to swap. /// - j: The index of the second value to swap. /// /// - Complexity: O(1) mutating func swapAt(_ i: Index, _ j: Index) /// Call `body(p)`, where `p` is a pointer to the collection's /// mutable contiguous storage. If no such storage exists, it is /// first created. If the collection does not support an internal /// representation in a form of mutable contiguous storage, `body` is not /// called and `nil` is returned. /// /// Often, the optimizer can eliminate bounds- and uniqueness-checks /// within an algorithm, but when that fails, invoking the /// same algorithm on `body`\ 's argument lets you trade safety for /// speed. @available(*, deprecated, renamed: "withContiguousMutableStorageIfAvailable") mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? /// Call `body(p)`, where `p` is a pointer to the collection's /// mutable contiguous storage. If no such storage exists, it is /// first created. If the collection does not support an internal /// representation in a form of mutable contiguous storage, `body` is not /// called and `nil` is returned. /// /// Often, the optimizer can eliminate bounds- and uniqueness-checks /// within an algorithm, but when that fails, invoking the /// same algorithm on `body`\ 's argument lets you trade safety for /// speed. mutating func withContiguousMutableStorageIfAvailable<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? } // TODO: swift-3-indexing-model - review the following extension MutableCollection { @inlinable @available(*, deprecated, renamed: "withContiguousMutableStorageIfAvailable") public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { return nil } @inlinable public mutating func withContiguousMutableStorageIfAvailable<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { return nil } /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.firstIndex(of: "Evarts") // 4 /// streets[index!] = "Eustace" /// print(streets[index!]) /// // Prints "Eustace" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. /// /// - Complexity: O(1) @available(*, unavailable) @inlinable public subscript(bounds: Range<Index>) -> Slice<Self> { get { _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex) return Slice(base: self, bounds: bounds) } set { _writeBackMutableSlice(&self, bounds: bounds, slice: newValue) } } // This unavailable default implementation of `subscript(bounds: Range<_>)` // prevents incomplete MutableCollection implementations from satisfying the // protocol through the use of the generic convenience implementation // `subscript<R: RangeExpression>(r: R)`. If that were the case, at // runtime the generic implementation would call itself // in an infinite recursion due to the absence of a better option. @available(*, unavailable) @_alwaysEmitIntoClient public subscript(bounds: Range<Index>) -> SubSequence { get { fatalError() } set { fatalError() } } /// Exchanges the values at the specified indices of the collection. /// /// Both parameters must be valid indices of the collection that are not /// equal to `endIndex`. Calling `swapAt(_:_:)` with the same index as both /// `i` and `j` has no effect. /// /// - Parameters: /// - i: The index of the first value to swap. /// - j: The index of the second value to swap. /// /// - Complexity: O(1) @inlinable public mutating func swapAt(_ i: Index, _ j: Index) { guard i != j else { return } let tmp = self[i] self[i] = self[j] self[j] = tmp } } extension MutableCollection where SubSequence == Slice<Self> { /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.firstIndex(of: "Evarts") // 4 /// streets[index!] = "Eustace" /// print(streets[index!]) /// // Prints "Eustace" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. /// /// - Complexity: O(1) @inlinable @_alwaysEmitIntoClient public subscript(bounds: Range<Index>) -> Slice<Self> { get { _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex) return Slice(base: self, bounds: bounds) } set { _writeBackMutableSlice(&self, bounds: bounds, slice: newValue) } } } //===----------------------------------------------------------------------===// // _rotate(in:shiftingToStart:) //===----------------------------------------------------------------------===// extension MutableCollection { /// Rotates the elements of the collection so that the element at `middle` /// ends up first. /// /// - Returns: The new index of the element that was first pre-rotation. /// /// - Complexity: O(*n*) @discardableResult internal mutating func _rotate( in subrange: Range<Index>, shiftingToStart middle: Index ) -> Index { var m = middle, s = subrange.lowerBound let e = subrange.upperBound // Handle the trivial cases if s == m { return e } if m == e { return s } // We have two regions of possibly-unequal length that need to be // exchanged. The return value of this method is going to be the // position following that of the element that is currently last // (element j). // // [a b c d e f g|h i j] or [a b c|d e f g h i j] // ^ ^ ^ ^ ^ ^ // s m e s m e // var ret = e // start with a known incorrect result. while true { // Exchange the leading elements of each region (up to the // length of the shorter region). // // [a b c d e f g|h i j] or [a b c|d e f g h i j] // ^^^^^ ^^^^^ ^^^^^ ^^^^^ // [h i j d e f g|a b c] or [d e f|a b c g h i j] // ^ ^ ^ ^ ^ ^ ^ ^ // s s1 m m1/e s s1/m m1 e // let (s1, m1) = _swapNonemptySubrangePrefixes(s..<m, m..<e) if m1 == e { // Left-hand case: we have moved element j into position. if // we haven't already, we can capture the return value which // is in s1. // // Note: the STL breaks the loop into two just to avoid this // comparison once the return value is known. I'm not sure // it's a worthwhile optimization, though. if ret == e { ret = s1 } // If both regions were the same size, we're done. if s1 == m { break } } // Now we have a smaller problem that is also a rotation, so we // can adjust our bounds and repeat. // // h i j[d e f g|a b c] or d e f[a b c|g h i j] // ^ ^ ^ ^ ^ ^ // s m e s m e s = s1 if s == m { m = m1 } } return ret } /// Swaps the elements of the two given subranges, up to the upper bound of /// the smaller subrange. The returned indices are the ends of the two /// ranges that were actually swapped. /// /// Input: /// [a b c d e f g h i j k l m n o p] /// ^^^^^^^ ^^^^^^^^^^^^^ /// lhs rhs /// /// Output: /// [i j k l e f g h a b c d m n o p] /// ^ ^ /// p q /// /// - Precondition: !lhs.isEmpty && !rhs.isEmpty /// - Postcondition: For returned indices `(p, q)`: /// /// - distance(from: lhs.lowerBound, to: p) == distance(from: /// rhs.lowerBound, to: q) /// - p == lhs.upperBound || q == rhs.upperBound internal mutating func _swapNonemptySubrangePrefixes( _ lhs: Range<Index>, _ rhs: Range<Index> ) -> (Index, Index) { assert(!lhs.isEmpty) assert(!rhs.isEmpty) var p = lhs.lowerBound var q = rhs.lowerBound repeat { swapAt(p, q) formIndex(after: &p) formIndex(after: &q) } while p != lhs.upperBound && q != rhs.upperBound return (p, q) } } // the legacy swap free function // /// Exchanges the values of the two arguments. /// /// The two arguments must not alias each other. To swap two elements of a /// mutable collection, use the `swapAt(_:_:)` method of that collection /// instead of this function. /// /// - Parameters: /// - a: The first value to swap. /// - b: The second value to swap. @inlinable public func swap<T>(_ a: inout T, _ b: inout T) { // Semantically equivalent to (a, b) = (b, a). // Microoptimized to avoid retain/release traffic. let p1 = Builtin.addressof(&a) let p2 = Builtin.addressof(&b) _debugPrecondition( p1 != p2, "swapping a location with itself is not supported") // Take from P1. let tmp: T = Builtin.take(p1) // Transfer P2 into P1. Builtin.initialize(Builtin.take(p2) as T, p1) // Initialize P2. Builtin.initialize(tmp, p2) }
apache-2.0
e3d59e495df2c0b73d61e145ac57ff06
37.373932
80
0.611504
4.154291
false
false
false
false
brightdigit/speculid
frameworks/speculid/Models/AnalyticsParameterKey.swift
1
494
public enum AnalyticsParameterKey: String { case hitType = "t", version = "v", trackingId = "tid", userTimingCategory = "utc", userTimingLabel = "utl", timing = "utt", clientId = "cid", userTimingVariable = "utv", applicationName = "an", applicationVersion = "av", eventAction = "ea", eventCategory = "ec", eventLabel = "el", eventValue = "ev", userLanguage = "ul", operatingSystemVersion = "cd1", model = "cd2", exceptionDescription = "exd", exceptionFatal = "exf" }
mit
f04b748c7a5e13407ced85e890be682e
53.888889
90
0.659919
3.742424
false
false
false
false
gyro-n/PaymentsIos
GyronPayments/Classes/PaymentsSDK.swift
1
2619
// // PaymentsSDK.swift // GyronPayments // // Created by Ye David on 10/27/16. // Copyright © 2016 gyron. All rights reserved. // import Foundation open class SDK { var api: RestApi public var authenticationResource: AuthenticationResource? public var merchantResource: MerchantResource? public var storeResource: StoreResource? // public var bankAccountResource: BankAccountResource? public var chargeResource: ChargeResource? // public var checkoutInfoResource: CheckoutInfoResource? public var refundResource: RefundResource? public var subscriptionResource: SubscriptionResource? public var transactionTokenResource: TransactionTokenResource? public var transactionHistoryResource: TransactionHistoryResource? public var transferResource: TransferResource? // public var verificationResource: VerificationResource? public var webhookResource: WebhookResource? public var ledgerResource: LedgerResource? // public var plaformsResource: PlatformsResource? public var cancelResource: CancelResource? // public var cardResource: CardResource? public var applicationTokenResource: ApplicationTokenResource? public init(options: Options) { self.api = RestApi(options: options) self.authenticationResource = AuthenticationResource(api: self.api) self.merchantResource = MerchantResource(api: self.api) self.storeResource = StoreResource(api: self.api) // self.bankAccountResource = BankAccountResource(api: self.api) self.chargeResource = ChargeResource(api: self.api) // self.checkoutInfoResource = CheckoutInfoResource(api: self.api) self.refundResource = RefundResource(api: self.api) self.subscriptionResource = SubscriptionResource(api: self.api) self.transactionTokenResource = TransactionTokenResource(api: self.api) self.transactionHistoryResource = TransactionHistoryResource(api: self.api) self.transferResource = TransferResource(api: self.api) // self.verificationResource = VerificationResource(api: self.api) self.webhookResource = WebhookResource(api: self.api) self.ledgerResource = LedgerResource(api: self.api) // self.plaformsResource = PlatformsResource(api: self.api) self.cancelResource = CancelResource(api: self.api) // self.cardResource = CardResource(api: self.api) self.applicationTokenResource = ApplicationTokenResource(api: self.api) } open func setApiOptions(options: Options) { self.api.setOptions(options: options) } }
mit
b43db13963bc5980ea8a281bdbb270b8
44.929825
83
0.740642
4.529412
false
false
false
false
jkolb/Shkadov
Shkadov/OneTriangle.swift
1
10602
/* The MIT License (MIT) Copyright (c) 2016 Justin Kolb 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 Swiftish let MaxBuffers = 3 let ConstantBufferSize = 1024*1024 let vertexData:[Float] = [ -1.0, -1.0, 0.0, 1.0, -1.0, 1.0, 0.0, 1.0, 1.0, -1.0, 0.0, 1.0, 1.0, -1.0, 0.0, 1.0, -1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, -0.0, 0.25, 0.0, 1.0, -0.25, -0.25, 0.0, 1.0, 0.25, -0.25, 0.0, 1.0 ] let vertexColorData:[Float] = [ 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0 ] public final class OneTriangle : EngineListener { private let engine: Engine private let logger: Logger private var totalDuration = Duration.zero private var previousTime = Time.zero private var accumulatedTime = Duration.zero private let tickDuration = Duration(seconds: 1.0 / 60.0) private let maxFrameDuration = Duration(seconds: 0.25) private var commandQueue: CommandQueue private var pipeline: RenderPipelineStateHandle private var renderPass: RenderPassHandle private var framebuffer: Framebuffer private var vertexBuffer: GPUBufferHandle private var vertexColorBuffer: GPUBufferHandle private var bufferIndex: Int private var xOffset:[Float] = [ -1.0, 1.0, -1.0 ] private var yOffset:[Float] = [ 1.0, 0.0, -1.0 ] private var xDelta:[Float] = [ 0.002, -0.001, 0.003 ] private var yDelta:[Float] = [ 0.001, 0.002, -0.001 ] public init(engine: Engine, logger: Logger) { self.engine = engine self.logger = logger self.commandQueue = engine.makeCommandQueue() self.pipeline = RenderPipelineStateHandle() self.renderPass = RenderPassHandle() self.framebuffer = Framebuffer() self.vertexBuffer = GPUBufferHandle() self.vertexColorBuffer = GPUBufferHandle() self.bufferIndex = 0 } private func makePipeline() -> RenderPipelineStateHandle { do { let modulePath = engine.pathForResource(named: "default.metallib") logger.debug("\(modulePath)") let module = try engine.createModule(filepath: modulePath) defer { engine.destroyModule(handle: module) } precondition(module.isValid) let vertexShader = engine.createVertexFunction(module: module, named: "passThroughVertex") let fragmentShader = engine.createFragmentFunction(module: module, named: "passThroughFragment") defer { engine.destroyVertexFunction(handle: vertexShader) engine.destroyFragmentFunction(handle: fragmentShader) } precondition(vertexShader.isValid) precondition(fragmentShader.isValid) var descriptor = RenderPipelineDescriptor() descriptor.vertexShader = vertexShader descriptor.fragmentShader = fragmentShader descriptor.colorAttachments.append(RenderPipelineColorAttachmentDescriptor()) descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm descriptor.sampleCount = 4 return try engine.createRenderPipelineState(descriptor: descriptor) } catch { logger.debug("\(error)") fatalError() } } private func makeRenderPass() -> RenderPassHandle { var descriptor = RenderPassDescriptor() descriptor.colorAttachments.append(RenderPassColorAttachmentDescriptor()) descriptor.colorAttachments[0].resolve = true descriptor.colorAttachments[0].storeAction = .multisampleResolve return engine.createRenderPass(descriptor: descriptor) } private func makeFramebuffer() -> Framebuffer { var framebuffer = Framebuffer() framebuffer.colorAttachments.append(FramebufferAttachment()) framebuffer.colorAttachments[0].render = makeMultisampleTexture() return framebuffer } private func makeMultisampleTexture() -> TextureHandle { var descriptor = TextureDescriptor() descriptor.width = 640 descriptor.height = 360 descriptor.pixelFormat = .bgra8Unorm descriptor.textureType = .type2D descriptor.sampleCount = 4 descriptor.textureUsage = [.shaderRead, .shaderWrite, .renderTarget] descriptor.storageMode = .privateToGPU return engine.createTexture(descriptor: descriptor) } public func didStartup() { logger.debug("\(#function)") logger.debug("Screen Size: \(engine.screensSize)") pipeline = makePipeline() framebuffer = makeFramebuffer() renderPass = makeRenderPass() vertexBuffer = engine.createBuffer(count: ConstantBufferSize, storageMode: .sharedWithCPU) vertexColorBuffer = engine.createBuffer(bytes: vertexColorData, count: vertexData.count * MemoryLayout<Float>.size, storageMode: .sharedWithCPU) precondition(pipeline.isValid) precondition(framebuffer.colorAttachments[0].render.isValid) precondition(renderPass.isValid) precondition(vertexBuffer.isValid) precondition(vertexColorBuffer.isValid) } public func willShutdown() { logger.debug("\(#function)") do { try engine.writeConfig() } catch { logger.error("\(error)") } } public func willResizeScreen(size: Vector2<Int>) -> Vector2<Int> { logger.debug("\(#function) \(size)") return size } public func didResizeScreen() { logger.debug("\(#function)") } public func willMoveScreen() { logger.debug("\(#function)") } public func didMoveScreen() { logger.debug("\(#function)") } public func willEnterFullScreen() { logger.debug("\(#function)") } public func didEnterFullScreen() { logger.debug("\(#function)") } public func willExitFullScreen() { logger.debug("\(#function)") } public func didExitFullScreen() { logger.debug("\(#function)") } public func received(input: RawInput) { logger.debug("\(#function) \(input)") } public func screensChanged() { logger.debug("\(#function)") } public func processFrame() { logger.trace("\(#function)") engine.waitForGPUIfNeeded() let currentTime = engine.currentTime var frameDuration = currentTime - previousTime logger.trace("FRAME DURATION: \(frameDuration)") if frameDuration > maxFrameDuration { logger.debug("EXCEEDED FRAME DURATION") frameDuration = maxFrameDuration } accumulatedTime += frameDuration previousTime = currentTime while accumulatedTime >= tickDuration { accumulatedTime -= tickDuration totalDuration += tickDuration update(elapsed: tickDuration) } render() } private func update(elapsed: Duration) { logger.trace("\(#function)") let vertices = engine.borrowBuffer(handle: vertexBuffer) let pData = vertices.bytes let vData = (pData + 256 * bufferIndex).bindMemory(to:Float.self, capacity: 256 / MemoryLayout<Float>.stride) vData.initialize(from: vertexData) let lastTriVertex = 24 let vertexSize = 4 for j in 0..<3 { xOffset[j] += xDelta[j] if(xOffset[j] >= 1.0 || xOffset[j] <= -1.0) { xDelta[j] = -xDelta[j] xOffset[j] += xDelta[j] } yOffset[j] += yDelta[j] if(yOffset[j] >= 1.0 || yOffset[j] <= -1.0) { yDelta[j] = -yDelta[j] yOffset[j] += yDelta[j] } let pos = lastTriVertex + j*vertexSize vData[pos] = xOffset[j] vData[pos+1] = yOffset[j] } } private func render() { logger.trace("\(#function)") let commandBuffer = commandQueue.makeCommandBuffer() let renderTarget = engine.acquireNextRenderTarget() precondition(renderTarget.isValid) framebuffer.colorAttachments[0].resolve = engine.textureForRenderTarget(handle: renderTarget) precondition(framebuffer.colorAttachments[0].resolve.isValid) let renderEncoder = commandBuffer.makeRenderCommandEncoder(handle: renderPass, framebuffer: framebuffer) renderEncoder.setRenderPipelineState(pipeline) renderEncoder.setVertexBuffer(vertexBuffer, offset: 256 * bufferIndex, at: 0) renderEncoder.setVertexBuffer(vertexColorBuffer, offset: 0, at: 1) renderEncoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 9, instanceCount: 1) renderEncoder.endEncoding() engine.present(commandBuffer: commandBuffer, renderTarget: renderTarget) bufferIndex = (bufferIndex + 1) % MaxBuffers commandBuffer.commit() } }
mit
0f2b305521be3518230257d227bdc4fe
32.980769
152
0.611583
4.64389
false
false
false
false
hawkfalcon/SpaceEvaders
SpaceEvaders/MainMenuScene.swift
1
1207
import SpriteKit class MainMenuScene: SKScene { var viewController: GameViewController? override func didMove(to view: SKView) { backgroundColor = UIColor.black addChild(Utility.skyFullofStars(width: size.width, height: size.height)) PopupMenu(size: size, title: "Space Evaders", label: "Play", id: "start").addTo(parent: self) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { let touched = self.atPoint(touch.location(in: self)) guard let name = touched.name else { return; } switch name { case "start": let gameScene = GameScene(size: size) gameScene.scaleMode = scaleMode let reveal = SKTransition.doorsOpenVertical(withDuration: 0.5) gameScene.viewController = self.viewController view?.presentScene(gameScene, transition: reveal) case "leaderboard": viewController?.openGC() default: Utility.pressButton(main: self, touched: touched, score: "-1") } } } }
mit
578a2241ef52569b100470a2992d215f
36.71875
101
0.584921
4.828
false
false
false
false
carolight/RWThreeRingControl
Example/RWThreeRingControl-Example/RWThreeRingControl-Example/ViewController.swift
1
2238
import UIKit import CoreMotion import RWThreeRingControl private let oneCircleLength = 30.0 // 30s to fill a circle private let scanInterval = 0.5 // check each 1/2 second extension ThreeRingView { var move: CGFloat { get { return innerRingValue } set { innerRingValue = newValue } } var exercise: CGFloat { get { return middleRingValue } set { middleRingValue = newValue } } var stand: CGFloat { get { return outerRingValue } set { outerRingValue = newValue } } } class ViewController: UIViewController { @IBOutlet weak var ringControl: ThreeRingView! var shakeStart: Date? var manager = CMMotionManager() override func canBecomeFirstResponder() -> Bool { return true } override func viewDidLoad() { super.viewDidLoad() Fanfare.sharedInstance.playSoundsWhenReady() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) becomeFirstResponder() manager.deviceMotionUpdateInterval = scanInterval manager.startDeviceMotionUpdates(to: OperationQueue.main()) { motion, error in if let upright = motion?.attitude.pitch where upright > M_PI_2 * 0.75 { self.ringControl.stand += CGFloat(1.0 / (oneCircleLength / scanInterval)) } if let rotationRate = motion?.rotationRate { let x = abs(rotationRate.x), y = abs(rotationRate.y), z = abs(rotationRate.z) if x > 0.5 || y > 0.5 || z > 0.5 { self.ringControl.move += CGFloat(1.0 / (oneCircleLength / scanInterval)) } } } } override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) { if motion == .motionShake { shakeStart = Date() } } override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) { if motion == .motionShake { let shakeEnd = Date() #if (arch(i386) || arch(x86_64)) && os(iOS) //Test on the simulator with a simple gesture action let diff = 2.0 #else let diff = shakeEnd.timeIntervalSinceDate(shakeStart!) #endif shake(diff) } } func shake(_ forNSeconds: TimeInterval) { self.ringControl.exercise += CGFloat(forNSeconds / oneCircleLength) } }
mit
2abea21ef9099c38f09799eec81897c1
25.963855
85
0.652368
4.144444
false
false
false
false
akaralar/siesta
Source/Siesta/Support/ARC+Siesta.swift
3
2527
// // ARC+Siesta.swift // Siesta // // Created by Paul on 2015/7/18. // Copyright © 2016 Bust Out Solutions. All rights reserved. // import Foundation /** In Swift 3, “is AnyObject” always returns true due to implicit value wrapping. This tests whether the argument is really a subtype of AnyObject, restoring the behavior of “is AnyObject” in Swift 2. */ internal func isObject(_ val: Any) -> Bool { return type(of: val) is AnyObject.Type } /** A reference that can switched between behaving as a strong or a weak ref to an object, and can also hold a non-object type. - If the value is an object (i.e. T is a subtype of AnyObject), then... - ...if strong == true, then StrongOrWeakRef holds a strong reference to value. - ...if strong == false, then StrongOrWeakRef holds a weak reference to value. - If the value is not an object (e.g. a struct), then... - ...if strong == true, then StrongOrWeakRef holds the structure. - ...if strong == false, then StrongOrWeakRef immediately discards the structure. */ internal struct StrongOrWeakRef<T> { private var strongRef: T? private weak var weakRef: AnyObject? var value: T? { return strongRef ?? (weakRef as? T) } init(_ value: T) { strongRef = value weakRef = value as AnyObject // More performant version of previous line, once // https://bugs.swift.org/browse/SR-2867 is fixed: // weakRef = isObject(value) // ? value as AnyObject? // : nil } var strong: Bool { get { return strongRef != nil } set { strongRef = newValue ? value : nil } } } /** A weak ref suitable for use in collections. This struct maintains stable behavior for == and hashValue even after the referenced object has been deallocated, making it suitable for use as a Set member and a Dictionary key. */ internal struct WeakRef<T: AnyObject>: Hashable { private(set) weak var value: T? private let originalIdentity: UInt private let originalHash: Int init(_ value: T) { self.value = value let ident = ObjectIdentifier(value) self.originalIdentity = UInt(bitPattern: ident) self.originalHash = ident.hashValue } var hashValue: Int { return originalHash } internal static func == <T>(lhs: WeakRef<T>, rhs: WeakRef<T>) -> Bool { return lhs.originalIdentity == rhs.originalIdentity } }
mit
5c060360efce3efa07c02fb8277445ad
29.707317
116
0.638602
4.134647
false
false
false
false
LYM-mg/MGDS_Swift
MGDS_Swift/MGDS_Swift/Class/Discover/Controller/FindViewController.swift
1
5428
// // FindViewController.swift // MGDS_Swift // // Created by i-Techsys.com on 2017/7/5. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit private let KFindCellID = "KFindCellID" class FindViewController: UIViewController { // MARK: - 懒加载属性 fileprivate lazy var findHeaderView: LivekyCycleHeader = {[unowned self] in let hdcView = LivekyCycleHeader(frame: CGRect(x: 0, y: 0, width: MGScreenW, height: MGScreenW/2.5),type: .find) // 图片轮播器点击回调 hdcView.carouselsClickBlock = { [unowned self] (carouselModel) in if (carouselModel.linkUrl != nil) { let webViewVc = WebViewController(navigationTitle: carouselModel.name, urlStr: carouselModel.linkUrl) self.show(webViewVc, sender: nil) } } return hdcView }() fileprivate lazy var tableView: UITableView = { [unowned self] in let tb = UITableView(frame: .zero, style: .plain) tb.backgroundColor = UIColor.white tb.autoresizingMask = [.flexibleWidth, .flexibleHeight] tb.dataSource = self tb.delegate = self // tb.estimatedRowHeight = 60 // 设置估算高度 // tb.rowHeight = UITableView.automaticDimension // 告诉tableView我们cell的高度是自动的 tb.register(FindCell.self, forCellReuseIdentifier: KFindCellID) return tb }() fileprivate lazy var findVM: FindViewModel = FindViewModel() override func viewDidLoad() { super.viewDidLoad() setUpMainView() loadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: - setUpMainView extension FindViewController { fileprivate func setUpMainView() { view.addSubview(tableView) tableView.tableHeaderView = findHeaderView setupFooterView() tableView.snp.makeConstraints { (make) in make.top.bottom.left.right.equalToSuperview() } self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "惊喜", style: .plain, target: self, action: #selector(rightClick)) } fileprivate func setupFooterView() { let footerView = UIView(frame: CGRect(x: 0, y: 0, width: MGScreenW, height: 80)) let btn = UIButton(frame: CGRect.zero) btn.frame.size = CGSize(width: MGScreenW * 0.5, height: 40) btn.center = CGPoint(x: MGScreenW * 0.5, y: 40) btn.setTitle("换一换", for: .normal) btn.setTitleColor(UIColor.black, for: .normal) btn.setTitleColor(UIColor.lightGray, for: .highlighted) btn.titleLabel?.font = UIFont.systemFont(ofSize: 16.0) btn.layer.cornerRadius = 5 btn.layer.borderColor = UIColor.orange.cgColor btn.layer.borderWidth = 0.5 btn.addTarget(self, action: #selector(changeAnchor), for: .touchUpInside) footerView.addSubview(btn) footerView.backgroundColor = UIColor(r: 250, g: 250, b: 250) tableView.tableFooterView = footerView } fileprivate func setupSectionHeaderView() -> UIView { let headerView = UIView(frame: CGRect(x: 0, y: 0, width: MGScreenW, height: 40)) let headerLabel = UILabel(frame: CGRect(x: 0, y: 0, width: MGScreenW, height: 40)) headerLabel.textAlignment = .center headerLabel.text = "猜你喜欢" headerLabel.textColor = UIColor.orange headerView.addSubview(headerLabel) headerView.backgroundColor = UIColor.white return headerView } @objc fileprivate func rightClick() { let discoverVC = DiscoverViewController() self.show(discoverVC, sender: nil) } @objc fileprivate func changeAnchor() { MGNotificationCenter.post(name: NSNotification.Name(KChangeanchorNotification), object: nil, userInfo: nil) } } // MARK: - 加载数据 extension FindViewController { func loadData() { findVM.loadContentData { (err) in if err == nil { self.tableView.reloadData() }else { self.showHint(hint: "网络请求失败\(err)") } } } } // MARK: - UITableViewDataSource,UITableViewDelegate extension FindViewController: UITableViewDataSource,UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return findVM.anchorModels.count > 0 ? 1:0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: KFindCellID, for: indexPath) as? FindCell cell?.anchorData = findVM.anchorModels cell?.cellDidSelected = { (anchor) in let liveVc = RoomViewController(anchor:anchor) self.navigationController?.pushViewController(liveVc, animated: true) } return cell! } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return setupSectionHeaderView() } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 35 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 200*3 } }
mit
f7dcdb07430f70dfa1aea78bd370dc4c
34.5
142
0.644883
4.535775
false
false
false
false
natan/ReactiveCocoa
ReactiveCocoaTests/Swift/PropertySpec.swift
113
11777
// // PropertySpec.swift // ReactiveCocoa // // Created by Justin Spahr-Summers on 2015-01-23. // Copyright (c) 2015 GitHub. All rights reserved. // import Result import Nimble import Quick import ReactiveCocoa private let initialPropertyValue = "InitialValue" private let subsequentPropertyValue = "SubsequentValue" class PropertySpec: QuickSpec { override func spec() { describe("ConstantProperty") { it("should have the value given at initialization") { let constantProperty = ConstantProperty(initialPropertyValue) expect(constantProperty.value).to(equal(initialPropertyValue)) } it("should yield a producer that sends the current value then completes") { let constantProperty = ConstantProperty(initialPropertyValue) var sentValue: String? var signalCompleted = false constantProperty.producer.start(next: { value in sentValue = value }, completed: { signalCompleted = true }) expect(sentValue).to(equal(initialPropertyValue)) expect(signalCompleted).to(beTruthy()) } } describe("MutableProperty") { it("should have the value given at initialization") { let mutableProperty = MutableProperty(initialPropertyValue) expect(mutableProperty.value).to(equal(initialPropertyValue)) } it("should yield a producer that sends the current value then all changes") { let mutableProperty = MutableProperty(initialPropertyValue) var sentValue: String? mutableProperty.producer.start(next: { value in sentValue = value }) expect(sentValue).to(equal(initialPropertyValue)) mutableProperty.value = subsequentPropertyValue expect(sentValue).to(equal(subsequentPropertyValue)) } it("should complete its producer when deallocated") { var mutableProperty: MutableProperty? = MutableProperty(initialPropertyValue) var signalCompleted = false mutableProperty?.producer.start(completed: { signalCompleted = true }) mutableProperty = nil expect(signalCompleted).to(beTruthy()) } it("should not deadlock on recursive value access") { let (producer, sink) = SignalProducer<Int, NoError>.buffer() let property = MutableProperty(0) var value: Int? property <~ producer property.producer.start(next: { _ in value = property.value }) sendNext(sink, 10) expect(value).to(equal(10)) } it("should not deadlock on recursive observation") { let property = MutableProperty(0) var value: Int? property.producer.start(next: { _ in property.producer.start(next: { x in value = x }) }) expect(value).to(equal(0)) property.value = 1 expect(value).to(equal(1)) } } describe("PropertyOf") { describe("from a PropertyType") { it("should pass through behaviors of the input property") { let constantProperty = ConstantProperty(initialPropertyValue) let propertyOf = PropertyOf(constantProperty) var sentValue: String? var producerCompleted = false propertyOf.producer.start(next: { value in sentValue = value }, completed: { producerCompleted = true }) expect(sentValue).to(equal(initialPropertyValue)) expect(producerCompleted).to(beTruthy()) } } describe("from a value and SignalProducer") { it("should initially take on the supplied value") { let property = PropertyOf( initialValue: initialPropertyValue, producer: SignalProducer.never) expect(property.value).to(equal(initialPropertyValue)) } it("should take on each value sent on the producer") { let property = PropertyOf( initialValue: initialPropertyValue, producer: SignalProducer(value: subsequentPropertyValue)) expect(property.value).to(equal(subsequentPropertyValue)) } } describe("from a value and Signal") { it("should initially take on the supplied value, then values sent on the signal") { let (signal, observer) = Signal<String, NoError>.pipe() let property = PropertyOf( initialValue: initialPropertyValue, signal: signal) expect(property.value).to(equal(initialPropertyValue)) sendNext(observer, subsequentPropertyValue) expect(property.value).to(equal(subsequentPropertyValue)) } } } describe("DynamicProperty") { var object: ObservableObject! var property: DynamicProperty! let propertyValue: () -> Int? = { if let value: AnyObject = property?.value { return value as? Int } else { return nil } } beforeEach { object = ObservableObject() expect(object.rac_value).to(equal(0)) property = DynamicProperty(object: object, keyPath: "rac_value") } afterEach { object = nil } it("should read the underlying object") { expect(propertyValue()).to(equal(0)) object.rac_value = 1 expect(propertyValue()).to(equal(1)) } it("should write the underlying object") { property.value = 1 expect(object.rac_value).to(equal(1)) expect(propertyValue()).to(equal(1)) } it("should observe changes to the property and underlying object") { var values: [Int] = [] property.producer.start(next: { value in expect(value).notTo(beNil()) values.append((value as? Int) ?? -1) }) expect(values).to(equal([ 0 ])) property.value = 1 expect(values).to(equal([ 0, 1 ])) object.rac_value = 2 expect(values).to(equal([ 0, 1, 2 ])) } it("should complete when the underlying object deallocates") { var completed = false property = { // Use a closure so this object has a shorter lifetime. let object = ObservableObject() let property = DynamicProperty(object: object, keyPath: "rac_value") property.producer.start(completed: { completed = true }) expect(completed).to(beFalsy()) expect(property.value).notTo(beNil()) return property }() expect(completed).toEventually(beTruthy()) expect(property.value).to(beNil()) } it("should retain property while DynamicProperty's object is retained"){ weak var dynamicProperty: DynamicProperty? = property property = nil expect(dynamicProperty).toNot(beNil()) object = nil expect(dynamicProperty).to(beNil()) } } describe("binding") { describe("from a Signal") { it("should update the property with values sent from the signal") { let (signal, observer) = Signal<String, NoError>.pipe() let mutableProperty = MutableProperty(initialPropertyValue) mutableProperty <~ signal // Verify that the binding hasn't changed the property value: expect(mutableProperty.value).to(equal(initialPropertyValue)) sendNext(observer, subsequentPropertyValue) expect(mutableProperty.value).to(equal(subsequentPropertyValue)) } it("should tear down the binding when disposed") { let (signal, observer) = Signal<String, NoError>.pipe() let mutableProperty = MutableProperty(initialPropertyValue) let bindingDisposable = mutableProperty <~ signal bindingDisposable.dispose() sendNext(observer, subsequentPropertyValue) expect(mutableProperty.value).to(equal(initialPropertyValue)) } it("should tear down the binding when bound signal is completed") { let (signal, observer) = Signal<String, NoError>.pipe() let mutableProperty = MutableProperty(initialPropertyValue) let bindingDisposable = mutableProperty <~ signal expect(bindingDisposable.disposed).to(beFalsy()) sendCompleted(observer) expect(bindingDisposable.disposed).to(beTruthy()) } it("should tear down the binding when the property deallocates") { let (signal, observer) = Signal<String, NoError>.pipe() var mutableProperty: MutableProperty<String>? = MutableProperty(initialPropertyValue) let bindingDisposable = mutableProperty! <~ signal mutableProperty = nil expect(bindingDisposable.disposed).to(beTruthy()) } } describe("from a SignalProducer") { it("should start a signal and update the property with its values") { let signalValues = [initialPropertyValue, subsequentPropertyValue] let signalProducer = SignalProducer<String, NoError>(values: signalValues) let mutableProperty = MutableProperty(initialPropertyValue) mutableProperty <~ signalProducer expect(mutableProperty.value).to(equal(signalValues.last!)) } it("should tear down the binding when disposed") { let signalValues = [initialPropertyValue, subsequentPropertyValue] let signalProducer = SignalProducer<String, NoError>(values: signalValues) let mutableProperty = MutableProperty(initialPropertyValue) let disposable = mutableProperty <~ signalProducer disposable.dispose() // TODO: Assert binding was torn down? } it("should tear down the binding when bound signal is completed") { let signalValues = [initialPropertyValue, subsequentPropertyValue] let (signalProducer, observer) = SignalProducer<String, NoError>.buffer(1) let mutableProperty = MutableProperty(initialPropertyValue) mutableProperty <~ signalProducer sendCompleted(observer) // TODO: Assert binding was torn down? } it("should tear down the binding when the property deallocates") { let signalValues = [initialPropertyValue, subsequentPropertyValue] let signalProducer = SignalProducer<String, NoError>(values: signalValues) var mutableProperty: MutableProperty<String>? = MutableProperty(initialPropertyValue) let disposable = mutableProperty! <~ signalProducer mutableProperty = nil expect(disposable.disposed).to(beTruthy()) } } describe("from another property") { it("should take the source property's current value") { let sourceProperty = ConstantProperty(initialPropertyValue) let destinationProperty = MutableProperty("") destinationProperty <~ sourceProperty.producer expect(destinationProperty.value).to(equal(initialPropertyValue)) } it("should update with changes to the source property's value") { let sourceProperty = MutableProperty(initialPropertyValue) let destinationProperty = MutableProperty("") destinationProperty <~ sourceProperty.producer sourceProperty.value = subsequentPropertyValue expect(destinationProperty.value).to(equal(subsequentPropertyValue)) } it("should tear down the binding when disposed") { let sourceProperty = MutableProperty(initialPropertyValue) let destinationProperty = MutableProperty("") let bindingDisposable = destinationProperty <~ sourceProperty.producer bindingDisposable.dispose() sourceProperty.value = subsequentPropertyValue expect(destinationProperty.value).to(equal(initialPropertyValue)) } it("should tear down the binding when the source property deallocates") { var sourceProperty: MutableProperty<String>? = MutableProperty(initialPropertyValue) let destinationProperty = MutableProperty("") destinationProperty <~ sourceProperty!.producer sourceProperty = nil // TODO: Assert binding was torn down? } it("should tear down the binding when the destination property deallocates") { let sourceProperty = MutableProperty(initialPropertyValue) var destinationProperty: MutableProperty<String>? = MutableProperty("") let bindingDisposable = destinationProperty! <~ sourceProperty.producer destinationProperty = nil expect(bindingDisposable.disposed).to(beTruthy()) } } } } } private class ObservableObject: NSObject { dynamic var rac_value: Int = 0 }
mit
7ebfb184fabba6986491dde6b3873068
28.15099
90
0.699669
4.353789
false
false
false
false
roshkadev/rHybrid-iOS
RHYWebViewController.swift
1
35630
// // RHYWebViewController.swift // rHybridDemo // // Created by Paul Von Schrottky on 7/10/15. // Copyright (c) 2015 Roshka. All rights reserved. // import UIKit import WebKit import Foundation typealias OnLoadListener = (webView: UIWebView) -> Void class RHYWebViewController: UIViewController, UIWebViewDelegate { var menuContainerViewController: RSKMenuContainerViewController! var activityIndictator: MBProgressHUD! var menuOverhang = 0 var menuOverhangConstraint: NSLayoutConstraint? var HTMLFile: String! var uiWebView: UIWebView! var javaScripts: NSMutableArray! let statusBarView = UIView() var onLoadListeners = [OnLoadListener]() var uiWebViewNavigationBarConstraint : NSLayoutConstraint! var uiWebViewStatusBarConstraint : NSLayoutConstraint! var showNavigationBar: Bool = false var form: NSData? override func viewDidLoad() { super.viewDidLoad() print(self) // We set this to 'false' so that the contents of the web view uses the full height // of the web view. self.automaticallyAdjustsScrollViewInsets = false; // Set the default status bar text color (remember to set 'View controller-based status bar' to 'NO' in the target's plist). UIApplication.sharedApplication().setStatusBarStyle(.Default, animated:false) // Hide the navigation bar (we have our own navigation bar in HTML). self.navigationController?.setNavigationBarHidden(true, animated: false) // Make the array of javascripts to inject into every page. let bundle = NSBundle.mainBundle() javaScripts = NSMutableArray() for jsFile in ["rhy", "rhy-ios", "rsk-utils"] { var path = NSBundle.mainBundle().bundlePath path = path.stringByAppendingString("/\(jsFile).js") let javaScript = try! String(contentsOfURL: NSURL(fileURLWithPath: path), encoding: NSUTF8StringEncoding) javaScripts.addObject(javaScript) } // Make a web view and add it to the screen. self.uiWebView = UIWebView() // Set the web view to use the full width except if this screen is the menu screen, which has a right margin. // Also, full height (except for the status bar margin). self.uiWebView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.uiWebView) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: .Left, relatedBy: .Equal, toItem: self.uiWebView, attribute: .Left, multiplier: 1, constant: 0)) self.menuOverhangConstraint = NSLayoutConstraint(item: self.uiWebView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0) self.view.addConstraint(self.menuOverhangConstraint!) self.statusBarView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.statusBarView) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[statusBarView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["statusBarView": self.statusBarView])) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat( "V:|[statusBarView(20)][uiWebView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["uiWebView": self.uiWebView, "statusBarView": self.statusBarView])) // This allows the keyboard to be shown programatically using the 'autofocus' HTML input tag attribute. self.uiWebView.keyboardDisplayRequiresUserAction = false // Assign its delegate to us so we can catch events. self.uiWebView.delegate = self // Do not display vertical scroll bars. self.uiWebView.scrollView.showsVerticalScrollIndicator = false; // Remove bounces from the web view. self.uiWebView.scrollView.bounces = false; // Disable blue highlighting of phone numbers, etc. by the web view. self.uiWebView.dataDetectorTypes = UIDataDetectorTypes.None // If this screen was passed a HTML page, open it. If not, open the default screen. if (HTMLFile == nil) { loadWebViewWithHTMLFile(self.uiWebView, file: "index.html") } else { loadWebViewWithHTMLFile(self.uiWebView, file: HTMLFile) } // self.uiWebViewNavigationBarConstraint = NSLayoutConstraint(item: self.uiWebView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 64) self.uiWebViewStatusBarConstraint = NSLayoutConstraint(item: self.uiWebView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 20) // if(self.showNavigationBar) { // self.view.addConstraint(self.uiWebViewNavigationBarConstraint) // self.navigationController?.setNavigationBarHidden(false, animated: true) // } else { // self.view.addConstraint(self.uiWebViewStatusBarConstraint) // self.navigationController?.setNavigationBarHidden(true, animated: true) // } self.view.layoutIfNeeded() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // if(self.showNavigationBar) { // self.view.addConstraint(self.uiWebViewNavigationBarConstraint) // self.navigationController?.setNavigationBarHidden(false, animated: false) // } else { // self.view.addConstraint(self.uiWebViewStatusBarConstraint) // self.navigationController?.setNavigationBarHidden(true, animated: false) // } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // When a screen is popped, we want to set the UIStatusBar color so that it matches the previous screen. // Note that this method, viewWillDisappear, is called on the screen being popped. // isMovingFromParentViewController returns true on the screen being popped, and topViewController already // is the previous screen. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) uiWebView.stringByEvaluatingJavaScriptFromString("Rhy.iOS.setStatusBarColor()") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /** Load the given file in the given web view. @param webView the web view to load the file into @param file the file to load into the web view */ func loadWebViewWithHTMLFile(webView:UIWebView, file:String) { let baseURL = NSURL.fileURLWithPath(NSBundle.mainBundle().bundlePath); let relativePath = "www/\(file)" let fileURL = NSURL(string: relativePath, relativeToURL: baseURL); let URLRequest = NSURLRequest(URL: fileURL!); webView.loadRequest(URLRequest) } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { // If the request uses our URL Scheme, this call corresponds to us. if request.URL!.scheme == "rhybrid" { // Get the parameters passes as query parameters from the URL. var query = request.URL!.query!.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! // var optionsJSON = query.componentsSeparatedByString("=")[1] // let params = RHYUtils.objectForJSONString(JSONString: optionsJSON) as! NSDictionary let params = RHYUtils.dictionaryFromQueryParams(query) print("params of\(self.HTMLFile): \(params)") if let keys = params["getValuesForKeys"] as? NSArray { var response = NSMutableDictionary() let timestamp = RHYUtils.rfc822DateAsEscapedString() let mobileID = UIDevice.currentDevice().identifierForVendor!.UUIDString let clientSecret = "" for key in keys { if key as! NSString == "MOBILE_ID" { response[key as! NSString] = mobileID } if key as! NSString == "TIMESTAMP" { response[key as! NSString] = RHYUtils.rfc822DateAsEscapedString() } } // Return the JavaScript {object} whose values are the requested parameters. if let JSONResponse = response.JSONString_rsk() { webView.stringByEvaluatingJavaScriptFromString("Rhy.iOS.response = JSON.parse('\(JSONResponse)')") } } if params["setiOSStatusBarColor"] != nil { // Add UIViewControllerBasedStatusBarAppearance YES to Info.plist let red = params["setiOSStatusBarColor"]?.floatValue let redValue:CGFloat = CGFloat(red!) / 255.0 let green = params["green"]?.floatValue let greenValue:CGFloat = CGFloat(green!) / 255.0 let blue = params["blue"]?.floatValue let blueValue:CGFloat = CGFloat(blue!) / 255.0 var averageColor = (redValue + greenValue + blueValue) / 3.0; // Set the status bar text color (either light or dark). if averageColor > 0.6 { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: false); } else { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: false); } // Set the status bar background. let color = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0) self.statusBarView.backgroundColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0) } if let URLScheme = params["showActivityIndicator"] as? String { if let menuContainerVC = self.menuContainerViewController { menuContainerVC.enabled = false } self.activityIndictator = MBProgressHUD(view:self.view) self.activityIndictator.animationType = MBProgressHUDAnimationFade self.activityIndictator.labelText = "Loading..." self.activityIndictator.detailsLabelText = "please wait..." if let title = params["title"] as? String { self.activityIndictator.labelText = title; } if let message = params["message"] as? String { self.activityIndictator.detailsLabelText = message; } self.view.addSubview(self.activityIndictator) self.activityIndictator.show(true) } if let URLScheme = params["hideActivityIndicator"] as? String { if let menuContainerVC = self.menuContainerViewController { menuContainerVC.enabled = true } self.activityIndictator.hide(true) } if let newScreen = params["newScreen"] as? String { if newScreen.containsString(".html") { let nextScreen = self.storyboard!.instantiateViewControllerWithIdentifier("RHYWebViewControllerStoryboardID") as! RHYWebViewController // let showStatusBar = params["showNavigationBar"] as? String nextScreen.HTMLFile = newScreen nextScreen.menuContainerViewController = self.menuContainerViewController // if(showStatusBar == "true") { // nextScreen.showNavigationBar = true; //// self.navigationController?.setNavigationBarHidden(false, animated: true) //// nextScreen.view.addConstraint(self.uiWebViewNavigationBarConstraint) // } else { // nextScreen.showNavigationBar = false; //// self.navigationController?.setNavigationBarHidden(true, animated: true) //// nextScreen.view.addConstraint(self.uiWebViewStatusBarConstraint) // } self.navigationController?.pushViewController(nextScreen, animated: true) } else { var nextScreen = self.storyboard!.instantiateViewControllerWithIdentifier(newScreen) // self.navigationController?.pushViewController(nextScreen, animated: true) self.navigationController?.pushViewController(nextScreen, animated: true) } } if params["popScreen"] != nil { let screens = params["popScreen"]?.integerValue let totalScreens = self.navigationController?.viewControllers.count let destinationViewControllerIndex = totalScreens! - screens! - 1 // Offset 0 indexing. let destinationViewController = self.navigationController?.viewControllers[destinationViewControllerIndex] as! RHYWebViewController self.navigationController?.popToViewController(destinationViewController, animated: true) if let callback = params["callback"] as? String { destinationViewController.uiWebView.stringByEvaluatingJavaScriptFromString("\(callback)()") } } if let menuHTMLFile = params["createMenu"] as? String { // We make a new screen for the menu HTML page. let menuViewController = RHYWebViewController() menuViewController.HTMLFile = menuHTMLFile let overhang = params["menuMargin"] as! Int menuViewController.view.frame = CGRectMake(0, 0, menuViewController.view.frame.size.width - CGFloat(overhang), menuViewController.view.frame.size.height) // menuViewController.addOnLoadListener({(webView: UIWebView) in // let newWidth = webView.frame.size.width - CGFloat(overhang) // let javaScript = "document.querySelector('meta[name=viewport]').setAttribute('content', 'width=\(newWidth);', false);" // webView.stringByEvaluatingJavaScriptFromString(javaScript) // }) // We make a new screen for the center HTML page (and wrap it in a navigation controller). let centerViewController = RHYWebViewController() centerViewController.HTMLFile = params["openFileName"] as! String // Make the menu container. var a = UIViewController() a.view.backgroundColor = UIColor.redColor() a.navigationController?.setNavigationBarHidden(true, animated: false) a.automaticallyAdjustsScrollViewInsets = false; self.menuContainerViewController = RSKMenuContainerViewController(leftViewController: menuViewController, mainViewController: centerViewController, overhang: overhang) // Setting this is important to fix the status bar for the menu. self.menuContainerViewController.automaticallyAdjustsScrollViewInsets = false // Each of the screens (menu and center) needs a reference to the menu container. menuViewController.menuContainerViewController = self.menuContainerViewController centerViewController.menuContainerViewController = self.menuContainerViewController // Show the menu container and its contents. self.navigationController?.pushViewController(self.menuContainerViewController, animated: true) } if let menuOverhang = params["menuOverhang"] as? Int { // We reduce the menu screen web view's width by the menu overhang. var menuVC = self.menuContainerViewController.menuViewController as! RHYWebViewController menuVC.view.removeConstraint(menuVC.menuOverhangConstraint!) menuVC.menuOverhangConstraint = NSLayoutConstraint(item: menuVC.uiWebView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: menuVC.view, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: -CGFloat(menuOverhang)) menuVC.view.addConstraint(menuVC.menuOverhangConstraint!) // Update the menu screen web view content's width to its new width. var javaScript = "document.querySelector('meta[name=viewport]').setAttribute('content', 'width=\(menuVC.uiWebView.frame.size.width - CGFloat(menuOverhang));', false);" menuVC.uiWebView.stringByEvaluatingJavaScriptFromString(javaScript) // Update the menu container's menu overhang to refect the change. self.menuContainerViewController.openMargin = menuOverhang } if let key = params["updateAppConfigKey"] as? String { // Update the app config with the given key and value. let appConfig = NSUserDefaults.standardUserDefaults().objectForKey(RHY_CONFIG_KEY) as! NSDictionary let appConfigMutable = appConfig.mutableCopy() as! NSMutableDictionary appConfigMutable.setValue(params[key], forKey: key) NSUserDefaults.standardUserDefaults().setObject(appConfigMutable, forKey: "RSK_APP_CONFIG") } if params["toggleMenu"] != nil { self.menuContainerViewController?.toggleMenu(true) } if let fileName = params["openMenuOption"] as? String { // Get the navigation controller of the right stack of screens. var rightNavigationController = self.menuContainerViewController.menuViewController as! UINavigationController // Get the view controller that is currently showing from the right stack of screens. var rightViewController = rightNavigationController.viewControllers.last! // If the selected option is already open, don't do anything. let isHTMLScreen = fileName.hasSuffix(".html") let isHTMLScreenAlreadyOpen = rightViewController is RHYWebViewController && (rightViewController as! RHYWebViewController).HTMLFile == fileName let isNativeScreenAlreadyOpen = !(rightViewController is RHYWebViewController) let isNativeScreenClassAlreadyOpen = rightViewController.dynamicType.description().hasSuffix(fileName) if isHTMLScreen && (!isHTMLScreenAlreadyOpen || isNativeScreenAlreadyOpen) { // Open the option's screen. var nextScreen = RHYWebViewController() nextScreen.HTMLFile = fileName nextScreen.menuContainerViewController = self.menuContainerViewController rightNavigationController.viewControllers = [nextScreen] } else if !isNativeScreenClassAlreadyOpen { // Open the option's screen. First get the view controller that corresponds to the // given file, instantiate it, and open it. var appName: String = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as! String appName = appName.stringByReplacingOccurrencesOfString("-", withString: "_") var anyobjectype : AnyObject.Type = NSClassFromString("\(appName).\(fileName)")! var nsobjectype : NSObject.Type = anyobjectype as! NSObject.Type var nextScreen: RHYViewController = nsobjectype.init() as! RHYViewController nextScreen.menuContainerViewController = self.menuContainerViewController rightNavigationController.viewControllers = [nextScreen] } // Close the menu. self.menuContainerViewController.closeMenu(true) } if let number = params["callPhone"] as? String { var URLScheme = "tel" if params["showPrompt"] != nil { URLScheme = "telprompt" } let telefoneURL = NSURL(string: "\(URLScheme)://\(number)") if UIApplication.sharedApplication().canOpenURL(telefoneURL!) { UIApplication.sharedApplication().openURL(telefoneURL!) } else { // If we don't execute the UIAlertView through the GCD dispatch main queue, // the DOM element in the web view below the UIAlertView receives an extra // touchstart JavaScript event (for some buggy reason), which can be // problematic. // Adding the UIAlertView back onto the main queue via dispatch_async guarantees // that it the alert view will be executed after the current method finishes. // See: http://www.raywenderlich.com/79149/grand-central-dispatch-tutorial-swift-part-1 dispatch_async(dispatch_get_main_queue()) { UIAlertView(title: params["title"] as! String?, message: params["message"] as! String?, delegate: nil, cancelButtonTitle: params["okButtonTitle"] as! String?).show() } } } if let URLString = params["openInBrowser"] as? String { let URL = NSURL(string: URLString) UIApplication.sharedApplication().openURL(URL!) } if params["isAppInstalled"] != nil { let options = params["IOS"] as! NSDictionary let URLScheme = options["URLScheme"] as! NSString let application = UIApplication.sharedApplication() let URLSchemeString = options["URLScheme"] as! NSString let URLString = "\(URLSchemeString)://" let URL = NSURL(string: URLString) var response: NSString; if application.canOpenURL(URL!) { response = "true" } else { response = "false" } webView.stringByEvaluatingJavaScriptFromString("Rhy.iOS.response = \(response)") } if params["openApp"] != nil { let options = params["IOS"] as! NSDictionary let appID = options["appID"] as! NSString let URLScheme = options["URLScheme"] as! NSString let application = UIApplication.sharedApplication() let URLString = "\(URLScheme)://" var URL = NSURL(string: URLString) // If the app is not installed, change to the app's App Store URL. if application.canOpenURL(URL!) == false { URL = NSURL(string: "itms://itunes.apple.com/app/id\(appID)") } // Open the URL. application.openURL(URL!) } if params["formFactor"] != nil { var formFactor: NSString // Note that this is better than using userInterfaceIdiom because this method will // still return iPad even for iPhone apps running on iPads. if (UIDevice.currentDevice().model.hasPrefix("iPad")) { formFactor = "TABLET" } else { formFactor = "SMARTPHONE" } webView.stringByEvaluatingJavaScriptFromString("Rhy.iOS.response = \"'\(formFactor)'\"") } if let key = params["getValueForKey"] as? String { var value = RHYValueForKey.getValueForKey(key) as String! // print(value!) if(value == nil) { value = "null" } var json = (try? String(data: NSJSONSerialization.dataWithJSONObject([value], options: NSJSONWritingOptions(rawValue: 0)), encoding: NSUTF8StringEncoding)!)! json = json.substringWithRange(Range<String.Index>(start: json.startIndex.advancedBy(2), end: json.endIndex.advancedBy(-2))) webView.stringByEvaluatingJavaScriptFromString("Rhy.iOS.response = '\(json)'") } if let key = params["setValueForKey"] as? String { RHYValueForKey.setValueForKey(key, value: params["value"]!) // print(value!) // webView.stringByEvaluatingJavaScriptFromString("Rhy.iOS.response = '\(value!)'") } if params["showNavigationBar"] != nil { let enabled = params["showNavigationBar"] as! String! if(enabled == "true") { self.navigationController!.setNavigationBarHidden(false, animated: false) self.uiWebView.removeConstraint(self.uiWebViewStatusBarConstraint) // self.uiWebView.addConstraint(self.uiWebViewNavigationBarConstraint) } else { if let navigationController = self.navigationController { navigationController.setNavigationBarHidden(true, animated: false) self.uiWebView.removeConstraint(self.uiWebViewNavigationBarConstraint) self.uiWebView.addConstraint(self.uiWebViewStatusBarConstraint) } } } /** * PAGO DE SERVICIOS. (Sólo para EFICASH) Al final no se usa, eliminar al terminar. */ if params["pay_form"] != nil { let nextScreen = RHYWebViewController() let showStatusBar = params["showNavigationBar"] as? String nextScreen.HTMLFile = "pago_servicios.html" if(showStatusBar == "true") { nextScreen.showNavigationBar = true; // self.navigationController?.setNavigationBarHidden(false, animated: true) // nextScreen.view.addConstraint(self.uiWebViewNavigationBarConstraint) } else { nextScreen.showNavigationBar = false; // self.navigationController?.setNavigationBarHidden(true, animated: true) // nextScreen.view.addConstraint(self.uiWebViewStatusBarConstraint) } self.navigationController?.pushViewController(nextScreen, animated: true) } if params["showAlert"] != nil { let message = params["showAlert"] as! String; var title : String? = params["title"] as? String var buttonText : String? = params["button_text"] as? String if(title == nil) { title = "Mensaje"; } if(buttonText == nil) { buttonText = "Aceptar"; } let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: buttonText, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in if(params["callback"] != nil) { let callback = params["callback"] as! String self.uiWebView.stringByEvaluatingJavaScriptFromString("\(callback)()") } })); self.presentViewController(alert, animated: true, completion: nil) } if params["logout"] != nil { let indexViewController = self.storyboard!.instantiateViewControllerWithIdentifier("RHYWebViewControllerStoryboardID") as! RHYWebViewController let loginViewController = self.storyboard!.instantiateViewControllerWithIdentifier("RHYWebViewControllerStoryboardID") as! RHYWebViewController indexViewController.HTMLFile = "index.html" loginViewController.HTMLFile = "login.html" navigationController!.setViewControllers([indexViewController, loginViewController], animated: true) } if params["showConfirmDialog"] != nil { let message = params["showConfirmDialog"] as! String; var title = "Mensaje" var buttonOk = "Aceptar" var buttonCancel = "Cancelar" if let passedTitle = params["title"] as? String { title = passedTitle } if let passedButtonOk = params["buttonOk"] as? String { buttonOk = passedButtonOk } if let passedButtonCancel = params["buttonCancel"] as? String { buttonCancel = passedButtonCancel } let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: buttonOk, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in if(params["callback"] != nil) { let callback = params["callback"] as! String self.uiWebView.stringByEvaluatingJavaScriptFromString("\(callback)()") } })); alert.addAction(UIAlertAction(title: buttonCancel, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in debugPrint("cancelado") })); self.presentViewController(alert, animated: true, completion: nil) } // We handled JavaScript communication, so there is no page to be loaded. return false } // There was no JavaScript communication to handle, so go ahead and load the page. return true } func renderFormData(data: NSData) -> Void { let string = NSString(data: data, encoding: NSUTF8StringEncoding)! as String var json = (try? String(data: NSJSONSerialization.dataWithJSONObject([string], options: NSJSONWritingOptions(rawValue: 0)), encoding: NSUTF8StringEncoding)!)! json = json.substringWithRange(Range<String.Index>(start: json.startIndex.advancedBy(2), end: json.endIndex.advancedBy(-2))) self.uiWebView.stringByEvaluatingJavaScriptFromString("renderForm(\"\(json)\")") } func webViewDidStartLoad(webView: UIWebView) { // Inject the JavaScript files into the web view. for jsFileString in javaScripts { webView.stringByEvaluatingJavaScriptFromString(jsFileString as! String) } // Inject the global app config into this web page. injectAppConfigInWebView(webView) } func webViewDidFinishLoad(webView: UIWebView) { // Set the iOS status bar color. // We must not allow a previous screen to trigger this if a new screen has been loaded, // because otherwise we get a previous screen setting the status bar color for a later screen, which // results in the wrong status bar color. // window indicates whether the web view is currently visible. if (webView.window != nil) { webView.stringByEvaluatingJavaScriptFromString("Rhy.iOS.setStatusBarColor()") } for onLoadListener in self.onLoadListeners { onLoadListener(webView: webView) } if(self.form != nil) { self.renderFormData(self.form!) } } func injectAppConfigInWebView(webView: UIWebView) { // Inject the app's current configuration into the web view. // This is set by RSKConfig's setupAppConfig method in the AppDelegate. Note that this configuration is // mutable. It can be changed by calls to setAppConfigKey. if let appConfig = NSUserDefaults.standardUserDefaults().objectForKey(RHY_CONFIG_KEY) as? NSDictionary { let appConfigJSON = RHYUtils.JSONStringFromObject(dictionary: appConfig)! self.uiWebView.stringByEvaluatingJavaScriptFromString("Rhy.Config = JSON.parse('\(appConfigJSON)');"); } } func addOnLoadListener(onLoadListener: OnLoadListener) { self.onLoadListeners.append(onLoadListener) } // class Test {var xyz = 0} // func initScreenFromViewControllerString(className: String) -> UIViewController { // var target = NSBundle.mainBundle().objectForInfoDictionaryKey("RSKTargetName") as! String // print("\(target)") // print("\(_stdlib_getTypeName(ITAGeoNativeScreenViewController()))") // print("\(_stdlib_getTypeName(Test()))") // // // // // let appName = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as String // let appNameNoSpaces = appName.stringByReplacingOccurrencesOfString(" ", withString: "_", options: .LiteralSearch, range: nil) // let mangledClassName = "_TtC\(countElements(appNameNoSpaces))\(appNameNoSpaces)\(countElements(className))\(className)" // print(mangledClassName) // var anyobjectype : AnyObject.Type = NSClassFromString(mangledClassName) // var nsobjectype : NSObject.Type = anyobjectype as NSObject.Type // var screen: UIViewController = nsobjectype() as UIViewController // return screen // } }
mit
7fcae0be9227a0d6b14977428f67b630
50.786337
267
0.589323
5.829352
false
false
false
false
apple/swift-nio
Tests/NIOPosixTests/MulticastTest.swift
1
30036
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore import NIOPosix import XCTest final class PromiseOnReadHandler: ChannelInboundHandler { typealias InboundIn = AddressedEnvelope<ByteBuffer> private let promise: EventLoopPromise<InboundIn> init(promise: EventLoopPromise<InboundIn>) { self.promise = promise } func channelRead(context: ChannelHandlerContext, data: NIOAny) { self.promise.succeed(self.unwrapInboundIn(data)) _ = context.pipeline.removeHandler(context: context) } } final class MulticastTest: XCTestCase { private var group: MultiThreadedEventLoopGroup! override func setUp() { self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1) } override func tearDown() { XCTAssertNoThrow(try self.group.syncShutdownGracefully()) } struct NoSuchInterfaceError: Error { } struct MulticastInterfaceMismatchError: Error { } struct ReceivedDatagramError: Error { } @available(*, deprecated) private func interfaceForAddress(address: String) throws -> NIONetworkInterface { let targetAddress = try SocketAddress(ipAddress: address, port: 0) guard let interface = try System.enumerateInterfaces().lazy.filter({ $0.address == targetAddress }).first else { throw NoSuchInterfaceError() } return interface } private func deviceForAddress(address: String) throws -> NIONetworkDevice { let targetAddress = try SocketAddress(ipAddress: address, port: 0) guard let device = try System.enumerateDevices().lazy.filter({ $0.address == targetAddress }).first else { throw NoSuchInterfaceError() } return device } @available(*, deprecated) private func bindMulticastChannel(host: String, port: Int, multicastAddress: String, interface: NIONetworkInterface) -> EventLoopFuture<MulticastChannel> { return DatagramBootstrap(group: self.group) .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) .bind(host: host, port: port) .flatMap { channel in let channel = channel as! MulticastChannel do { let multicastAddress = try SocketAddress(ipAddress: multicastAddress, port: channel.localAddress!.port!) return channel.joinGroup(multicastAddress, interface: interface).map { channel } } catch { return channel.eventLoop.makeFailedFuture(error) } }.flatMap { (channel: MulticastChannel) -> EventLoopFuture<MulticastChannel> in let provider = channel as! SocketOptionProvider switch channel.localAddress! { case .v4: return provider.setIPMulticastLoop(1).map { channel } case .v6: return provider.setIPv6MulticastLoop(1).map { channel } case .unixDomainSocket: preconditionFailure("Multicast is meaningless on unix domain sockets") } } } private func bindMulticastChannel(host: String, port: Int, multicastAddress: String, device: NIONetworkDevice) -> EventLoopFuture<MulticastChannel> { return DatagramBootstrap(group: self.group) .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) .bind(host: host, port: port) .flatMap { channel in let channel = channel as! MulticastChannel do { let multicastAddress = try SocketAddress(ipAddress: multicastAddress, port: channel.localAddress!.port!) return channel.joinGroup(multicastAddress, device: device).map { channel } } catch { return channel.eventLoop.makeFailedFuture(error) } }.flatMap { (channel: MulticastChannel) -> EventLoopFuture<MulticastChannel> in let provider = channel as! SocketOptionProvider switch channel.localAddress! { case .v4: return provider.setIPMulticastLoop(1).map { channel } case .v6: return provider.setIPv6MulticastLoop(1).map { channel } case .unixDomainSocket: preconditionFailure("Multicast is meaningless on unix domain sockets") } } } @available(*, deprecated) private func configureSenderMulticastIf(sender: Channel, multicastInterface: NIONetworkInterface) -> EventLoopFuture<Void> { let provider = sender as! SocketOptionProvider switch (sender.localAddress!, multicastInterface.address) { case (.v4, .v4(let addr)): return provider.setIPMulticastIF(addr.address.sin_addr) case (.v6, .v6): return provider.setIPv6MulticastIF(CUnsignedInt(multicastInterface.interfaceIndex)) default: XCTFail("Cannot join channel bound to \(sender.localAddress!) to interface at \(multicastInterface.address)") return sender.eventLoop.makeFailedFuture(MulticastInterfaceMismatchError()) } } private func configureSenderMulticastIf(sender: Channel, multicastDevice: NIONetworkDevice) -> EventLoopFuture<Void> { let provider = sender as! SocketOptionProvider switch (sender.localAddress!, multicastDevice.address) { case (.v4, .some(.v4(let addr))): return provider.setIPMulticastIF(addr.address.sin_addr) case (.v6, .some(.v6)): return provider.setIPv6MulticastIF(CUnsignedInt(multicastDevice.interfaceIndex)) default: XCTFail("Cannot join channel bound to \(sender.localAddress!) to interface at \(String(describing: multicastDevice.address))") return sender.eventLoop.makeFailedFuture(MulticastInterfaceMismatchError()) } } @available(*, deprecated) private func leaveMulticastGroup(channel: Channel, multicastAddress: String, interface: NIONetworkInterface) -> EventLoopFuture<Void> { let channel = channel as! MulticastChannel do { let multicastAddress = try SocketAddress(ipAddress: multicastAddress, port: channel.localAddress!.port!) return channel.leaveGroup(multicastAddress, interface: interface) } catch { return channel.eventLoop.makeFailedFuture(error) } } private func leaveMulticastGroup(channel: Channel, multicastAddress: String, device: NIONetworkDevice) -> EventLoopFuture<Void> { let channel = channel as! MulticastChannel do { let multicastAddress = try SocketAddress(ipAddress: multicastAddress, port: channel.localAddress!.port!) return channel.leaveGroup(multicastAddress, device: device) } catch { return channel.eventLoop.makeFailedFuture(error) } } private func assertDatagramReaches(multicastChannel: Channel, sender: Channel, multicastAddress: SocketAddress, file: StaticString = #filePath, line: UInt = #line) throws { let receivedMulticastDatagram = multicastChannel.eventLoop.makePromise(of: AddressedEnvelope<ByteBuffer>.self) XCTAssertNoThrow(try multicastChannel.pipeline.addHandler(PromiseOnReadHandler(promise: receivedMulticastDatagram)).wait()) var messageBuffer = sender.allocator.buffer(capacity: 24) messageBuffer.writeStaticString("hello, world!") XCTAssertNoThrow( try sender.writeAndFlush(AddressedEnvelope(remoteAddress: multicastAddress, data: messageBuffer)).wait(), file: (file), line: line ) let receivedDatagram = try assertNoThrowWithValue(receivedMulticastDatagram.futureResult.wait(), file: (file), line: line) XCTAssertEqual(receivedDatagram.remoteAddress, sender.localAddress!) XCTAssertEqual(receivedDatagram.data, messageBuffer) } private func assertDatagramDoesNotReach(multicastChannel: Channel, after timeout: TimeAmount, sender: Channel, multicastAddress: SocketAddress, file: StaticString = #filePath, line: UInt = #line) throws { let timeoutPromise = multicastChannel.eventLoop.makePromise(of: Void.self) let receivedMulticastDatagram = multicastChannel.eventLoop.makePromise(of: AddressedEnvelope<ByteBuffer>.self) XCTAssertNoThrow(try multicastChannel.pipeline.addHandler(PromiseOnReadHandler(promise: receivedMulticastDatagram)).wait()) // If we receive a datagram, or the reader promise fails, we must fail the timeoutPromise. receivedMulticastDatagram.futureResult.map { (_: AddressedEnvelope<ByteBuffer>) in timeoutPromise.fail(ReceivedDatagramError()) }.cascadeFailure(to: timeoutPromise) var messageBuffer = sender.allocator.buffer(capacity: 24) messageBuffer.writeStaticString("hello, world!") XCTAssertNoThrow( try sender.writeAndFlush(AddressedEnvelope(remoteAddress: multicastAddress, data: messageBuffer)).wait(), file: (file), line: line ) _ = multicastChannel.eventLoop.scheduleTask(in: timeout) { timeoutPromise.succeed(()) } XCTAssertNoThrow(try timeoutPromise.futureResult.wait(), file: (file), line: line) } @available(*, deprecated) func testCanJoinBasicMulticastGroupIPv4() throws { let multicastInterface = try assertNoThrowWithValue(self.interfaceForAddress(address: "127.0.0.1")) guard multicastInterface.multicastSupported else { // alas, we don't support multicast, let's skip but test the right error is thrown XCTAssertThrowsError(try self.bindMulticastChannel(host: "0.0.0.0", port: 0, multicastAddress: "224.0.2.66", interface: multicastInterface).wait()) { error in if let error = error as? NIOMulticastNotSupportedError { XCTAssertEqual(NIONetworkDevice(multicastInterface), error.device) } else { XCTFail("unexpected error: \(error)") } } return } // We avoid the risk of interference due to our all-addresses bind by only joining this multicast // group on the loopback. let listenerChannel: Channel do { listenerChannel = try assertNoThrowWithValue(self.bindMulticastChannel(host: "0.0.0.0", port: 0, multicastAddress: "224.0.2.66", interface: multicastInterface).wait()) // no error, that's great } catch { if error is NIOMulticastNotSupportedError { XCTFail("network interface (\(multicastInterface))) claims we support multicast but: \(error)") } else { XCTFail("unexpected error: \(error)") } return } defer { XCTAssertNoThrow(try listenerChannel.close().wait()) } let multicastAddress = try assertNoThrowWithValue(try SocketAddress(ipAddress: "224.0.2.66", port: listenerChannel.localAddress!.port!)) // Now that we've joined the group, let's send to it. let sender = try assertNoThrowWithValue(DatagramBootstrap(group: self.group) .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) .bind(host: "127.0.0.1", port: 0) .wait() ) defer { XCTAssertNoThrow(try sender.close().wait()) } XCTAssertNoThrow(try configureSenderMulticastIf(sender: sender, multicastInterface: multicastInterface).wait()) try self.assertDatagramReaches(multicastChannel: listenerChannel, sender: sender, multicastAddress: multicastAddress) } @available(*, deprecated) func testCanJoinBasicMulticastGroupIPv6() throws { guard System.supportsIPv6 else { // Skip on non-IPv6 systems return } let multicastInterface = try assertNoThrowWithValue(self.interfaceForAddress(address: "::1")) guard multicastInterface.multicastSupported else { // alas, we don't support multicast, let's skip but test the right error is thrown XCTAssertThrowsError(try self.bindMulticastChannel(host: "::1", port: 0, multicastAddress: "ff12::beeb", interface: multicastInterface).wait()) { error in if let error = error as? NIOMulticastNotSupportedError { XCTAssertEqual(NIONetworkDevice(multicastInterface), error.device) } else { XCTFail("unexpected error: \(error)") } } return } let listenerChannel: Channel do { // We avoid the risk of interference due to our all-addresses bind by only joining this multicast // group on the loopback. listenerChannel = try assertNoThrowWithValue(self.bindMulticastChannel(host: "::1", port: 0, multicastAddress: "ff12::beeb", interface: multicastInterface).wait()) } catch { if error is NIOMulticastNotSupportedError { XCTFail("network interface (\(multicastInterface))) claims we support multicast but: \(error)") } else { XCTFail("unexpected error: \(error)") } return } defer { XCTAssertNoThrow(try listenerChannel.close().wait()) } let multicastAddress = try assertNoThrowWithValue(try SocketAddress(ipAddress: "ff12::beeb", port: listenerChannel.localAddress!.port!)) // Now that we've joined the group, let's send to it. let sender = try assertNoThrowWithValue(DatagramBootstrap(group: self.group) .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) .bind(host: "::1", port: 0) .wait() ) defer { XCTAssertNoThrow(try sender.close().wait()) } XCTAssertNoThrow(try configureSenderMulticastIf(sender: sender, multicastInterface: multicastInterface).wait()) try self.assertDatagramReaches(multicastChannel: listenerChannel, sender: sender, multicastAddress: multicastAddress) } @available(*, deprecated) func testCanLeaveAnIPv4MulticastGroup() throws { let multicastInterface = try assertNoThrowWithValue(self.interfaceForAddress(address: "127.0.0.1")) guard multicastInterface.multicastSupported else { // alas, we don't support multicast, let's skip return } // We avoid the risk of interference due to our all-addresses bind by only joining this multicast // group on the loopback. let listenerChannel = try assertNoThrowWithValue(self.bindMulticastChannel(host: "0.0.0.0", port: 0, multicastAddress: "224.0.2.66", interface: multicastInterface).wait()) defer { XCTAssertNoThrow(try listenerChannel.close().wait()) } let multicastAddress = try assertNoThrowWithValue(try SocketAddress(ipAddress: "224.0.2.66", port: listenerChannel.localAddress!.port!)) // Now that we've joined the group, let's send to it. let sender = try assertNoThrowWithValue(DatagramBootstrap(group: self.group) .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) .bind(host: "127.0.0.1", port: 0) .wait() ) defer { XCTAssertNoThrow(try sender.close().wait()) } XCTAssertNoThrow(try configureSenderMulticastIf(sender: sender, multicastInterface: multicastInterface).wait()) try self.assertDatagramReaches(multicastChannel: listenerChannel, sender: sender, multicastAddress: multicastAddress) // Now we should *leave* the group. XCTAssertNoThrow(try leaveMulticastGroup(channel: listenerChannel, multicastAddress: "224.0.2.66", interface: multicastInterface).wait()) try self.assertDatagramDoesNotReach(multicastChannel: listenerChannel, after: .milliseconds(500), sender: sender, multicastAddress: multicastAddress) } @available(*, deprecated) func testCanLeaveAnIPv6MulticastGroup() throws { guard System.supportsIPv6 else { // Skip on non-IPv6 systems return } let multicastInterface = try assertNoThrowWithValue(self.interfaceForAddress(address: "::1")) guard multicastInterface.multicastSupported else { // alas, we don't support multicast, let's skip return } // We avoid the risk of interference due to our all-addresses bind by only joining this multicast // group on the loopback. let listenerChannel = try assertNoThrowWithValue(self.bindMulticastChannel(host: "::1", port: 0, multicastAddress: "ff12::beeb", interface: multicastInterface).wait()) defer { XCTAssertNoThrow(try listenerChannel.close().wait()) } let multicastAddress = try assertNoThrowWithValue(try SocketAddress(ipAddress: "ff12::beeb", port: listenerChannel.localAddress!.port!)) // Now that we've joined the group, let's send to it. let sender = try assertNoThrowWithValue(DatagramBootstrap(group: self.group) .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) .bind(host: "::1", port: 0) .wait() ) defer { XCTAssertNoThrow(try sender.close().wait()) } XCTAssertNoThrow(try configureSenderMulticastIf(sender: sender, multicastInterface: multicastInterface).wait()) try self.assertDatagramReaches(multicastChannel: listenerChannel, sender: sender, multicastAddress: multicastAddress) // Now we should *leave* the group. XCTAssertNoThrow(try leaveMulticastGroup(channel: listenerChannel, multicastAddress: "ff12::beeb", interface: multicastInterface).wait()) try self.assertDatagramDoesNotReach(multicastChannel: listenerChannel, after: .milliseconds(500), sender: sender, multicastAddress: multicastAddress) } func testCanJoinBasicMulticastGroupIPv4WithDevice() throws { let multicastDevice = try assertNoThrowWithValue(self.deviceForAddress(address: "127.0.0.1")) guard multicastDevice.multicastSupported else { // alas, we don't support multicast, let's skip but test the right error is thrown XCTAssertThrowsError(try self.bindMulticastChannel(host: "0.0.0.0", port: 0, multicastAddress: "224.0.2.66", device: multicastDevice).wait()) { error in if let error = error as? NIOMulticastNotSupportedError { XCTAssertEqual(multicastDevice, error.device) } else { XCTFail("unexpected error: \(error)") } } return } // We avoid the risk of interference due to our all-addresses bind by only joining this multicast // group on the loopback. let listenerChannel: Channel do { listenerChannel = try assertNoThrowWithValue(self.bindMulticastChannel(host: "0.0.0.0", port: 0, multicastAddress: "224.0.2.66", device: multicastDevice).wait()) // no error, that's great } catch { if error is NIOMulticastNotSupportedError { XCTFail("network interface (\(multicastDevice)) claims we support multicast but: \(error)") } else { XCTFail("unexpected error: \(error)") } return } defer { XCTAssertNoThrow(try listenerChannel.close().wait()) } let multicastAddress = try assertNoThrowWithValue(try SocketAddress(ipAddress: "224.0.2.66", port: listenerChannel.localAddress!.port!)) // Now that we've joined the group, let's send to it. let sender = try assertNoThrowWithValue(DatagramBootstrap(group: self.group) .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) .bind(host: "127.0.0.1", port: 0) .wait() ) defer { XCTAssertNoThrow(try sender.close().wait()) } XCTAssertNoThrow(try configureSenderMulticastIf(sender: sender, multicastDevice: multicastDevice).wait()) try self.assertDatagramReaches(multicastChannel: listenerChannel, sender: sender, multicastAddress: multicastAddress) } func testCanJoinBasicMulticastGroupIPv6WithDevice() throws { guard System.supportsIPv6 else { // Skip on non-IPv6 systems return } let multicastDevice = try assertNoThrowWithValue(self.deviceForAddress(address: "::1")) guard multicastDevice.multicastSupported else { // alas, we don't support multicast, let's skip but test the right error is thrown XCTAssertThrowsError(try self.bindMulticastChannel(host: "::1", port: 0, multicastAddress: "ff12::beeb", device: multicastDevice).wait()) { error in if let error = error as? NIOMulticastNotSupportedError { XCTAssertEqual(multicastDevice, error.device) } else { XCTFail("unexpected error: \(error)") } } return } let listenerChannel: Channel do { // We avoid the risk of interference due to our all-addresses bind by only joining this multicast // group on the loopback. listenerChannel = try assertNoThrowWithValue(self.bindMulticastChannel(host: "::1", port: 0, multicastAddress: "ff12::beeb", device: multicastDevice).wait()) } catch { if error is NIOMulticastNotSupportedError { XCTFail("network interface (\(multicastDevice)) claims we support multicast but: \(error)") } else { XCTFail("unexpected error: \(error)") } return } defer { XCTAssertNoThrow(try listenerChannel.close().wait()) } let multicastAddress = try assertNoThrowWithValue(try SocketAddress(ipAddress: "ff12::beeb", port: listenerChannel.localAddress!.port!)) // Now that we've joined the group, let's send to it. let sender = try assertNoThrowWithValue(DatagramBootstrap(group: self.group) .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) .bind(host: "::1", port: 0) .wait() ) defer { XCTAssertNoThrow(try sender.close().wait()) } XCTAssertNoThrow(try configureSenderMulticastIf(sender: sender, multicastDevice: multicastDevice).wait()) try self.assertDatagramReaches(multicastChannel: listenerChannel, sender: sender, multicastAddress: multicastAddress) } func testCanLeaveAnIPv4MulticastGroupWithDevice() throws { let multicastDevice = try assertNoThrowWithValue(self.deviceForAddress(address: "127.0.0.1")) guard multicastDevice.multicastSupported else { // alas, we don't support multicast, let's skip return } // We avoid the risk of interference due to our all-addresses bind by only joining this multicast // group on the loopback. let listenerChannel = try assertNoThrowWithValue(self.bindMulticastChannel(host: "0.0.0.0", port: 0, multicastAddress: "224.0.2.66", device: multicastDevice).wait()) defer { XCTAssertNoThrow(try listenerChannel.close().wait()) } let multicastAddress = try assertNoThrowWithValue(try SocketAddress(ipAddress: "224.0.2.66", port: listenerChannel.localAddress!.port!)) // Now that we've joined the group, let's send to it. let sender = try assertNoThrowWithValue(DatagramBootstrap(group: self.group) .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) .bind(host: "127.0.0.1", port: 0) .wait() ) defer { XCTAssertNoThrow(try sender.close().wait()) } XCTAssertNoThrow(try configureSenderMulticastIf(sender: sender, multicastDevice: multicastDevice).wait()) try self.assertDatagramReaches(multicastChannel: listenerChannel, sender: sender, multicastAddress: multicastAddress) // Now we should *leave* the group. XCTAssertNoThrow(try leaveMulticastGroup(channel: listenerChannel, multicastAddress: "224.0.2.66", device: multicastDevice).wait()) try self.assertDatagramDoesNotReach(multicastChannel: listenerChannel, after: .milliseconds(500), sender: sender, multicastAddress: multicastAddress) } func testCanLeaveAnIPv6MulticastGroupWithDevice() throws { guard System.supportsIPv6 else { // Skip on non-IPv6 systems return } let multicastDevice = try assertNoThrowWithValue(self.deviceForAddress(address: "::1")) guard multicastDevice.multicastSupported else { // alas, we don't support multicast, let's skip return } // We avoid the risk of interference due to our all-addresses bind by only joining this multicast // group on the loopback. let listenerChannel = try assertNoThrowWithValue(self.bindMulticastChannel(host: "::1", port: 0, multicastAddress: "ff12::beeb", device: multicastDevice).wait()) defer { XCTAssertNoThrow(try listenerChannel.close().wait()) } let multicastAddress = try assertNoThrowWithValue(try SocketAddress(ipAddress: "ff12::beeb", port: listenerChannel.localAddress!.port!)) // Now that we've joined the group, let's send to it. let sender = try assertNoThrowWithValue(DatagramBootstrap(group: self.group) .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) .bind(host: "::1", port: 0) .wait() ) defer { XCTAssertNoThrow(try sender.close().wait()) } XCTAssertNoThrow(try configureSenderMulticastIf(sender: sender, multicastDevice: multicastDevice).wait()) try self.assertDatagramReaches(multicastChannel: listenerChannel, sender: sender, multicastAddress: multicastAddress) // Now we should *leave* the group. XCTAssertNoThrow(try leaveMulticastGroup(channel: listenerChannel, multicastAddress: "ff12::beeb", device: multicastDevice).wait()) try self.assertDatagramDoesNotReach(multicastChannel: listenerChannel, after: .milliseconds(500), sender: sender, multicastAddress: multicastAddress) } }
apache-2.0
24498a74b854e417e0a6cc73c3ff21b3
47.839024
176
0.590724
5.460098
false
false
false
false
congncif/SiFUtilities
Example/Pods/SiFUtilities/SiFUtilities/Classes/String++.swift
1
2882
// // String++.swift // SiFUtilities // // Created by FOLY on 1/11/17. // Copyright © 2017 [iF] Solution. All rights reserved. // import Foundation public extension String { public static func random(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 } public var htmlToAttributedString: NSAttributedString? { guard let data = data(using: String.Encoding.utf8) else { return nil } return try? NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute: NSNumber(value: String.Encoding.utf8.rawValue)], documentAttributes: nil) } public var htmlToString: String? { guard let data = data(using: String.Encoding.utf8) else { return nil } var result: String? result = try? NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute: NSNumber(value: String.Encoding.utf8.rawValue)], documentAttributes: nil).string return result } public func containOneAtLeastRegex(separatedBy: String? = nil) -> String { let searchTags = separatedBy == nil ? [self] : self.components(separatedBy: separatedBy!) var regex = ".*(" for tag in searchTags { regex += tag if tag != searchTags.last { regex += "|" } } regex += ").*" return regex } func toDate(format: String? = nil) -> Date? { let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) let internalFormat = format != nil ? format : "dd-MM-yyyy" dateFormatter.dateFormat = internalFormat return dateFormatter.date(from: self) } public func toDate(format: String? = "dd-MM-yyyy", timeZone: TimeZone = TimeZone(secondsFromGMT: 0)!) -> Date? { let dateFormatter = DateFormatter() dateFormatter.timeZone = timeZone let internalFormat = format dateFormatter.dateFormat = internalFormat return dateFormatter.date(from: self) } }
mit
8f009caf5e0e8f2f353eb3cc9b7c46a2
32.114943
193
0.574453
5.385047
false
false
false
false
ReduxKit/ReduxKit
ReduxKitTests/Mocks.swift
1
5943
// // Mocks.swift // ReduxKit // // Created by Aleksander Herforth Rendtslev on 05/11/15. // Copyright © 2015 Kare Media. All rights reserved. // import ReduxKit /** Application state */ struct AppState { var counter: Int! var countries: [String]! var textField: TextFieldState! } /** Nested textField state. Application state can effectively be compartementalized this way. */ struct TextFieldState { var value: String = "" } /** Total application reducer. This should create your base state and associate each individual reducer with its part of the state. Reducers can effectively be nested to avoid having to specify the whole chain on the top level. All reducers have been implemented with optional states. This is to simplify this reducer, so that it can be called without an initial AppState - parameter state: AppState - will default to nil - parameter action: ActionType - returns: Will return BaseState */ func applicationReducer(state: AppState? = nil, action: Action) -> AppState { return AppState( counter: counterReducer(state?.counter, action: action), countries: countryReducer(state?.countries, action: action), textField: textFieldReducer(state?.textField, action: action)) } /** Example of a simple counter reducer. This state takes a simple integer value and returns it in an incremented state - for the IncrementAction This could also have a decrementAction. - parameter previousState: Int - parameter action: ActionType - returns: Will return nextState - Int */ func counterReducer(previousState: Int?, action: Action) -> Int { // Declare the type of the state let state = previousState ?? 0 switch action { case let action as IncrementAction: return state + action.rawPayload default: return state } } /** Example of an array based reducer. It will push any new values into a new array and return it. - parameter previousState: [String]? - parameter action: ActiontYpe - returns: Will return nextState: [String] */ func countryReducer(previousState: [String]?, action: Action) -> [String] { let state = previousState ?? [String]() switch action { case let action as PushAction: return state + [action.rawPayload.text] default: return state } } /** Example of a more complex reducer. It takes a textFieldState as an argument and returns a new textFieldState - parameter previousState: TextFieldState? - parameter action: ActionType - returns: Will return nextState: TextFieldState */ func textFieldReducer(previousState: TextFieldState?, action: Action) -> TextFieldState { switch action { case let action as UpdateTextFieldAction: return TextFieldState(value: action.rawPayload.text) default: return previousState ?? TextFieldState() } } /** Simple updateTextFieldAction - with unique payload */ struct UpdateTextFieldAction: StandardAction { let meta: Any? let error: Bool let rawPayload: Payload init(payload: Payload?, meta: Any? = nil, error: Bool = false) { self.rawPayload = payload != nil ? payload! : Payload(text: "") self.meta = meta self.error = error } struct Payload { var text: String } } struct ReTravelAction: SimpleStandardAction { let meta: Any? = nil let error: Bool = false let rawPayload: Any? = nil } /** Simple IncrementAction. Since it doesn't utilize payload it has been set to 1 */ struct IncrementAction: StandardAction { let meta: Any? let error: Bool let rawPayload: Int init(payload: Int? = nil, meta: Any? = nil, error: Bool = false) { self.rawPayload = payload ?? 1 self.meta = meta self.error = error } } /** Push action */ struct PushAction: StandardAction { let meta: Any? let error: Bool let rawPayload: Payload init(payload: Payload?, meta: Any? = nil, error: Bool = false) { self.rawPayload = payload != nil ? payload! : Payload(text: "") self.meta = meta self.error = error } struct Payload { var text: String init(text: String) { self.text = text } } } /** first middleware - it will add .first to the payload of any pushAction. - parameter store: store description - returns: return value description */ func firstPushMiddleware<State>(store: MiddlewareApi<State>) -> DispatchTransformer { return { next in { action in if let pushAction = action as? PushAction { let newAction = PushAction( payload: PushAction.Payload(text: pushAction.rawPayload.text + ".first")) return next(newAction) } else { return next(action) } }} } /** second middleware - it will add .secondary to the payload of any pushAction. - parameter store: store description - returns: return value description */ func secondaryPushMiddleware<State>(store: MiddlewareApi<State>) -> DispatchTransformer { return { next in { action in if let pushAction = action as? PushAction { let newAction = PushAction( payload: PushAction.Payload(text: pushAction.rawPayload.text + ".secondary")) return next(newAction) } else { return next(action) } }} } /** Re-travel middleware - it will discard ReTravelAction's and dispatch an IncrementAction instead. - parameter store: store description - returns: return value description */ func reTravelMiddleware<State>(store: MiddlewareApi<State>) -> DispatchTransformer { return { next in { action in if action is ReTravelAction { store.dispatch(IncrementAction(payload: 10)) } else if action is IncrementAction { return next(IncrementAction()) } return next(action) }} }
mit
55e02e21487e5486762a9a4f6df86d75
24.947598
99
0.666611
4.356305
false
false
false
false
IvanVorobei/RequestPermission
Example/SPPermission/SPPermission/Frameworks/SparrowKit/Extension/SPArrayExtension.swift
1
1817
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([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 extension Array { func get(count: Int) -> Array { if (count < self.count) { return Array(self[0..<count]) } return Array(self) } } extension Array where Element: Equatable { mutating func removeDuplicates() { var result = [Element]() for value in self { if result.contains(value) == false { result.append(value) } } self = result } } extension Array where Element: Hashable { func after(item: Element) -> Element? { if let index = self.firstIndex(of: item), index + 1 < self.count { return self[index + 1] } return nil } }
mit
afbb949cb1f014acef2bcd68c26118b1
36.061224
99
0.695485
4.386473
false
false
false
false
CtrlCnV/iOS-Swift_CustomBackButton
CustomBack/AppDelegate.swift
1
6133
// // AppDelegate.swift // CustomBack // // Created by Kkumkkum Kim on 2015. 1. 1.. // Copyright (c) 2015년 CtrlCnV. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // 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.ctrlcnv.CustomBack" 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("CustomBack", 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("CustomBack.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. let dict = NSMutableDictionary() 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 }() // MARK: - Core Data Saving support 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
9a3cdd80905311aa0d898c347a882dab
54.234234
290
0.716196
5.729907
false
false
false
false