repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
dominickhera/Projects
personal/iOU/iOU 4.0/SettingsTableViewController.swift
2
3991
// // SettingsTableViewController.swift // iOU 4.0 // // Created by Dominick Hera on 2/24/15. // Copyright (c) 2015 Posa. All rights reserved. // import UIKit class SettingsTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 0 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { print("i work") let alert = UIAlertController(title: "Item selected", message: "You selected item \(indexPath.row)", preferredStyle: UIAlertControllerStyle.Alert) let action = UIAlertAction(title: "Okay", style: .Cancel) { (action) in // ... } alert.addAction(action) print("boutta present") //self.presentViewController(alert, animated: true, completion: nil ) self.presentViewController(alert, animated: true) { () -> Void in print("completed") } } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // 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. } */ }
apache-2.0
18038aa4d730338bdcf4bdeae80e1051
34.954955
157
0.674267
5.444748
false
false
false
false
silence0201/Swift-Study
AdvancedSwift/函数/Properties and Subscripts - 2.playgroundpage/Contents.swift
1
4565
/*: If we want to make the `record` property available as read-only to the outside, but read-write internally, we can use the `private(set)` or `fileprivate(set)` modifiers: */ //#-hidden-code import Foundation import CoreLocation //#-end-hidden-code struct GPSTrack { private(set) var record: [(CLLocation, Date)] = [] } /*: To access all the dates in a GPS track, we create a computed property: */ extension GPSTrack { /// Returns all the dates for the GPS track. /// - Complexity: O(*n*), where *n* is the number of points recorded. var dates: [Date] { return record.map { $0.1 } } } /*: Because we didn't specify a setter, the `dates` property is read-only. The result isn't cached; each time you access the `dates` property, it computes the result. The Swift API Design Guidelines recommend that you document the complexity of every computed property that isn't `O(1)`, because callers might assume that computing a property takes constant time. ### Lazy Stored Properties Initializing a value lazily is such a common pattern that Swift has a special `lazy` keyword to define a lazy property. Note that a lazy property is automatically `mutating` and therefore must be declared as `var`. The lazy modifier is a very specific form of [memoization](https://en.wikipedia.org/wiki/Memoization). For example, if we have a view controller that displays a `GPSTrack`, we might want to have a preview image of the track. By making the property for that lazy, we can defer the expensive generation of the image until the property is accessed for the first time: */ //#-hidden-code import UIKit //#-end-hidden-code class GPSTrackViewController: UIViewController { var track: GPSTrack = GPSTrack() lazy var preview: UIImage = { for point in self.track.record { // Do some expensive computation } return UIImage() }() } /*: Notice how we defined the lazy property: it's a closure expression that returns the value we want to store — in our case, an image. When the property is first accessed, the closure is executed (note the parentheses at the end), and its return value is stored in the property. This is a common pattern for lazy properties that require more than a one-liner to be initialized. Because a lazy variable needs storage, we're required to define the lazy property in the definition of `GPSTrackViewController`. Unlike computed properties, stored properties and stored lazy properties can't be defined in an extension. Also, we're required to use `self.` inside the closure expression when we want to access instance members (in this case, we need to write `self.track`). If the `track` property changes, the `preview` won't automatically get invalidated. Let's look at an even simpler example to see what's going on. We have a `Point` struct, and we store `distanceFromOrigin` as a lazy computed property: */ //#-editable-code struct Point { var x: Double = 0 var y: Double = 0 lazy var distanceFromOrigin: Double = self.x*self.x + self.y*self.y init(x: Double, y: Double) { self.x = x self.y = y } } //#-end-editable-code /*: When we create a point, we can access the `distanceFromOrigin` property, and it'll compute the value and store it for reuse. However, if we then change the `x` value, this won't be reflected in `distanceFromOrigin`: */ //#-editable-code var point = Point(x: 3, y: 4) point.distanceFromOrigin point.x += 10 point.distanceFromOrigin //#-end-editable-code /*: It's important to be aware of this. One way around it would be to recompute `distanceFromOrigin` in the `didSet` property observers of `x` and `y`, but then `distanceFromOrigin` isn't really lazy anymore: it'll get computed each time `x` or `y` changes. Of course, in this example, the solution is easy: we should have made `distanceFromOrigin` a regular (non-lazy) computed property from the beginning. As we saw in the chapter on structs and classes, we can also implement the `willSet` and `didSet` callbacks for properties and variables. These get called before and after the setter, respectively. One useful case is when working with Interface Builder: we can implement `didSet` to know when an `IBOutlet` gets connected, and then we can configure our views there. For example, if we want to set a label's text color once it's available, we can do the following: */ class SettingsController: UIViewController { @IBOutlet weak var label: UILabel? { didSet { label?.textColor = .black } } }
mit
0371bb5716465555157b368de0f004e0
32.065217
80
0.728687
3.999124
false
false
false
false
alvinvarghese/EasyIAPs
EasyIAPs/Classes/EasyIAP.swift
1
11892
// // IAPHelpers.swift // // Created by SwiftCoder.Club on 05/05/16. // Copyright (c) 2016 SwiftCoder.Club. All rights reserved. // import UIKit import StoreKit import Foundation import SVProgressHUD //MARK: SKProductsRequestDelegate extension EasyIAP : SKProductsRequestDelegate { func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) { if response.products.count > 0 { let validProduct = response.products[0] validProduct.productIdentifier == self.currnetProductIdentifier ? self.buyProduct(validProduct) : self.EasyIAPCompletionBlock!(success: false, error: EasyIAPErrorType.NoProductFound) } else { self.EasyIAPCompletionBlock!(success: false, error: EasyIAPErrorType.NoProducts) // Stop Activity Indicator self.hideActivityIndicator() } } } //MARK: SKRequestDelegate extension EasyIAP : SKRequestDelegate { func requestDidFinish(request: SKRequest) { } func request(request: SKRequest, didFailWithError error: NSError) { self.EasyIAPCompletionBlock!(success: false, error: EasyIAPErrorType.ProductRequestFailed) } } //MARK: SKPaymentTransactionObserver extension EasyIAP : SKPaymentTransactionObserver { func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { self.handlingTransactions(transactions) } func paymentQueueRestoreCompletedTransactionsFinished(queue: SKPaymentQueue) { queue.transactions.count == 0 ? self.EasyIAPCompletionBlock!(success: false, error: EasyIAPErrorType.DidntMakeAnyPayments) : self.handlingTransactions(queue.transactions) } func paymentQueue(queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: NSError) { // Stop Activity Indicator self.hideActivityIndicator() self.EasyIAPCompletionBlock!(success: false, error: EasyIAPErrorType.CouldNotRestore) } } //MARRK: EasyIAP class EasyIAP : NSObject { //MARK: Variables private let restorePurchaseIdentifier = "RESTORE_PURCHASE" private var receiptValidationServer = String() private var currnetProductIdentifier = String() private var loaderRingColor = UIColor.whiteColor() private var EasyIAPCompletionBlock : ((success : Bool, error : EasyIAPErrorType?) -> ())? //MARRK: startProductRequest func startProductRequest(productReferenceName : String, receiptValidatingServerURL : String, restore : Bool, loaderRingColor : UIColor, completion : (success : Bool, error : EasyIAPErrorType?) -> ()) { self.EasyIAPCompletionBlock = completion if Platform.isSimulator { self.EasyIAPCompletionBlock!(success: false, error: EasyIAPErrorType.CantRunInSimulator) } else { self.loaderRingColor = loaderRingColor if restore { self.currnetProductIdentifier = self.restorePurchaseIdentifier } else { self.currnetProductIdentifier = productReferenceName } self.receiptValidationServer = receiptValidatingServerURL self.showActivityIndicator() self.start() } } //MARK: Product Request private func start() { if let _ = NSURL(string: self.receiptValidationServer) { if (SKPaymentQueue.canMakePayments()) { if self.currnetProductIdentifier == self.restorePurchaseIdentifier { self.restorePurchases() } else { let productID : Set<String> = [self.currnetProductIdentifier] let productsRequest : SKProductsRequest = SKProductsRequest(productIdentifiers: productID) productsRequest.delegate = self productsRequest.start() } } else { // Stop Activity Indicator self.hideActivityIndicator() // Can't make payments self.EasyIAPCompletionBlock!(success: false, error: EasyIAPErrorType.CantMakePayments) } } else { // Stop Activity Indicator self.hideActivityIndicator() // Not a valid Receipt URL self.EasyIAPCompletionBlock!(success: false, error: EasyIAPErrorType.NotAValidReceiptURL) } } //MARK: Buy Product - Payment Section private func buyProduct(product : SKProduct) { // Show Activity Indicator self.showActivityIndicator() let payment = SKPayment(product: product) SKPaymentQueue.defaultQueue().addTransactionObserver(self) SKPaymentQueue.defaultQueue().addPayment(payment) } //MARK: Restore Transaction private func restoreTransaction(transaction : SKPaymentTransaction) { self.deliverProduct(transaction.payment.productIdentifier) } //MARK: Restore Purchases private func restorePurchases() { SKPaymentQueue.defaultQueue().addTransactionObserver(self) SKPaymentQueue.defaultQueue().restoreCompletedTransactions() } //MARK: Transaction Observer Handler private func handlingTransactions(transactions : [AnyObject]) { // Show Activity Indicator self.showActivityIndicator() for transaction in transactions { if let paymentTransaction : SKPaymentTransaction = transaction as? SKPaymentTransaction { switch paymentTransaction.transactionState { case .Purchasing : print("Purchasing") case .Purchased : print("Purchased") self.deliverProduct(paymentTransaction.payment.productIdentifier) SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction) case .Failed: print("Failed") SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction) case .Restored: print("Restored") SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction) self.restoreTransaction(paymentTransaction) case .Deferred: print("Deferred") } } } } //MARK: Deliver Product private func deliverProduct(product : String) { // Show Activity Indicator self.showActivityIndicator() self.validateReceipt { status , error in status ? self.EasyIAPCompletionBlock!(success: true, error: nil) : self.EasyIAPCompletionBlock!(success: false, error: error) // Stop Activity Indicator self.hideActivityIndicator() } } //MARK: Receipt Validation private func validateReceipt(completion : (status : Bool, error : EasyIAPErrorType?) -> ()) { if let receiptUrl = NSBundle.mainBundle().appStoreReceiptURL, urlPath = receiptUrl.path { if NSFileManager.defaultManager().fileExistsAtPath(urlPath) { if let receipt = NSData(contentsOfURL: receiptUrl) { let receiptdata: NSString = receipt.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.EncodingEndLineWithLineFeed) let dict = ["receipt-data" : receiptdata] let jsonData = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions(rawValue: 0)) let request = NSMutableURLRequest(URL: NSURL(string: self.receiptValidationServer)!) let session = NSURLSession.sharedSession() request.HTTPMethod = "POST" request.HTTPBody = jsonData request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("\(jsonData.length)", forHTTPHeaderField: "Content-Length") request.addValue("application/json", forHTTPHeaderField: "Accept") let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error in if let properData = data { self.handleResponseFromServer(properData, completion: { status, error in completion(status: status, error: error) }) } else { completion(status: false, error: EasyIAPErrorType.NoResponseFromServer) } }) task.resume() } else { completion(status: false, error: EasyIAPErrorType.CouldNotConvertReceiptURLToNSData) } } else { completion(status: false, error: EasyIAPErrorType.ReceiptURLDoesNotExists) } } else { completion(status: false, error: EasyIAPErrorType.ReceiptURLDoesNotExists) } } private func handleResponseFromServer(responseDatas : NSData, completion : (status : Bool, error : EasyIAPErrorType?) -> ()) { do { if let json = try NSJSONSerialization.JSONObjectWithData(responseDatas, options: NSJSONReadingOptions.MutableLeaves) as? NSDictionary { if let value = json.valueForKeyPath("status") as? Int { value == 0 ? completion(status: true, error: nil) : completion(status: false, error: value.easyIAPErrorType) } } else { completion(status: false, error: EasyIAPErrorType.StatusKeyDoesNotExistsInJSON) } } catch { completion(status: false, error: EasyIAPErrorType.CoultNotParseJSONFromRecieptServer) } } //MARK: Show Activity private func showActivityIndicator() { dispatch_async(dispatch_get_main_queue()) { SVProgressHUD.setDefaultStyle(SVProgressHUDStyle.Custom) SVProgressHUD.setForegroundColor(self.loaderRingColor) SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black) SVProgressHUD.setDefaultAnimationType(SVProgressHUDAnimationType.Flat) SVProgressHUD.show() } } //MARK: Hide Activity private func hideActivityIndicator() { dispatch_async(dispatch_get_main_queue()) { SVProgressHUD.dismiss() } } }
mit
c32612c11ca63b420abce42838db11ad
31.941828
205
0.564329
6.265543
false
false
false
false
tardieu/swift
benchmark/utils/ArgParse.swift
21
2670
//===--- ArgParse.swift ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation public struct Arguments { public var progName: String public var positionalArgs: [String] public var optionalArgsMap: [String : String] init(_ pName: String, _ posArgs: [String], _ optArgsMap: [String : String]) { progName = pName positionalArgs = posArgs optionalArgsMap = optArgsMap } } /// Using CommandLine.arguments, returns an Arguments struct describing /// the arguments to this program. If we fail to parse arguments, we /// return nil. /// /// We assume that optional switch args are of the form: /// /// --opt-name[=opt-value] /// -opt-name[=opt-value] /// /// with opt-name and opt-value not containing any '=' signs. Any /// other option passed in is assumed to be a positional argument. public func parseArgs(_ validOptions: [String]? = nil) -> Arguments? { let progName = CommandLine.arguments[0] var positionalArgs = [String]() var optionalArgsMap = [String : String]() // For each argument we are passed... var passThroughArgs = false for arg in CommandLine.arguments[1..<CommandLine.arguments.count] { // If the argument doesn't match the optional argument pattern. Add // it to the positional argument list and continue... if passThroughArgs || !arg.characters.starts(with: "-".characters) { positionalArgs.append(arg) continue } if arg == "--" { passThroughArgs = true continue } // Attempt to split it into two components separated by an equals sign. let components = arg.components(separatedBy: "=") let optionName = components[0] if validOptions != nil && !validOptions!.contains(optionName) { print("Invalid option: \(arg)") return nil } var optionVal : String switch components.count { case 1: optionVal = "" case 2: optionVal = components[1] default: // If we do not have two components at this point, we can not have // an option switch. This is an invalid argument. Bail! print("Invalid option: \(arg)") return nil } optionalArgsMap[optionName] = optionVal } return Arguments(progName, positionalArgs, optionalArgsMap) }
apache-2.0
64c581b62a3e07c8d77316b0934f51bf
33.230769
80
0.647566
4.57976
false
false
false
false
jmgc/swift
test/ClangImporter/objc_parse.swift
1
26168
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil -I %S/Inputs/custom-modules %s -verify // REQUIRES: objc_interop import AppKit import AVFoundation import Newtype import NewtypeSystem import objc_ext import TestProtocols import TypeAndValue import ObjCParseExtras import ObjCParseExtrasToo import ObjCParseExtrasSystem func markUsed<T>(_ t: T) {} func testAnyObject(_ obj: AnyObject) { _ = obj.nsstringProperty } // Construction func construction() { _ = B() } // Subtyping func treatBAsA(_ b: B) -> A { return b } // Instance method invocation func instanceMethods(_ b: B) { var i = b.method(1, with: 2.5 as Float) i = i + b.method(1, with: 2.5 as Double) // BOOL b.setEnabled(true) // SEL b.perform(#selector(NSObject.isEqual(_:)), with: b) if let result = b.perform(#selector(B.getAsProto), with: nil) { _ = result.takeUnretainedValue() } // Renaming of redundant parameters. b.performAdd(1, withValue:2, withValue2:3, withValue:4) // expected-error{{argument 'withValue' must precede argument 'withValue2'}} {{32-32=withValue:4, }} {{44-57=}} b.performAdd(1, withValue:2, withValue:4, withValue2: 3) b.performAdd(1, 2, 3, 4) // expected-error{{missing argument labels 'withValue:withValue:withValue2:' in call}} {{19-19=withValue: }} {{22-22=withValue: }} {{25-25=withValue2: }} // Both class and instance methods exist. _ = b.description b.instanceTakesObjectClassTakesFloat(b) b.instanceTakesObjectClassTakesFloat(2.0) // Instance methods with keyword components var obj = NSObject() var prot = NSObjectProtocol.self b.`protocol`(prot, hasThing:obj) b.doThing(obj, protocol: prot) } // Class method invocation func classMethods(_ b: B, other: NSObject) { var i = B.classMethod() i += B.classMethod(1) i += B.classMethod(1, with: 2) i += b.classMethod() // expected-error{{static member 'classMethod' cannot be used on instance of type 'B'}} // Both class and instance methods exist. B.description() B.instanceTakesObjectClassTakesFloat(2.0) // TODO(diagnostics): Once argument/parameter conversion diagnostics are implemented we should be able to // diagnose this as failed conversion from NSObject to Float, but right now the problem is that there // exists another overload `instanceTakesObjectClassTakesFloat: (Any?) -> Void` which makes this invocation // type-check iff base is an instance of `B`. B.instanceTakesObjectClassTakesFloat(other) // expected-error@-1 {{instance member 'instanceTakesObjectClassTakesFloat' cannot be used on type 'B'; did you mean to use a value of this type instead?}} // Call an instance method of NSObject. var c: AnyClass = B.myClass() // no-warning c = b.myClass() // no-warning } // Instance method invocation on extensions func instanceMethodsInExtensions(_ b: B) { b.method(1, onCat1:2.5) b.method(1, onExtA:2.5) b.method(1, onExtB:2.5) b.method(1, separateExtMethod:3.5) let m1 = b.method(_:onCat1:) _ = m1(1, 2.5) let m2 = b.method(_:onExtA:) _ = m2(1, 2.5) let m3 = b.method(_:onExtB:) _ = m3(1, 2.5) let m4 = b.method(_:separateExtMethod:) _ = m4(1, 2.5) } func dynamicLookupMethod(_ b: AnyObject) { if let m5 = b.method(_:separateExtMethod:) { _ = m5(1, 2.5) } } // Properties func properties(_ b: B) { var i = b.counter b.counter = i + 1 i = i + b.readCounter b.readCounter = i + 1 // expected-error{{cannot assign to property: 'readCounter' is a get-only property}} b.setCounter(5) // expected-error{{value of type 'B' has no member 'setCounter'}} // Informal properties in Objective-C map to methods, not variables. b.informalProp() // An informal property cannot be made formal in a subclass. The // formal property is simply ignored. b.informalMadeFormal() b.informalMadeFormal = i // expected-error{{cannot assign to value: 'informalMadeFormal' is a method}} b.setInformalMadeFormal(5) b.overriddenProp = 17 // Dynamic properties. var obj : AnyObject = b var optStr = obj.nsstringProperty // optStr has type String?? if optStr != nil { var s : String = optStr! // expected-error{{value of optional type 'String?' must be unwrapped}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} var t : String = optStr!! } // Properties that are Swift keywords var prot = b.`protocol` // Properties whose accessors run afoul of selector splitting. _ = SelectorSplittingAccessors() } // Construction. func newConstruction(_ a: A, aproxy: AProxy) { var b : B = B() b = B(int: 17) b = B(int:17) b = B(double:17.5, 3.14159) b = B(bbb:b) b = B(forWorldDomination:()) b = B(int: 17, andDouble : 3.14159) b = B.new(with: a) B.alloc()._initFoo() b.notAnInit() // init methods are not imported by themselves. b.initWithInt(17) // expected-error{{value of type 'B' has no member 'initWithInt'}} // init methods on non-NSObject-rooted classes AProxy(int: 5) // expected-warning{{unused}} } // Indexed subscripting func indexedSubscripting(_ b: B, idx: Int, a: A) { b[idx] = a _ = b[idx] as! A } // Keyed subscripting func keyedSubscripting(_ b: B, idx: A, a: A) { b[a] = a var a2 = b[a] as! A let dict = NSMutableDictionary() dict[NSString()] = a let value = dict[NSString()] dict[nil] = a // expected-error {{'nil' is not compatible with expected argument type 'NSCopying'}} let q = dict[nil] // expected-error {{'nil' is not compatible with expected argument type 'NSCopying'}} _ = q } // Typed indexed subscripting func checkHive(_ hive: Hive, b: Bee) { let b2 = hive.bees[5] as Bee b2.buzz() } // Protocols func testProtocols(_ b: B, bp: BProto) { var bp2 : BProto = b var b2 : B = bp // expected-error{{cannot convert value of type 'BProto' to specified type 'B'}} bp.method(1, with: 2.5 as Float) bp.method(1, withFoo: 2.5) // expected-error{{incorrect argument label in call (have '_:withFoo:', expected '_:with:')}} bp2 = b.getAsProto() var c1 : Cat1Proto = b var bcat1 = b.getAsProtoWithCat()! c1 = bcat1 bcat1 = c1 // expected-error{{value of type 'Cat1Proto' does not conform to 'BProto' in assignment}} } // Methods only defined in a protocol func testProtocolMethods(_ b: B, p2m: P2.Type) { b.otherMethod(1, with: 3.14159) b.p2Method() b.initViaP2(3.14159, second: 3.14159) // expected-error{{value of type 'B' has no member 'initViaP2'}} // Imported constructor. var b2 = B(viaP2: 3.14159, second: 3.14159) _ = p2m.init(viaP2:3.14159, second: 3.14159) } func testId(_ x: AnyObject) { x.perform!("foo:", with: x) // expected-warning{{no method declared with Objective-C selector 'foo:'}} // expected-warning @-1 {{result of call to function returning 'Unmanaged<AnyObject>?' is unused}} _ = x.performAdd(1, withValue: 2, withValue: 3, withValue2: 4) _ = x.performAdd!(1, withValue: 2, withValue: 3, withValue2: 4) _ = x.performAdd?(1, withValue: 2, withValue: 3, withValue2: 4) } class MySubclass : B { // Override a regular method. override func anotherMethodOnB() {} // Override a category method override func anotherCategoryMethod() {} } func getDescription(_ array: NSArray) { _ = array.description } // Method overriding with unfortunate ordering. func overridingTest(_ srs: SuperRefsSub) { let rs : RefedSub rs.overridden() } func almostSubscriptableValueMismatch(_ as1: AlmostSubscriptable, a: A) { as1[a] // expected-error{{value of type 'AlmostSubscriptable' has no subscripts}} } func almostSubscriptableKeyMismatch(_ bc: BadCollection, key: NSString) { // FIXME: We end up importing this as read-only due to the mismatch between // getter/setter element types. var _ : Any = bc[key] } func almostSubscriptableKeyMismatchInherited(_ bc: BadCollectionChild, key: String) { var value : Any = bc[key] bc[key] = value // expected-error{{cannot assign through subscript: subscript is get-only}} } func almostSubscriptableKeyMismatchInherited(_ roc: ReadOnlyCollectionChild, key: String) { var value : Any = roc[key] roc[key] = value // expected-error{{cannot assign through subscript: subscript is get-only}} } // Use of 'Class' via dynamic lookup. func classAnyObject(_ obj: NSObject) { _ = obj.myClass().description!() } // Protocol conformances class Wobbler : NSWobbling { @objc func wobble() { } func returnMyself() -> Self { return self } } extension Wobbler : NSMaybeInitWobble { // expected-error{{type 'Wobbler' does not conform to protocol 'NSMaybeInitWobble'}} } @objc class Wobbler2 : NSObject, NSWobbling { func wobble() { } func returnMyself() -> Self { return self } } extension Wobbler2 : NSMaybeInitWobble { // expected-error{{type 'Wobbler2' does not conform to protocol 'NSMaybeInitWobble'}} } func optionalMemberAccess(_ w: NSWobbling) { w.wobble() w.wibble() // expected-error{{value of optional type '(() -> Void)?' must be unwrapped to a value of type '() -> Void'}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let x = w[5]!! _ = x } func protocolInheritance(_ s: NSString) { var _: NSCoding = s } func ivars(_ hive: Hive) { var d = hive.bees.description hive.queen.description() // expected-error{{value of type 'Hive' has no member 'queen'}} } class NSObjectable : NSObjectProtocol { @objc var description : String { return "" } @objc(conformsToProtocol:) func conforms(to _: Protocol) -> Bool { return false } @objc(isKindOfClass:) func isKind(of aClass: AnyClass) -> Bool { return false } } // Properties with custom accessors func customAccessors(_ hive: Hive, bee: Bee) { markUsed(hive.isMakingHoney) markUsed(hive.makingHoney()) // expected-error{{cannot call value of non-function type 'Bool'}}{{28-30=}} hive.setMakingHoney(true) // expected-error{{value of type 'Hive' has no member 'setMakingHoney'}} _ = (hive.`guard` as AnyObject).description // okay _ = (hive.`guard` as AnyObject).description! // no-warning hive.`guard` = bee // no-warning } // instancetype/Dynamic Self invocation. func testDynamicSelf(_ queen: Bee, wobbler: NSWobbling) { var hive = Hive() // Factory method with instancetype result. var hive1 = Hive(queen: queen) hive1 = hive hive = hive1 // Instance method with instancetype result. var hive2 = hive!.visit() hive2 = hive hive = hive2 // Instance method on a protocol with instancetype result. var wobbler2 = wobbler.returnMyself()! var wobbler: NSWobbling = wobbler2 wobbler2 = wobbler // Instance method on a base class with instancetype result, called on the // class itself. // FIXME: This should be accepted. let baseClass: ObjCParseExtras.Base.Type = ObjCParseExtras.Base.returnMyself() // expected-error@-1 {{instance member 'returnMyself' cannot be used on type 'Base'; did you mean to use a value of this type instead?}} // expected-error@-2 {{cannot convert value of type 'Base?' to specified type 'Base.Type'}} } func testRepeatedProtocolAdoption(_ w: NSWindow) { _ = w.description } class ProtocolAdopter1 : FooProto { @objc var bar: CInt // no-warning init() { bar = 5 } } class ProtocolAdopter2 : FooProto { @objc var bar: CInt { get { return 42 } set { /* do nothing! */ } } } class ProtocolAdopterBad1 : FooProto { // expected-error {{type 'ProtocolAdopterBad1' does not conform to protocol 'FooProto'}} @objc var bar: Int = 0 // expected-note {{candidate has non-matching type 'Int'}} } class ProtocolAdopterBad2 : FooProto { // expected-error {{type 'ProtocolAdopterBad2' does not conform to protocol 'FooProto'}} let bar: CInt = 0 // expected-note {{candidate is not settable, but protocol requires it}} } class ProtocolAdopterBad3 : FooProto { // expected-error {{type 'ProtocolAdopterBad3' does not conform to protocol 'FooProto'}} var bar: CInt { // expected-note {{candidate is not settable, but protocol requires it}} return 42 } } @objc protocol RefinedFooProtocol : FooProto {} func testPreferClassMethodToCurriedInstanceMethod(_ obj: NSObject) { // FIXME: We shouldn't need the ": Bool" type annotation here. // <rdar://problem/18006008> let _: Bool = NSObject.isEqual(obj) _ = NSObject.isEqual(obj) as (NSObject?) -> Bool // no-warning } func testPropertyAndMethodCollision(_ obj: PropertyAndMethodCollision, rev: PropertyAndMethodReverseCollision) { obj.object = nil obj.object(obj, doSomething:#selector(getter: NSMenuItem.action)) type(of: obj).classRef = nil type(of: obj).classRef(obj, doSomething:#selector(getter: NSMenuItem.action)) rev.object = nil rev.object(rev, doSomething:#selector(getter: NSMenuItem.action)) type(of: rev).classRef = nil type(of: rev).classRef(rev, doSomething:#selector(getter: NSMenuItem.action)) var value: Any value = obj.protoProp() value = obj.protoPropRO() value = type(of: obj).protoClassProp() value = type(of: obj).protoClassPropRO() _ = value } func testPropertyAndMethodCollisionInOneClass( obj: PropertyAndMethodCollisionInOneClass, rev: PropertyAndMethodReverseCollisionInOneClass ) { obj.object = nil obj.object() type(of: obj).classRef = nil type(of: obj).classRef() rev.object = nil rev.object() type(of: rev).classRef = nil type(of: rev).classRef() } func testSubscriptAndPropertyRedeclaration(_ obj: SubscriptAndProperty) { _ = obj.x obj.x = 5 _ = obj.objectAtIndexedSubscript(5) // expected-error{{'objectAtIndexedSubscript' is unavailable: use subscripting}} obj.setX(5) // expected-error{{value of type 'SubscriptAndProperty' has no member 'setX'}} _ = obj[0] obj[1] = obj obj.setObject(obj, atIndexedSubscript: 2) // expected-error{{'setObject(_:atIndexedSubscript:)' is unavailable: use subscripting}} } func testSubscriptAndPropertyWithProtocols(_ obj: SubscriptAndPropertyWithProto) { _ = obj.x obj.x = 5 obj.setX(5) // expected-error{{value of type 'SubscriptAndPropertyWithProto' has no member 'setX'}} _ = obj[0] obj[1] = obj obj.setObject(obj, atIndexedSubscript: 2) // expected-error{{'setObject(_:atIndexedSubscript:)' is unavailable: use subscripting}} } func testProtocolMappingSameModule(_ obj: AVVideoCompositionInstruction, p: AVVideoCompositionInstructionProtocol) { markUsed(p.enablePostProcessing) markUsed(obj.enablePostProcessing) _ = obj.backgroundColor } func testProtocolMappingDifferentModules(_ obj: ObjCParseExtrasToo.ProtoOrClass, p: ObjCParseExtras.ProtoOrClass) { markUsed(p.thisIsTheProto) markUsed(obj.thisClassHasAnAwfulName) let _: ProtoOrClass? // expected-error{{'ProtoOrClass' is ambiguous for type lookup in this context}} _ = ObjCParseExtrasToo.ClassInHelper() // expected-error{{'ClassInHelper' cannot be constructed because it has no accessible initializers}} _ = ObjCParseExtrasToo.ProtoInHelper() _ = ObjCParseExtrasTooHelper.ClassInHelper() _ = ObjCParseExtrasTooHelper.ProtoInHelper() // expected-error{{'ProtoInHelper' cannot be constructed because it has no accessible initializers}} } func testProtocolClassShadowing(_ obj: ClassInHelper, p: ProtoInHelper) { let _: ObjCParseExtrasToo.ClassInHelper = obj let _: ObjCParseExtrasToo.ProtoInHelper = p } func testDealloc(_ obj: NSObject) { // dealloc is subsumed by deinit. obj.dealloc() // expected-error{{'dealloc()' is unavailable in Swift: use 'deinit' to define a de-initializer}} } func testConstantGlobals() { markUsed(MAX) markUsed(SomeImageName) markUsed(SomeNumber.description) MAX = 5 // expected-error{{cannot assign to value: 'MAX' is a 'let' constant}} SomeImageName = "abc" // expected-error{{cannot assign to value: 'SomeImageName' is a 'let' constant}} SomeNumber = nil // expected-error{{cannot assign to value: 'SomeNumber' is a 'let' constant}} } func testWeakVariable() { let _: AnyObject = globalWeakVar } class IncompleteProtocolAdopter : Incomplete, IncompleteOptional { // expected-error {{type 'IncompleteProtocolAdopter' cannot conform to protocol 'Incomplete' because it has requirements that cannot be satisfied}} @objc func getObject() -> AnyObject { return self } } func testNullarySelectorPieces(_ obj: AnyObject) { obj.foo(1, bar: 2, 3) // no-warning obj.foo(1, 2, bar: 3) // expected-error{{cannot invoke 'foo' with an argument list of type '(Int, Int, bar: Int)'}} } func testFactoryMethodAvailability() { _ = DeprecatedFactoryMethod() // expected-warning{{'init()' is deprecated: use something newer}} } func testRepeatedMembers(_ obj: RepeatedMembers) { obj.repeatedMethod() } // rdar://problem/19726164 class FooDelegateImpl : NSObject, FooDelegate { var _started = false var isStarted: Bool { get { return _started } @objc(setStarted:) set { _started = newValue } } } class ProtoAdopter : NSObject, ExplicitSetterProto, OptionalSetterProto { var foo: Any? // no errors about conformance var bar: Any? // no errors about conformance } func testUnusedResults(_ ur: UnusedResults) { _ = ur.producesResult() ur.producesResult() // expected-warning{{result of call to 'producesResult()' is unused}} } func testStrangeSelectors(obj: StrangeSelectors) { StrangeSelectors.cStyle(0, 1, 2) // expected-error{{type 'StrangeSelectors' has no member 'cStyle'}} _ = StrangeSelectors(a: 0, b: 0) // okay obj.empty(1, 2) // okay } func testProtocolQualified(_ obj: CopyableNSObject, cell: CopyableSomeCell, plainObj: NSObject, plainCell: SomeCell) { _ = obj as NSObject // expected-error {{'CopyableNSObject' (aka 'NSCopying & NSObjectProtocol') is not convertible to 'NSObject'}} // expected-note@-1 {{did you mean to use 'as!' to force downcast?}} {{11-13=as!}} _ = obj as NSObjectProtocol _ = obj as NSCopying _ = obj as SomeCell // expected-error {{'CopyableNSObject' (aka 'NSCopying & NSObjectProtocol') is not convertible to 'SomeCell'}} // expected-note@-1 {{did you mean to use 'as!' to force downcast?}} {{11-13=as!}} _ = cell as NSObject _ = cell as NSObjectProtocol _ = cell as NSCopying _ = cell as SomeCell _ = plainObj as CopyableNSObject // expected-error {{value of type 'NSObject' does not conform to 'CopyableNSObject' (aka 'NSCopying & NSObjectProtocol') in coercion}} _ = plainCell as CopyableSomeCell // expected-error {{value of type 'SomeCell' does not conform to 'CopyableSomeCell' (aka 'SomeCell & NSCopying') in coercion}} } extension Printing { func testImplicitWarnUnqualifiedAccess() { print() // expected-warning {{use of 'print' treated as a reference to instance method in class 'Printing'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} print(self) // expected-warning {{use of 'print' treated as a reference to instance method in class 'Printing'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} print(self, options: self) // no-warning } static func testImplicitWarnUnqualifiedAccess() { print() // expected-warning {{use of 'print' treated as a reference to class method in class 'Printing'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} print(self) // expected-warning {{use of 'print' treated as a reference to class method in class 'Printing'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} print(self, options: self) // no-warning } } // <rdar://problem/21979968> The "with array" initializers for NSCountedSet and NSMutable set should be properly disambiguated. func testSetInitializers() { let a: [AnyObject] = [NSObject()] let _ = NSCountedSet(array: a) let _ = NSMutableSet(array: a) } func testNSUInteger(_ obj: NSUIntegerTests, uint: UInt, int: Int) { obj.consumeUnsigned(uint) // okay obj.consumeUnsigned(int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} obj.consumeUnsigned(0, withTheNSUIntegerHere: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} obj.consumeUnsigned(0, withTheNSUIntegerHere: int) // okay obj.consumeUnsigned(uint, andAnother: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} obj.consumeUnsigned(uint, andAnother: int) // okay do { let x = obj.unsignedProducer() let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} } do { obj.unsignedProducer(uint, fromCount: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} obj.unsignedProducer(int, fromCount: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} let x = obj.unsignedProducer(uint, fromCount: int) // okay let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} } do { obj.normalProducer(uint, fromUnsigned: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} obj.normalProducer(int, fromUnsigned: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} let x = obj.normalProducer(int, fromUnsigned: uint) let _: String = x // expected-error {{cannot convert value of type 'Int' to specified type 'String'}} } let _: String = obj.normalProp // expected-error {{cannot convert value of type 'Int' to specified type 'String'}} let _: String = obj.unsignedProp // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} do { testUnsigned(int, uint) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} testUnsigned(uint, int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} let x = testUnsigned(uint, uint) // okay let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} } // NSNumber let num = NSNumber(value: uint) let _: String = num.uintValue // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} } class NewtypeUser { @objc func stringNewtype(a: SNTErrorDomain) {} // expected-error {{'SNTErrorDomain' has been renamed to 'ErrorDomain'}}{{31-45=ErrorDomain}} @objc func stringNewtypeOptional(a: SNTErrorDomain?) {} // expected-error {{'SNTErrorDomain' has been renamed to 'ErrorDomain'}}{{39-53=ErrorDomain}} @objc func intNewtype(a: MyInt) {} @objc func intNewtypeOptional(a: MyInt?) {} // expected-error {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} @objc func intNewtypeArray(a: [MyInt]) {} // expected-error {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} @objc func intNewtypeDictionary(a: [MyInt: NSObject]) {} // expected-error {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} @objc func cfNewtype(a: CFNewType) {} @objc func cfNewtypeArray(a: [CFNewType]) {} // expected-error {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} typealias MyTuple = (Int, AnyObject?) typealias MyNamedTuple = (a: Int, b: AnyObject?) @objc func blockWithTypealias(_ input: @escaping (MyTuple) -> MyInt) {} // expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2{{function types cannot be represented in Objective-C}} @objc func blockWithTypealiasWithNames(_ input: (MyNamedTuple) -> MyInt) {} // expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2{{function types cannot be represented in Objective-C}} } func testTypeAndValue() { _ = testStruct() _ = testStruct(value: 0) let _: (testStruct) -> Void = testStruct let _: () -> testStruct = testStruct.init let _: (CInt) -> testStruct = testStruct.init } // rdar://problem/34913507 func testBridgedTypedef(bt: BridgedTypedefs) { let _: Int = bt.arrayOfArrayOfStrings // expected-error{{'[[String]]'}} } func testBridgeFunctionPointerTypedefs(fptrTypedef: FPTypedef) { // See also print_clang_bool_bridging.swift. let _: Int = fptrTypedef // expected-error{{'@convention(c) (String) -> String'}} let _: Int = getFP() // expected-error{{'@convention(c) (String) -> String'}} } func testNonTrivialStructs() { _ = NonTrivialToCopy() // expected-error {{cannot find 'NonTrivialToCopy' in scope}} _ = NonTrivialToCopyWrapper() // expected-error {{cannot find 'NonTrivialToCopyWrapper' in scope}} _ = TrivialToCopy() // okay } func testErrorNewtype() { _ = ErrorNewType(3) // expected-error {{argument type 'Int' does not conform to expected type 'Error'}} // Since we import NSError as Error, and Error is not Hashable...we end up // losing the types for these functions, even though the above assignment // works. testErrorDictionary(3) // expected-error {{cannot convert value of type 'Int' to expected argument type '[AnyHashable : String]'}} testErrorDictionaryNewtype(3) // expected-error {{cannot convert value of type 'Int' to expected argument type '[AnyHashable : String]'}} } func testNSUIntegerNewtype() { let _: NSUIntegerNewType = NSUIntegerNewType(4) let _: UInt = NSUIntegerNewType(4).rawValue let _: NSUIntegerNewType = NSUIntegerNewType.constant let _: NSUIntegerSystemNewType = NSUIntegerSystemNewType(4) let _: Int = NSUIntegerSystemNewType(4).rawValue let _: NSUIntegerSystemNewType = NSUIntegerSystemNewType.constant }
apache-2.0
94987690edc11986da2653f739caef6f
36.223329
214
0.700245
3.941557
false
true
false
false
GraphKit/GraphKit
Tests/Entity/EntityPropertyStressTests.swift
5
5957
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import XCTest @testable import Graph class EntityPropertyStressTests: XCTestCase, GraphEntityDelegate { var saveExpectation: XCTestExpectation? var entityInsertExpectation: XCTestExpectation? var entityDeleteExpectation: XCTestExpectation? var propertyInsertExpception: XCTestExpectation? var propertyUpdateExpception: XCTestExpectation? var propertyDeleteExpception: XCTestExpectation? override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testPropertyStress() { saveExpectation = expectation(description: "[EntityPropertyStressTests Error: Graph save test failed.]") entityInsertExpectation = expectation(description: "[EntityPropertyStressTests Error: Entity insert test failed.]") let graph = Graph() let watch = Watch<Entity>(graph: graph).where(.type("T")) watch.delegate = self let entity = Entity("T") graph.async { [weak self] (success, error) in XCTAssertTrue(success) XCTAssertNil(error) self?.saveExpectation?.fulfill() } waitForExpectations(timeout: 5, handler: nil) var properties : [String] = [] for i in 0..<100 { properties.append("P\(i)") } watch.where(.exists(properties)) for i in 0..<100 { let property = "P\(i)" var value = i entity[property] = value XCTAssertEqual(value, entity[property] as? Int) saveExpectation = expectation(description: "[EntityPropertyStressTests Error: Graph save test failed.]") propertyInsertExpception = expectation(description: "[EntityPropertyStressTests Error: Property insert test failed.]") graph.async { [weak self] (success, error) in XCTAssertTrue(success) XCTAssertNil(error) self?.saveExpectation?.fulfill() } waitForExpectations(timeout: 5, handler: nil) value += 1 entity[property] = value XCTAssertEqual(value, entity[property] as? Int) saveExpectation = expectation(description: "[EntityPropertyStressTests Error: Graph save test failed.]") propertyUpdateExpception = expectation(description: "[EntityPropertyStressTests Error: Property update test failed.]") graph.async { [weak self] (success, error) in XCTAssertTrue(success) XCTAssertNil(error) self?.saveExpectation?.fulfill() } waitForExpectations(timeout: 5, handler: nil) entity[property] = nil XCTAssertNil(entity[property]) saveExpectation = expectation(description: "[EntityPropertyStressTests Error: Graph save test failed.]") propertyDeleteExpception = expectation(description: "[EntityPropertyStressTests Error: Property delete test failed.]") graph.async { [weak self] (success, error) in self?.saveExpectation?.fulfill() XCTAssertTrue(success) XCTAssertNil(error) } waitForExpectations(timeout: 5, handler: nil) } saveExpectation = expectation(description: "[EntityPropertyStressTests Error: Graph save test failed.]") entityDeleteExpectation = expectation(description: "[EntityPropertyStressTests Error: Entity delete test failed.]") entity.delete() graph.async { [weak self] (success, error) in XCTAssertTrue(success) XCTAssertNil(error) self?.saveExpectation?.fulfill() } waitForExpectations(timeout: 5, handler: nil) } func graph(_ graph: Graph, inserted entity: Entity, source: GraphSource) { XCTAssertTrue("T" == entity.type) XCTAssertTrue(0 < entity.id.count) XCTAssertEqual(0, entity.properties.count) entityInsertExpectation?.fulfill() } func graph(_ graph: Graph, deleted entity: Entity, source: GraphSource) { XCTAssertTrue("T" == entity.type) XCTAssertTrue(0 < entity.id.count) XCTAssertEqual(0, entity.properties.count) entityDeleteExpectation?.fulfill() } func graph(_ graph: Graph, entity: Entity, added property: String, with value: Any, source: GraphSource) { XCTAssertTrue("T" == entity.type) XCTAssertTrue(0 < entity.id.count) propertyInsertExpception?.fulfill() } func graph(_ graph: Graph, entity: Entity, updated property: String, with value: Any, source: GraphSource) { XCTAssertTrue("T" == entity.type) XCTAssertTrue(0 < entity.id.count) propertyUpdateExpception?.fulfill() } func graph(_ graph: Graph, entity: Entity, removed property: String, with value: Any, source: GraphSource) { XCTAssertTrue("T" == entity.type) XCTAssertTrue(0 < entity.id.count) propertyDeleteExpception?.fulfill() } }
agpl-3.0
afced4bcf57f92198d2ba52f75f5bfa9
33.633721
124
0.689777
4.712816
false
true
false
false
AsyncNinja/AsyncNinja
Sources/AsyncNinja/appleOS_ExecutionContext.swift
1
14425
// // Copyright (c) 2016-2017 Anton Mironov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom // the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) import Foundation public extension ExecutionContext where Self: NSObject { /// a getter that could be provided as customization point typealias CustomGetter<T> = (Self) -> T? /// a setter that could be provided as customization point typealias CustomSetter<T> = (Self, T) -> Void /// makes an `UpdatableProperty<T?>` for specified key path. /// /// `UpdatableProperty` is a kind of `Producer` so you can: /// * subscribe for updates /// * transform using `map`, `flatMap`, `filter`, `debounce`, `distinct`, ... /// * update manually with `update()` method /// * bind `Channel` to an `UpdatableProperty` using `Channel.bind` /// /// - Parameter keyPath: to observe. /// /// **Make sure that keyPath refers to KVO-compliant property**. /// * Make sure that properties defined in swift have dynamic attribute. /// * Make sure that methods `class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String>` /// return correct values for read-only properties /// - Parameter originalExecutor: `Executor` you calling this method on. /// Specifying this argument will allow to perform syncronous executions /// on `strictAsync: false` `Executor`s. /// Use default value or nil if you are not sure about an `Executor` /// you calling this method on. /// - Parameter observationSession: is an object that helps to control observation /// - Parameter allowSettingSameValue: set to true if you want /// to set a new value event if it is equal to an old one /// - Parameter channelBufferSize: size of the buffer within returned channel /// - Parameter customGetter: provides a custom getter to use instead of value(forKeyPath:) call /// - Parameter customSetter: provides a custom getter to use instead of setValue(_: forKeyPath:) call /// - Returns: an `UpdatableProperty<T?>` bound to observe and update specified keyPath func updatable<T>( forKeyPath keyPath: String, from originalExecutor: Executor?, observationSession: ObservationSession? = nil, allowSettingSameValue: Bool = false, channelBufferSize: Int = 1, customGetter: CustomGetter<T?>? = nil, customSetter: CustomSetter<T?>? = nil ) -> ProducerProxy<T?, Void> { return updatable(forKeyPath: keyPath, executor: executor, from: originalExecutor, observationSession: observationSession, allowSettingSameValue: allowSettingSameValue, channelBufferSize: channelBufferSize, customGetter: customGetter, customSetter: customSetter) } /// makes an `UpdatableProperty<T>` for specified key path. /// /// `UpdatableProperty` is a kind of `Producer` so you can: /// * subscribe for updates /// * transform using `map`, `flatMap`, `filter`, `debounce`, `distinct`, ... /// * update manually with `update()` method /// * bind `Channel` to an `UpdatableProperty` using `Channel.bind` /// /// - Parameter keyPath: to observe. /// /// **Make sure that keyPath refers to KVO-compliant property**. /// * Make sure that properties defined in swift have dynamic attribute. /// * Make sure that methods `class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String>` /// return correct values for read-only properties /// - Parameter onNone: is a policy of handling `None` (or `nil`) value /// that can arrive from Key-Value observation. /// - Parameter executor: to subscribe and update value on /// - Parameter originalExecutor: `Executor` you calling this method on. /// Specifying this argument will allow to perform syncronous executions /// on `strictAsync: false` `Executor`s. /// Use default value or nil if you are not sure about an `Executor` /// you calling this method on. /// - Parameter observationSession: is an object that helps to control observation /// - Parameter allowSettingSameValue: set to true if you want /// to set a new value event if it is equal to an old one /// - Parameter channelBufferSize: size of the buffer within returned channel /// - Parameter customGetter: provides a custom getter to use instead of value(forKeyPath:) call /// - Parameter customSetter: provides a custom getter to use instead of setValue(_: forKeyPath:) call /// - Returns: an `UpdatableProperty<T>` bound to observe and update specified keyPath func updatable<T>( forKeyPath keyPath: String, onNone: UpdateWithNoneHandlingPolicy<T>, from originalExecutor: Executor?, observationSession: ObservationSession? = nil, allowSettingSameValue: Bool = false, channelBufferSize: Int = 1, customGetter: CustomGetter<T>? = nil, customSetter: CustomSetter<T>? = nil ) -> ProducerProxy<T, Void> { return updatable(forKeyPath: keyPath, onNone: onNone, executor: executor, from: originalExecutor, observationSession: observationSession, allowSettingSameValue: allowSettingSameValue, channelBufferSize: channelBufferSize, customGetter: customGetter, customSetter: customSetter) } /// makes an `Updating<T?>` for specified key path. /// /// `Updating` is a kind of `Channel` so you can: /// * subscribe for updates /// * transform using `map`, `flatMap`, `filter`, `debounce`, `distinct`, ... /// /// - Parameter keyPath: to observe. /// /// **Make sure that keyPath refers to KVO-compliant property**. /// * Make sure that properties defined in swift have dynamic attribute. /// * Make sure that methods `class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String>` /// return correct values for read-only properties /// - Parameter originalExecutor: `Executor` you calling this method on. /// Specifying this argument will allow to perform syncronous executions /// on `strictAsync: false` `Executor`s. /// Use default value or nil if you are not sure about an `Executor` /// you calling this method on. /// - Parameter observationSession: is an object that helps to control observation /// - Parameter channelBufferSize: size of the buffer within returned channel /// - Parameter customGetter: provides a custom getter to use instead of value(forKeyPath:) call /// - Returns: an `Updating<T?>` bound to observe and update specified keyPath func updating<T>( forKeyPath keyPath: String, from originalExecutor: Executor?, observationSession: ObservationSession? = nil, channelBufferSize: Int = 1, customGetter: CustomGetter<T?>? = nil ) -> Channel<T?, Void> { return updating(forKeyPath: keyPath, executor: executor, from: originalExecutor, observationSession: observationSession, channelBufferSize: channelBufferSize, customGetter: customGetter) } /// makes an `Updating<T>` for specified key path. /// /// `Updating` is a kind of `Channel` so you can: /// * subscribe for updates /// * transform using `map`, `flatMap`, `filter`, `debounce`, `distinct`, ... /// /// - Parameter keyPath: to observe. /// /// **Make sure that keyPath refers to KVO-compliant property**. /// * Make sure that properties defined in swift have dynamic attribute. /// * Make sure that methods `class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String>` /// return correct values for read-only properties /// - Parameter onNone: is a policy of handling `None` (or `nil`) value /// that can arrive from Key-Value observation. /// - Parameter originalExecutor: `Executor` you calling this method on. /// Specifying this argument will allow to perform syncronous executions /// on `strictAsync: false` `Executor`s. /// Use default value or nil if you are not sure about an `Executor` /// you calling this method on. /// - Parameter observationSession: is an object that helps to control observation /// - Parameter channelBufferSize: size of the buffer within returned channel /// - Parameter customGetter: provides a custom getter to use instead of value(forKeyPath:) call /// - Returns: an `Updating<T>` bound to observe and update specified keyPath func updating<T>( forKeyPath keyPath: String, onNone: UpdateWithNoneHandlingPolicy<T>, from originalExecutor: Executor?, observationSession: ObservationSession? = nil, channelBufferSize: Int = 1, customGetter: CustomGetter<T>? = nil ) -> Channel<T, Void> { return updating(forKeyPath: keyPath, onNone: onNone, executor: executor, from: originalExecutor, observationSession: observationSession, channelBufferSize: channelBufferSize, customGetter: customGetter) } /// makes an `Updating<(old: T?, new: T?)>` for specified key path. /// With an `Updating` you can /// * subscribe for updates /// * transform `Updating` as any `Channel` (`map`, `flatMap`, `filter`, `debounce`, `distinct`, ...) /// /// - Parameter keyPath: to observe. /// /// **Make sure that keyPath refers to KVO-compliant property**. /// * Make sure that properties defined in swift have dynamic attribute. /// * Make sure that methods `class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String>` /// return correct values for read-only properties /// - Parameter originalExecutor: `Executor` you calling this method on. /// Specifying this argument will allow to perform syncronous executions /// on `strictAsync: false` `Executor`s. /// Use default value or nil if you are not sure about an `Executor` /// you calling this method on. /// - Parameter observationSession: is an object that helps to control observation /// - Parameter channelBufferSize: size of the buffer within returned channel /// - Returns: an `Updating<(old: T?, new: T?)>` bound to observe and update specified keyPath func updatingOldAndNew<T>( forKeyPath keyPath: String, from originalExecutor: Executor? = nil, observationSession: ObservationSession? = nil, channelBufferSize: Int = 1 ) -> Channel<(old: T?, new: T?), Void> { return updatingOldAndNew(forKeyPath: keyPath, executor: executor, observationSession: observationSession, channelBufferSize: channelBufferSize) } /// makes an `Updating<[NSKeyValueChangeKey: Any]>` for specified key path. /// With an `Updating` you can /// * subscribe for updates /// * transform `Updating` as any `Channel` (`map`, `flatMap`, `filter`, `debounce`, `distinct`, ...) /// /// - Parameter keyPath: to observe. /// /// **Make sure that keyPath refers to KVO-compliant property**. /// * Make sure that properties defined in swift have dynamic attribute. /// * Make sure that methods `class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String>` /// return correct values for read-only properties /// - Parameter originalExecutor: `Executor` you calling this method on. /// Specifying this argument will allow to perform syncronous executions /// on `strictAsync: false` `Executor`s. /// Use default value or nil if you are not sure about an `Executor` /// you calling this method on. /// - Parameter observationSession: is an object that helps to control observation /// - Parameter channelBufferSize: size of the buffer within returned channel /// - Returns: an `Updating<[NSKeyValueChangeKey: Any]>` bound to observe and update specified keyPath func updatingChanges( forKeyPath keyPath: String, from originalExecutor: Executor? = nil, options: NSKeyValueObservingOptions, observationSession: ObservationSession? = nil, channelBufferSize: Int = 1 ) -> Channel<[NSKeyValueChangeKey: Any], Void> { return updatingChanges(forKeyPath: keyPath, executor: executor, from: originalExecutor, options: options, observationSession: observationSession, channelBufferSize: channelBufferSize) } /// Makes a sink that wraps specified setter /// /// - Parameter setter: to use with sink /// - Returns: constructed sink func sink<T>(setter: @escaping CustomSetter<T>) -> Sink<T, Void> { return sink(executor: executor, setter: setter) } } #endif
mit
017eaf8ac795fb17eddfcd843903320a
51.075812
114
0.650052
4.858538
false
false
false
false
berzerker-io/ledger-ios
LedgerKit/Logger.swift
1
5036
// // Logger.swift // Ledger // // Created by Benoit Sarrazin on 2016-05-25. // Copyright © 2016 Berzerker IO. All rights reserved. // import Foundation import SwiftyBeaver /// <#Description#> public class Logger { // MARK: Properties private static let consoleDestination = ConsoleDestination() private static let fileDestination = FileDestination() // MARK: Configuration /// <#Description#> public static var asynchronous = true { didSet { configure() } } /// <#Description#> public static var fileURL: NSURL? { didSet { configure() } } /** <#Description#> - Debug: <#Debug description#> - Error: <#Error description#> - Info: <#Info description#> - Verbose: <#Verbose description#> - Warning: <#Warning description#> */ public enum Level { case Debug case Error case Info case Verbose case Warning } /// <#Description#> public static var minLevel: Level = .Warning { didSet { configure() } } private class func configure() { switch minLevel { case .Debug: consoleDestination.minLevel = .Debug fileDestination.minLevel = .Debug case .Error: consoleDestination.minLevel = .Error fileDestination.minLevel = .Error case .Info: consoleDestination.minLevel = .Info fileDestination.minLevel = .Info case .Verbose: consoleDestination.minLevel = .Verbose fileDestination.minLevel = .Verbose case .Warning: consoleDestination.minLevel = .Warning fileDestination.minLevel = .Warning } consoleDestination.asynchronously = asynchronous fileDestination.asynchronously = asynchronous if !SwiftyBeaver.destinations.contains(consoleDestination) { SwiftyBeaver.addDestination(consoleDestination) } if let url = fileURL where url.fileURL { fileDestination.logFileURL = url if !SwiftyBeaver.destinations.contains(fileDestination) { SwiftyBeaver.addDestination(fileDestination) } } else { if SwiftyBeaver.destinations.contains(fileDestination) { SwiftyBeaver.removeDestination(fileDestination) } } } /** <#Description#> */ public class func reset() { asynchronous = true minLevel = .Warning fileURL = nil } // MARK: Logging Methods /** <#Description#> - parameter message: <#message description#> - parameter path: <#path description#> - parameter function: <#function description#> - parameter line: <#line description#> */ public class func debug(@autoclosure message: () -> Any, _ path: String = #file, _ function: String = #function, _ line: Int = #line) { SwiftyBeaver.debug(message, path, function, line: line) } /** <#Description#> - parameter message: <#message description#> - parameter path: <#path description#> - parameter function: <#function description#> - parameter line: <#line description#> */ public class func error(@autoclosure message: () -> Any, _ path: String = #file, _ function: String = #function, _ line: Int = #line) { SwiftyBeaver.error(message, path, function, line: line) } /** <#Description#> - parameter message: <#message description#> - parameter path: <#path description#> - parameter function: <#function description#> - parameter line: <#line description#> */ public class func info(@autoclosure message: () -> Any, _ path: String = #file, _ function: String = #function, _ line: Int = #line) { SwiftyBeaver.info(message, path, function, line: line) } /** <#Description#> - parameter message: <#message description#> - parameter path: <#path description#> - parameter function: <#function description#> - parameter line: <#line description#> */ public class func verbose(@autoclosure message: () -> Any, _ path: String = #file, _ function: String = #function, _ line: Int = #line) { SwiftyBeaver.verbose(message, path, function, line: line) } /** <#Description#> - parameter message: <#message description#> - parameter path: <#path description#> - parameter function: <#function description#> - parameter line: <#line description#> */ public class func warning(@autoclosure message: () -> Any, _ path: String = #file, _ function: String = #function, _ line: Int = #line) { SwiftyBeaver.warning(message, path, function, line: line) } }
unlicense
c0f7c05b3751a2cb9a27c9d4478d33ab
28.617647
141
0.574578
4.960591
false
false
false
false
glyuck/GlyuckDataGrid
Example/Tests/Cells/DataGridViewBaseCellSpec.swift
1
1273
// // DataGridViewBaseCellSpec.swift // GlyuckDataGrid // // Created by Vladimir Lyukov on 12/08/15. // Copyright © 2015 CocoaPods. All rights reserved. // import Quick import Nimble import GlyuckDataGrid class DataGridViewBaseCellSpec: QuickSpec { override func spec() { var sut: DataGridViewBaseCell! beforeEach { sut = DataGridViewBaseCell(frame: CGRect(x: 0, y: 0, width: 100, height: 60)) } describe("textLabel") { it("should not be nil") { expect(sut.textLabel).notTo(beNil()) } it("should be subview of contentView") { expect(sut.textLabel.superview) === sut.contentView } it("should resize along with cell with respect to cell.textLabelInsets") { sut.textLabel.text = "" // Ensure text label is initialized when tests are started sut.textLabelInsets = UIEdgeInsets(top: 1, left: 2, bottom: 3, right: 4) sut.frame = CGRect(x: 0, y: 0, width: sut.frame.width * 2, height: sut.frame.height / 2) sut.layoutIfNeeded() expect(sut.textLabel.frame) == UIEdgeInsetsInsetRect(sut.bounds, sut.textLabelInsets) } } } }
mit
2be7961c499b3d9128b0334282e9ff59
30.02439
104
0.591195
4.254181
false
false
false
false
rdhiggins/PythonMacros
PythonMacros/PythonObject.swift
1
5343
// // PythonObject.swift // MIT License // // Copyright (c) 2016 Spazstik Software, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation /// A Class that holds a reference to a PyObject reference. This reference /// is a UnsafeMutablePointer<PyObject>. This reference must be released when /// the PythonObject is deleted. /// /// This is used to manage PyObject references when interacting with the CPython /// runtime. class PythonObject { /// Property containing the reference to the PyObject let object: UnsafeMutablePointer<PyObject> /// Initialization method. Passed the UnsafeMutablePointer<PyObject> to /// manage. /// /// - parameter object: UnsafeMutablePointer<PyObject> to manage init(object: UnsafeMutablePointer<PyObject>) { self.object = object Py_IncRef(self.object) } /// deinit needs to decrement the CPython reference count for the /// object. deinit { Py_DecRef(object) } /// Method used to lookup a attribute of the managed PyObject. /// /// - parameter attribute: A string containing the name of the /// attribute to lookup. /// - returns: A string of the attribute contents requested on /// success. func getAttrString(_ attribute: String) -> String? { let pyOutput = PyObject_GetAttrString(object, attribute) let output = String(validatingUTF8: PyUnicode_AsUTF8(pyOutput)) Py_DecRef(pyOutput) return output } /// Method used to set a attribute on the manager PyObject. /// /// - parameter attribute: A string containing the name of the attribute. /// - parameter value: A string containing the new value to set the /// attribute to. func setAttrString(_ attribute: String, value: String) { PyObject_SetAttrString(object, attribute, PyUnicode_DecodeUTF8(value, value.utf8.count, nil)) } /// A method used to get a PythonObject reference of a PyObject /// attribute. /// /// - parameter attribute: A string containing the attribute name to /// get the value of. /// - returns: A PythonObject reference func getAttr(_ attribute: String) -> PythonObject { let ref = PyObject_GetAttr(object, PyUnicode_DecodeUTF8(attribute, attribute.utf8.count, nil)) let newObject = PythonObject(object: ref!) Py_DecRef(ref) return newObject } /// A method used to convert the PyObject to a string. /// /// returns: Optional string contents to the managed PyObject func toString() -> String? { let ref = PyObject_Str(object) let output = String(validatingUTF8: PyUnicode_AsUTF8(ref)) Py_DecRef(ref) return output } /// A method used to return the Float value of the managed PyObject. /// /// returns: Float value of the PyObject func toFloat() -> Float { return Float(PyFloat_AsDouble(object)) } /// A method used to return the Double value of the managed PyObject. /// /// returns: Double value of the PyObject func toDouble() -> Double { return PyFloat_AsDouble(object) } /// A method used to return the Int value of the managed PyObject. /// /// returns: Int value of the PyObject func toInt() -> Int { return Int(PyLong_AsLong(object)) } /// A method used to return the Int64 value of the managed PyObject. /// /// returns: Int64 value of the PyObject func toInt64() -> Int64 { return Int64(PyLong_AsLong(object)) } } extension PythonObject: CustomDebugStringConvertible, CustomStringConvertible { var debugDescription: String { return self.customDescription() } var description: String { return self.customDescription() } fileprivate func customDescription() -> String { if let s = self.toString() { return "python object: \(s)" } return "pythong object: unknown" } }
mit
1e0d663045652fdb4d044f1bb256eff5
30.615385
81
0.635411
4.715799
false
false
false
false
muccy/Ferrara
Source/Match.swift
1
932
import Foundation /// How two objects match /// /// - none: No match /// - change: Partial match (same object has changed) /// - equal: Complete match public enum Match: String, CustomDebugStringConvertible { case none = "❌" case change = "🔄" case equal = "✅" public var debugDescription: String { return self.rawValue } } /// The way two objects are compared to spot no match, partial match or complete match public protocol Matchable { func match(with object: Any) -> Match } public extension Matchable where Self: Equatable { public func match(with object: Any) -> Match { if let object = object as? Self { return self == object ? .equal : .none } return .none } } public extension Equatable where Self: Matchable { public static func ==(lhs: Self, rhs: Self) -> Bool { return lhs.match(with: rhs) == .equal } }
mit
5a62bd6d0c446bbfa84a638df9f4411d
24
86
0.624865
4.282407
false
false
false
false
andr3a88/TryNetworkLayer
TryNetworkLayer/Models/GHUser.swift
1
1693
// // GHItems.swift // // Created by Andrea Stevanato on 22/08/2017 // Copyright (c) . All rights reserved. // import Foundation import Realm import RealmSwift public final class GHUser: Object, Codable { // MARK: Declaration for string constants to be used to decode and also serialize. enum CodingKeys: String, CodingKey { case organizationsUrl = "organizations_url" case score = "score" case reposUrl = "repos_url" case htmlUrl = "html_url" case gravatarId = "gravatar_id" case avatarUrl = "avatar_url" case type = "type" case login = "login" case followersUrl = "followers_url" case id = "id" case subscriptionsUrl = "subscriptions_url" case receivedEventsUrl = "received_events_url" case url = "url" } // MARK: Properties @objc dynamic public var organizationsUrl: String? @objc dynamic public var score: Float = 0 @objc dynamic public var reposUrl: String? @objc dynamic public var htmlUrl: String? @objc dynamic public var gravatarId: String? @objc dynamic public var avatarUrl: String? @objc dynamic public var type: String? @objc dynamic public var login: String = "" @objc dynamic public var followersUrl: String? @objc dynamic public var id: Int = 0 @objc dynamic public var subscriptionsUrl: String? @objc dynamic public var receivedEventsUrl: String? @objc dynamic public var url: String? // MARK: Primary Key override public static func primaryKey() -> String? { "id" } // MARK: Init required public init() { super.init() } }
mit
eec24a349513e3e8d514b73df7c08e4b
27.694915
86
0.637921
4.307888
false
false
false
false
lyp1992/douyu-Swift
YPTV/Pods/Kingfisher/Sources/CacheSerializer.swift
28
3729
// // CacheSerializer.swift // Kingfisher // // Created by Wei Wang on 2016/09/02. // // Copyright (c) 2018 Wei Wang <[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 /// An `CacheSerializer` would be used to convert some data to an image object for /// retrieving from disk cache and vice versa for storing to disk cache. public protocol CacheSerializer { /// Get the serialized data from a provided image /// and optional original data for caching to disk. /// /// /// - parameter image: The image needed to be serialized. /// - parameter original: The original data which is just downloaded. /// If the image is retrieved from cache instead of /// downloaded, it will be `nil`. /// /// - returns: A data which will be stored to cache, or `nil` when no valid /// data could be serialized. func data(with image: Image, original: Data?) -> Data? /// Get an image deserialized from provided data. /// /// - parameter data: The data from which an image should be deserialized. /// - parameter options: Options for deserialization. /// /// - returns: An image deserialized or `nil` when no valid image /// could be deserialized. func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? } /// `DefaultCacheSerializer` is a basic `CacheSerializer` used in default cache of /// Kingfisher. It could serialize and deserialize PNG, JEPG and GIF images. For /// image other than these formats, a normalized `pngRepresentation` will be used. public struct DefaultCacheSerializer: CacheSerializer { public static let `default` = DefaultCacheSerializer() private init() {} public func data(with image: Image, original: Data?) -> Data? { let imageFormat = original?.kf.imageFormat ?? .unknown let data: Data? switch imageFormat { case .PNG: data = image.kf.pngRepresentation() case .JPEG: data = image.kf.jpegRepresentation(compressionQuality: 1.0) case .GIF: data = image.kf.gifRepresentation() case .unknown: data = original ?? image.kf.normalized.kf.pngRepresentation() } return data } public func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? { let options = options ?? KingfisherEmptyOptionsInfo return Kingfisher<Image>.image( data: data, scale: options.scaleFactor, preloadAllAnimationData: options.preloadAllAnimationData, onlyFirstFrame: options.onlyLoadFirstFrame) } }
mit
5632d832d97baa7beb67be862057fd40
41.862069
84
0.680343
4.708333
false
false
false
false
IDAGIO/AudioPlayer
AudioPlayer/AudioPlayer/Reachability.swift
2
12677
/* Copyright (c) 2014, Ashley Mills All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import SystemConfiguration import Foundation public let ReachabilityChangedNotification = "ReachabilityChangedNotification" func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutablePointer<Void>) { let reachability = Unmanaged<Reachability>.fromOpaque(COpaquePointer(info)).takeUnretainedValue() dispatch_async(dispatch_get_main_queue()) { reachability.reachabilityChanged(flags) } } public class Reachability: NSObject { public typealias NetworkReachable = (Reachability) -> () public typealias NetworkUnreachable = (Reachability) -> () public enum NetworkStatus: CustomStringConvertible { case NotReachable, ReachableViaWiFi, ReachableViaWWAN public var description: String { switch self { case .ReachableViaWWAN: return "Cellular" case .ReachableViaWiFi: return "WiFi" case .NotReachable: return "No Connection" } } } // MARK: - *** Public properties *** public var whenReachable: NetworkReachable? public var whenUnreachable: NetworkUnreachable? public var reachableOnWWAN: Bool public var notificationCenter = NSNotificationCenter.defaultCenter() public var currentReachabilityStatus: NetworkStatus { if isReachable() { if isReachableViaWiFi() { return .ReachableViaWiFi } if isRunningOnDevice { return .ReachableViaWWAN } } return .NotReachable } public var currentReachabilityString: String { return "\(currentReachabilityStatus)" } // MARK: - *** Initialisation methods *** required public init(reachabilityRef: SCNetworkReachability?) { reachableOnWWAN = true self.reachabilityRef = reachabilityRef } public convenience init(hostname: String) { let nodename = (hostname as NSString).UTF8String let ref = SCNetworkReachabilityCreateWithName(nil, nodename) self.init(reachabilityRef: ref) } public class func reachabilityForInternetConnection() -> Reachability { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let ref = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) } return Reachability(reachabilityRef: ref) } public class func reachabilityForLocalWiFi() -> Reachability { var localWifiAddress: sockaddr_in = sockaddr_in(sin_len: __uint8_t(0), sin_family: sa_family_t(0), sin_port: in_port_t(0), sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) localWifiAddress.sin_len = UInt8(sizeofValue(localWifiAddress)) localWifiAddress.sin_family = sa_family_t(AF_INET) // IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0 let address: UInt32 = 0xA9FE0000 localWifiAddress.sin_addr.s_addr = in_addr_t(address.bigEndian) let ref = withUnsafePointer(&localWifiAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) } return Reachability(reachabilityRef: ref) } // MARK: - *** Notifier methods *** public func startNotifier() -> Bool { if notifierRunning { return true } var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque()) if SCNetworkReachabilitySetCallback(reachabilityRef!, callback, &context) { if SCNetworkReachabilitySetDispatchQueue(reachabilityRef!, reachabilitySerialQueue) { notifierRunning = true return true } } stopNotifier() return false } public func stopNotifier() { if let reachabilityRef = reachabilityRef { SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil) } notifierRunning = false } // MARK: - *** Connection test methods *** public func isReachable() -> Bool { return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in return self.isReachableWithFlags(flags) }) } public func isReachableViaWWAN() -> Bool { if isRunningOnDevice { return isReachableWithTest() { flags -> Bool in // Check we're REACHABLE if self.isReachable(flags) { // Now, check we're on WWAN if self.isOnWWAN(flags) { return true } } return false } } return false } public func isReachableViaWiFi() -> Bool { return isReachableWithTest() { flags -> Bool in // Check we're reachable if self.isReachable(flags) { if self.isRunningOnDevice { // Check we're NOT on WWAN if self.isOnWWAN(flags) { return false } } return true } return false } } // MARK: - *** Private methods *** private var isRunningOnDevice: Bool = { #if (arch(i386) || arch(x86_64)) && os(iOS) return false #else return true #endif }() private var notifierRunning = false private var reachabilityRef: SCNetworkReachability? private let reachabilitySerialQueue = dispatch_queue_create("uk.co.ashleymills.reachability", DISPATCH_QUEUE_SERIAL) private func reachabilityChanged(flags: SCNetworkReachabilityFlags) { if isReachableWithFlags(flags) { if let block = whenReachable { block(self) } } else { if let block = whenUnreachable { block(self) } } notificationCenter.postNotificationName(ReachabilityChangedNotification, object:self) } private func isReachableWithFlags(flags: SCNetworkReachabilityFlags) -> Bool { let reachable = isReachable(flags) if !reachable { return false } if isConnectionRequiredOrTransient(flags) { return false } if isRunningOnDevice { if isOnWWAN(flags) && !reachableOnWWAN { // We don't want to connect when on 3G. return false } } return true } private func isReachableWithTest(test: (SCNetworkReachabilityFlags) -> (Bool)) -> Bool { if let reachabilityRef = reachabilityRef { var flags = SCNetworkReachabilityFlags(rawValue: 0) let gotFlags = withUnsafeMutablePointer(&flags) { SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0)) } if gotFlags { return test(flags) } } return false } // WWAN may be available, but not active until a connection has been established. // WiFi may require a connection for VPN on Demand. private func isConnectionRequired() -> Bool { return connectionRequired() } private func connectionRequired() -> Bool { return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in return self.isConnectionRequired(flags) }) } // Dynamic, on demand connection? private func isConnectionOnDemand() -> Bool { return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in return self.isConnectionRequired(flags) && self.isConnectionOnTrafficOrDemand(flags) }) } // Is user intervention required? private func isInterventionRequired() -> Bool { return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in return self.isConnectionRequired(flags) && self.isInterventionRequired(flags) }) } private func isOnWWAN(flags: SCNetworkReachabilityFlags) -> Bool { #if os(iOS) return flags.contains(.IsWWAN) #else return false #endif } private func isReachable(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.Reachable) } private func isConnectionRequired(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.ConnectionRequired) } private func isInterventionRequired(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.InterventionRequired) } private func isConnectionOnTraffic(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.ConnectionOnTraffic) } private func isConnectionOnDemand(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.ConnectionOnDemand) } func isConnectionOnTrafficOrDemand(flags: SCNetworkReachabilityFlags) -> Bool { return !flags.intersect([.ConnectionOnTraffic, .ConnectionOnDemand]).isEmpty } private func isTransientConnection(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.TransientConnection) } private func isLocalAddress(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.IsLocalAddress) } private func isDirect(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.IsDirect) } private func isConnectionRequiredOrTransient(flags: SCNetworkReachabilityFlags) -> Bool { let testcase:SCNetworkReachabilityFlags = [.ConnectionRequired, .TransientConnection] return flags.intersect(testcase) == testcase } private var reachabilityFlags: SCNetworkReachabilityFlags { if let reachabilityRef = reachabilityRef { var flags = SCNetworkReachabilityFlags(rawValue: 0) let gotFlags = withUnsafeMutablePointer(&flags) { SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0)) } if gotFlags { return flags } } return [] } override public var description: String { var W: String if isRunningOnDevice { W = isOnWWAN(reachabilityFlags) ? "W" : "-" } else { W = "X" } let R = isReachable(reachabilityFlags) ? "R" : "-" let c = isConnectionRequired(reachabilityFlags) ? "c" : "-" let t = isTransientConnection(reachabilityFlags) ? "t" : "-" let i = isInterventionRequired(reachabilityFlags) ? "i" : "-" let C = isConnectionOnTraffic(reachabilityFlags) ? "C" : "-" let D = isConnectionOnDemand(reachabilityFlags) ? "D" : "-" let l = isLocalAddress(reachabilityFlags) ? "l" : "-" let d = isDirect(reachabilityFlags) ? "d" : "-" return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" } deinit { stopNotifier() reachabilityRef = nil whenReachable = nil whenUnreachable = nil } }
mit
cdc4c87ff7c2f2d8b798c1fca9096ff6
32.625995
196
0.637454
5.577211
false
false
false
false
ncalexan/firefox-ios
Sync/SyncTelemetry.swift
2
11389
/* 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 Account import Storage import SwiftyJSON import Telemetry import Deferred fileprivate let log = Logger.syncLogger public let PrefKeySyncEvents = "sync.telemetry.events" public enum SyncReason: String { case startup = "startup" case scheduled = "scheduled" case backgrounded = "backgrounded" case user = "user" case syncNow = "syncNow" case didLogin = "didLogin" case push = "push" } public enum SyncPingReason: String { case shutdown = "shutdown" case schedule = "schedule" case idChanged = "idchanged" } public protocol Stats { func hasData() -> Bool } private protocol DictionaryRepresentable { func asDictionary() -> [String: Any] } public struct SyncUploadStats: Stats { var sent: Int = 0 var sentFailed: Int = 0 public func hasData() -> Bool { return sent > 0 || sentFailed > 0 } } extension SyncUploadStats: DictionaryRepresentable { func asDictionary() -> [String: Any] { return [ "sent": sent, "sentFailed": sentFailed ] } } public struct SyncDownloadStats: Stats { var applied: Int = 0 var succeeded: Int = 0 var failed: Int = 0 var newFailed: Int = 0 var reconciled: Int = 0 public func hasData() -> Bool { return applied > 0 || succeeded > 0 || failed > 0 || newFailed > 0 || reconciled > 0 } } extension SyncDownloadStats: DictionaryRepresentable { func asDictionary() -> [String: Any] { return [ "applied": applied, "succeeded": succeeded, "failed": failed, "newFailed": newFailed, "reconciled": reconciled ] } } public struct ValidationStats: Stats, DictionaryRepresentable { let problems: [ValidationProblem] let took: Int64 let checked: Int? public func hasData() -> Bool { return !problems.isEmpty } func asDictionary() -> [String: Any] { var dict: [String : Any] = [ "problems": problems.map { $0.asDictionary() }, "took": took ] if let checked = self.checked { dict["checked"] = checked } return dict } } public struct ValidationProblem: DictionaryRepresentable { let name: String let count: Int func asDictionary() -> [String: Any] { return ["name": name, "count": count] } } public class StatsSession { var took: Int64 = 0 var when: Timestamp? private var startUptimeNanos: UInt64? public func start(when: UInt64 = Date.now()) { self.when = when self.startUptimeNanos = DispatchTime.now().uptimeNanoseconds } public func hasStarted() -> Bool { return startUptimeNanos != nil } public func end() -> Self { guard let startUptime = startUptimeNanos else { assertionFailure("SyncOperationStats called end without first calling start!") return self } // Casting to Int64 should be safe since we're using uptime since boot in both cases. // Convert to milliseconds as stated in the sync ping format took = (Int64(DispatchTime.now().uptimeNanoseconds) - Int64(startUptime)) / 1000000 return self } } // Stats about a single engine's sync. public class SyncEngineStatsSession: StatsSession { public var validationStats: ValidationStats? private(set) var uploadStats: SyncUploadStats private(set) var downloadStats: SyncDownloadStats public init(collection: String) { self.uploadStats = SyncUploadStats() self.downloadStats = SyncDownloadStats() } public func recordDownload(stats: SyncDownloadStats) { self.downloadStats.applied += stats.applied self.downloadStats.succeeded += stats.succeeded self.downloadStats.failed += stats.failed self.downloadStats.newFailed += stats.newFailed self.downloadStats.reconciled += stats.reconciled } public func recordUpload(stats: SyncUploadStats) { self.uploadStats.sent += stats.sent self.uploadStats.sentFailed += stats.sentFailed } } extension SyncEngineStatsSession: DictionaryRepresentable { func asDictionary() -> [String : Any] { var dict: [String: Any] = [ "took": took, ] if downloadStats.hasData() { dict["incoming"] = downloadStats.asDictionary() } if uploadStats.hasData() { dict["outgoing"] = uploadStats.asDictionary() } if let validation = self.validationStats, validation.hasData() { dict["validation"] = validation.asDictionary() } return dict } } // Stats and metadata for a sync operation. public class SyncOperationStatsSession: StatsSession { public let why: SyncReason public var uid: String? public var deviceID: String? fileprivate let didLogin: Bool public init(why: SyncReason, uid: String, deviceID: String?) { self.why = why self.uid = uid self.deviceID = deviceID self.didLogin = (why == .didLogin) } } extension SyncOperationStatsSession: DictionaryRepresentable { func asDictionary() -> [String : Any] { let whenValue = when ?? 0 return [ "when": whenValue, "took": took, "didLogin": didLogin, "why": why.rawValue ] } } public enum SyncPingError: MaybeErrorType { case failedToRestoreScratchpad public var description: String { switch self { case .failedToRestoreScratchpad: return "Failed to restore Scratchpad from prefs" } } } public enum SyncPingFailureReasonName: String { case httpError = "httperror" case unexpectedError = "unexpectederror" case sqlError = "sqlerror" case otherError = "othererror" } public protocol SyncPingFailureFormattable { var failureReasonName: SyncPingFailureReasonName { get } } public struct SyncPing: TelemetryPing { public private(set) var payload: JSON public static func from(result: SyncOperationResult, account: FirefoxAccount, remoteClientsAndTabs: RemoteClientsAndTabs, prefs: Prefs, why: SyncPingReason) -> Deferred<Maybe<SyncPing>> { // Grab our token so we can use the hashed_fxa_uid and clientGUID from our scratchpad for // our ping's identifiers return account.syncAuthState.token(Date.now(), canBeExpired: false) >>== { (token, kB) in let scratchpadPrefs = prefs.branch("sync.scratchpad") guard let scratchpad = Scratchpad.restoreFromPrefs(scratchpadPrefs, syncKeyBundle: KeyBundle.fromKB(kB)) else { return deferMaybe(SyncPingError.failedToRestoreScratchpad) } var ping: [String: Any] = [ "version": 1, "why": why.rawValue, "uid": token.hashedFxAUID, "deviceID": (scratchpad.clientGUID + token.hashedFxAUID).sha256.hexEncodedString ] // TODO: We don't cache our sync pings so if it fails, it fails. Once we add // some kind of caching we'll want to make sure we don't dump the events if // the ping has failed. let pickledEvents = prefs.arrayForKey(PrefKeySyncEvents) as? [Data] ?? [] let events = pickledEvents.flatMap(Event.unpickle).map { $0.toArray() } ping["events"] = events prefs.setObject(nil, forKey: PrefKeySyncEvents) return dictionaryFrom(result: result, storage: remoteClientsAndTabs, token: token) >>== { syncDict in // TODO: Split the sync ping metadata from storing a single sync. ping["syncs"] = [syncDict] return deferMaybe(SyncPing(payload: JSON(ping))) } } } // Generates a single sync ping payload that is stored in the 'syncs' list in the sync ping. private static func dictionaryFrom(result: SyncOperationResult, storage: RemoteClientsAndTabs, token: TokenServerToken) -> Deferred<Maybe<[String: Any]>> { return connectedDevices(fromStorage: storage, token: token) >>== { devices in guard let stats = result.stats else { return deferMaybe([String: Any]()) } var dict = stats.asDictionary() if let engineResults = result.engineResults.successValue { dict["engines"] = SyncPing.enginePingDataFrom(engineResults: engineResults) } else if let failure = result.engineResults.failureValue { var errorName: SyncPingFailureReasonName if let formattableFailure = failure as? SyncPingFailureFormattable { errorName = formattableFailure.failureReasonName } else { errorName = .unexpectedError } dict["failureReason"] = [ "name": errorName.rawValue, "error": "\(type(of: failure))", ] } dict["devices"] = devices return deferMaybe(dict) } } // Returns a list of connected devices formatted for use in the 'devices' property in the sync ping. private static func connectedDevices(fromStorage storage: RemoteClientsAndTabs, token: TokenServerToken) -> Deferred<Maybe<[[String: Any]]>> { func dictionaryFrom(client: RemoteClient) -> [String: Any]? { var device = [String: Any]() if let os = client.os { device["os"] = os } if let version = client.version { device["version"] = version } if let guid = client.guid { device["id"] = (guid + token.hashedFxAUID).sha256.hexEncodedString } return device } return storage.getClients() >>== { deferMaybe($0.flatMap(dictionaryFrom)) } } private static func enginePingDataFrom(engineResults: EngineResults) -> [[String: Any]] { return engineResults.map { result in let (name, status) = result var engine: [String: Any] = [ "name": name ] // For complete/partial results, extract out the collect stats // and add it to engine information. For syncs that were not able to // start, return why and a reason. switch status { case .completed(let stats): engine.merge(with: stats.asDictionary()) case .partial(let stats): engine.merge(with: stats.asDictionary()) case .notStarted(let reason): engine.merge(with: [ "status": reason.telemetryId ]) } return engine } } }
mpl-2.0
cb9f7e5387be6aff36ad20db7a244647
30.991573
123
0.596453
4.904823
false
false
false
false
Hout/JHDate
Pod/Classes/JHDateComponentPort.swift
1
11306
// // JHDatePortFunc.swift // Pods // // Created by Jeroen Houtzager on 26/10/15. // // import Foundation // MARK: - NSCalendar & NSDateComponent ports public extension JHDate { /// Today's date /// /// - Returns: the date of today at midnight (00:00) in the current calendar and default time zone. /// public static func today() -> JHDate { let calendar = NSCalendar.currentCalendar() let components = calendar.components([.Era, .Year, .Month, .Day, .Calendar, .TimeZone], fromDate: NSDate()) let date = calendar.dateFromComponents(components)! return JHDate(date: date) } /// Yesterday's date /// /// - Returns: the date of yesterday at midnight (00:00) in the current calendar and default time zone. /// public static func yesterday() -> JHDate { return (today() - 1.days)! } /// Tomorrow's date /// /// - Returns: the date of tomorrow at midnight (00:00) in the current calendar and default time zone. /// public static func tomorrow() -> JHDate { return (today() + 1.days)! } /// Returns a NSDateComponents object containing a given date decomposed into components: /// day, month, year, hour, minute, second, nanosecond, timeZone, calendar, /// yearForWeekOfYear, weekOfYear, weekday<s>, quarter</s> and weekOfMonth. /// Values returned are in the context of the calendar and time zone properties. /// /// - Returns: An NSDateComponents object containing date decomposed into the components as specified. /// public var components : NSDateComponents { return calendar.components(JHDate.componentFlags, fromDate: self.date) } /// Returns the value for an NSDateComponents object. /// Values returned are in the context of the calendar and time zone properties. /// /// - Parameters: /// - flag: specifies the calendrical unit that should be returned /// /// - Returns: The value of the NSDateComponents object for the date. public func valueForComponent(flag: NSCalendarUnit) -> Int? { let value = calendar.components(flag, fromDate: date).valueForComponent(flag) return value == NSDateComponentUndefined ? nil : value } /// Returns a new JHDate object with self as base value and a value for a NSDateComponents object set. /// /// - Parameters: /// - value: value to be set for the unit /// - unit: specifies the calendrical unit that should be set /// /// - Returns: A new JHDate object with self as base and a specific component value set. /// If no date can be constructed from the value given, a nil will be returned /// /// - seealso: public func withValues(valueUnits: [(Int, NSCalendarUnit)]) -> JHDate? /// public func withValue(value: Int, forUnit unit: NSCalendarUnit) -> JHDate? { let valueUnits = [(value, unit)] return withValues(valueUnits) } /// Returns a new JHDate object with self as base value and a value for a NSDateComponents object set. /// /// - Parameters: /// - valueUnits: a set of tupels of values and units to be set /// /// - Returns: A new JHDate object with self as base and the component values set. /// If no date can be constructed from the values given, a nil will be returned /// /// - seealso: public func withValues(valueUnits: [(Int, NSCalendarUnit)]) -> JHDate? /// public func withValues(valueUnits: [(Int, NSCalendarUnit)]) -> JHDate? { let newComponents = components for valueUnit in valueUnits { let value = valueUnit.0 let unit = valueUnit.1 newComponents.setValue(value, forComponent: unit) } let newDate = calendar.dateFromComponents(newComponents) guard newDate != nil else { return nil } return JHDate(date: newDate!, calendar: self.calendar, timeZone: self.timeZone) } /// The number of era units for the receiver. /// /// - note: This value is interpreted in the context of the calendar with which it is used /// public var era: Int? { return valueForComponent(.Era) } /// The number of year units for the receiver. /// /// - note: This value is interpreted in the context of the calendar with which it is used /// public var year: Int? { return valueForComponent(.Year) } /// The number of month units for the receiver. /// /// - note: This value is interpreted in the context of the calendar with which it is used /// public var month: Int? { return valueForComponent(.Month) } /// The number of day units for the receiver. /// /// - note: This value is interpreted in the context of the calendar with which it is used /// public var day: Int? { return valueForComponent(.Day) } /// The number of hour units for the receiver. /// /// - note: This value is interpreted in the context of the calendar with which it is used /// public var hour: Int? { return valueForComponent(.Hour) } /// The number of minute units for the receiver. /// /// - note: This value is interpreted in the context of the calendar with which it is used /// public var minute: Int? { return valueForComponent(.Minute) } /// The number of second units for the receiver. /// /// - note: This value is interpreted in the context of the calendar with which it is used /// public var second: Int? { return valueForComponent(.Second) } /// The number of nanosecond units for the receiver. /// /// - note: This value is interpreted in the context of the calendar with which it is used /// public var nanosecond: Int? { return valueForComponent(.Nanosecond) } /// The ISO 8601 week-numbering year of the receiver. /// /// - note: This value is interpreted in the context of the calendar with which it is used /// public var yearForWeekOfYear: Int? { return valueForComponent(.YearForWeekOfYear) } /// The ISO 8601 week date of the year for the receiver. /// /// - note: This value is interpreted in the context of the calendar with which it is used /// public var weekOfYear: Int? { return valueForComponent(.WeekOfYear) } /// The number of weekday units for the receiver. /// Weekday units are the numbers 1 through n, where n is the number of days in the week. /// For example, in the Gregorian calendar, n is 7 and Sunday is represented by 1. /// /// - note: This value is interpreted in the context of the calendar with which it is used /// public var weekday: Int? { return valueForComponent(.Weekday) } /// The ordinal number of weekday units for the receiver. /// Weekday ordinal units represent the position of the weekday within the next larger calendar unit, /// such as the month. For example, 2 is the weekday ordinal unit for the second Friday of the month. /// /// - note: This value is interpreted in the context of the calendar with which it is used /// public var weekdayOrdinal: Int? { return valueForComponent(.WeekdayOrdinal) } /** QUARTER IS NOT INCLUDED DUE TO INCORRECT REPRESENTATION OF QUARTER IN NSCALENDAR /// The number of quarter units for the receiver. /// Weekday ordinal units represent the position of the weekday within the next larger calendar unit, /// such as the month. For example, 2 is the weekday ordinal unit for the second Friday of the month. /// /// - note: This value is interpreted in the context of the calendar with which it is used /// public var quarter: Int? { return valueForComponent(.Quarter) } **/ /// The week number in the month for the receiver. /// /// - note: This value is interpreted in the context of the calendar with which it is used /// public var weekOfMonth: Int? { return valueForComponent(.WeekOfMonth) } /// Boolean value that indicates whether the month is a leap month. /// ``YES`` if the month is a leap month, ``NO`` otherwise /// /// - note: This value is interpreted in the context of the calendar with which it is used /// public var leapMonth: Bool { // Library function for leap contains a bug for Gregorian calendars, implemented workaround if calendar.calendarIdentifier == NSCalendarIdentifierGregorian && year >= 1582 { let range = calendar.rangeOfUnit(NSCalendarUnit.Day, inUnit: NSCalendarUnit.Month, forDate: date) return range.length == 29 } // For other calendars: return calendar.components([.Day, .Month, .Year], fromDate: date).leapMonth } /// Boolean value that indicates whether the year is a leap year. /// ``YES`` if the year is a leap year, ``NO`` otherwise /// /// - note: This value is interpreted in the context of the calendar with which it is used /// public var leapYear: Bool { // Library function for leap contains a bug for Gregorian calendars, implemented workaround if calendar.calendarIdentifier == NSCalendarIdentifierGregorian { let testDate = JHDate(refDate: self, month: 2, day: 1)! return testDate.leapMonth } // For other calendars: return calendar.components([.Day, .Month, .Year], fromDate: date).leapMonth } /// Returns two JHDate objects indicating the start and the end of the previous weekend before the date. /// /// - Returns: a tuple of two JHDate objects indicating the start and the end of the next weekend after the date. /// /// - Note: The weekend returned when the receiver is in a weekend is the previous weekend not the current one. /// public func previousWeekend() -> (startDate: JHDate, endDate: JHDate)? { let date = (self - 9.days)! return date.nextWeekend() } /// Returns two JHDate objects indicating the start and the end of the next weekend after the date. /// /// - Returns: a tuple of two JHDate objects indicating the start and the end of the next weekend after the date. /// /// - Note: The weekend returned when the receiver is in a weekend is the next weekend not the current one. /// public func nextWeekend() -> (startDate: JHDate, endDate: JHDate)? { var weekendStart: NSDate? var timeInterval: NSTimeInterval = 0 if !calendar.nextWeekendStartDate(&weekendStart, interval: &timeInterval, options: NSCalendarOptions(rawValue: 0), afterDate: self.date) { return nil } // Subtract 10000 nanoseconds to distinguish from Midnigth on the next Monday for the isEqualDate function of NSDate let weekendEnd = weekendStart!.dateByAddingTimeInterval(timeInterval - 0.00001) let startDate = JHDate(date: weekendStart!, calendar: calendar, timeZone: timeZone, locale: locale) let endDate = JHDate(date: weekendEnd, calendar: calendar, timeZone: timeZone, locale: locale) return (startDate, endDate) } }
mit
6aaf0515e29c92127caea5b3a6c93e6f
37.989655
146
0.649036
4.646938
false
false
false
false
iCodesign/TASideMenu-Swift
TASideMenu/MainTableViewController.swift
1
3418
// // MainTableViewController.swift // TASideMenu // // Created by 电魂 on 9/27/14. // Copyright (c) 2014 TouchingApp. All rights reserved. // import UIKit class MainTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } @IBAction func showLeftMenu(sender: AnyObject) { if self.sideMenuViewController!.presentingStatus == TASideMenu.Main{ self.sideMenuViewController!.presentMenu(.Left) }else{ self.sideMenuViewController!.presentMenu(.Main) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 40 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell // Configure the cell... return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView!, moveRowAtIndexPath fromIndexPath: NSIndexPath!, toIndexPath: NSIndexPath!) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView!, canMoveRowAtIndexPath indexPath: NSIndexPath!) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // 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. } */ }
mit
85de797ee9d9624a5672df56d1146d70
33.484848
159
0.673697
5.560261
false
false
false
false
allen-zeng/PromiseKit
Categories/MessageUI/MFMailComposeViewController+Promise.swift
2
2832
import MessageUI.MFMailComposeViewController import UIKit.UIViewController #if !COCOAPODS import PromiseKit #endif /** To import this `UIViewController` category: use_frameworks! pod "PromiseKit/MessageUI" And then in your sources: import PromiseKit */ extension UIViewController { public func promiseViewController(vc: MFMailComposeViewController, animated: Bool = true, completion:(() -> Void)? = nil) -> Promise<MFMailComposeResult> { let proxy = PMKMailComposeViewControllerDelegate() proxy.retainCycle = proxy vc.mailComposeDelegate = proxy presentViewController(vc, animated: animated, completion: completion) proxy.promise.always { self.dismissViewControllerAnimated(animated, completion: nil) } return proxy.promise } } extension MFMailComposeViewController { public enum Error: CancellableErrorType { case Cancelled public var cancelled: Bool { switch self { case .Cancelled: return true } } } } private class PMKMailComposeViewControllerDelegate: NSObject, MFMailComposeViewControllerDelegate, UINavigationControllerDelegate { let (promise, fulfill, reject) = Promise<MFMailComposeResult>.pendingPromise() var retainCycle: NSObject? @objc func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { defer { retainCycle = nil } if let error = error { reject(error) } else { #if swift(>=2.3) switch result { case .Failed: var info = [NSObject: AnyObject]() info[NSLocalizedDescriptionKey] = "The attempt to save or send the message was unsuccessful." info[NSUnderlyingErrorKey] = NSNumber(integer: result.rawValue) reject(NSError(domain: PMKErrorDomain, code: PMKOperationFailed, userInfo: info)) case .Cancelled: reject(MFMailComposeViewController.Error.Cancelled) default: fulfill(result) } #else switch result.rawValue { case MFMailComposeResultFailed.rawValue: var info = [NSObject: AnyObject]() info[NSLocalizedDescriptionKey] = "The attempt to save or send the message was unsuccessful." info[NSUnderlyingErrorKey] = NSNumber(unsignedInt: result.rawValue) reject(NSError(domain: PMKErrorDomain, code: PMKOperationFailed, userInfo: info)) case MFMailComposeResultCancelled.rawValue: reject(MFMailComposeViewController.Error.Cancelled) default: fulfill(result) } #endif } } }
mit
72f23d4aa008531e5d00a0b32fe41fcd
34.4
159
0.648305
5.744422
false
false
false
false
Jmeggesto/StringUtils
StringUtils/Classes/StringExtensions.swift
1
8859
// // StringExtensions.swift // SwiftUtilsTest // // Created by Jackie Meggesto on 5/18/16. // Copyright © 2016 Jackie Meggesto. All rights reserved. // import Foundation //Standard library conveniences and extensions. public extension String { /** Convenience property for a `String`'s length */ public var length: Int { return self.characters.count } /** An Array of the individual substrings composing `self`. Read-only. */ public var chars: [String] { return Array(self.characters).map({String($0)}) } /** A Set<String> of the unique characters in `self`. */ public var charSet: Set<String> { return Set(self.characters.map{String($0)}) } public var firstCharacter: String? { return self.chars.first } public var lastCharacter: String? { return self.chars.last } public var isEmpty: Bool { return self.chars.isEmpty } /** Returns the number of times `string` appears in self. */ public func count(string: String) -> Int { return self.regex.numberOfMatchesInString(string) } /** Returns the most common character in `self`. If `self.chars.count` == `self.charSet.count`, returns the first string in `self.charSet`. */ public func mostCommonCharacter() -> String { var mostCommon = "" var count = 0 for string in self.charSet { if self.count(string) > count { count = self.count(string) mostCommon = string } } return mostCommon } /// Returns the first index where `value` appears in `self` or `nil` if /// `value` is not found. /// /// - Complexity: O(n). func indexOf(element: String) -> Int? { return self.chars.indexOf(element) } mutating func insertString(string: String, atIndex: Int) { var _copy = self.chars _copy.insert(string, atIndex: atIndex) self = _copy.joinWithSeparator("") } /** Function to allow range removal with Int Ranges. */ mutating func removeRange(range: Range<Int>) { var _copy = self.chars _copy.removeRange(range) self = _copy.joinWithSeparator("") } /** Convenience wrapper around `String.componentsSeparatedByString`. */ public func split(separator: String) -> [String] { return self.componentsSeparatedByString(separator) } /** Convenience wrapper around `String.stringByReplacingOccurencesOfString()`. */ public mutating func replace(string: String, with: String) { self = self.stringByReplacingOccurrencesOfString(string, withString: with) } /** Returns a copy of `self` where copy is the reversed form of `self`. */ public func reversed() -> String { return String(self.characters.reverse()) } /** Reverses `self`. */ public mutating func reverse() { self = String(self.characters.reverse()) } } //Emoji-related properties and functions. public extension String { /** Boolean representing whether `self` contains any emoji characters. The unichar value ranges for testing emoji should not be assumed to be exhaustive, and extension of this property is highly encouraged. */ public var containsEmoji: Bool { for scalar in unicodeScalars { switch scalar.value { case 0x1F600...0x1F64F, // Emoticons 0x1F300...0x1F5FF, 0x1F900...0x1F9FF, 0x1F600...0x1F64F, // Misc Symbols and Pictographs 0x1F680...0x1F6FF, // Transport and Map 0x2600...0x26FF, // Misc symbols 0x2700...0x27BF, // Dingbats 0xFE00...0xFE0F, // Variation Selectors 0xF8FF: return true default: continue } } return false } public mutating func removeEmoji() { self = self.chars.filter({!$0.containsEmoji}).joinWithSeparator("") } public func stringByRemovingEmoji() -> String { return self.chars.filter({!$0.containsEmoji}).joinWithSeparator("") } } //Extensions for converting Strings into different value types, //checking if String satisfies certain conditions. public extension String { /** Performs a regular expression operation on `self` to determine whether or not the String can be considered a valid email. */ public func isEmail() -> Bool { return self.regex.matchesPattern("^[[:alnum:]._%+-]+@[[:alnum:].-]+\\.[A-Z]+$") } /** Uses regular expressions to determine whether `self` can be considered a valid numeric form. Currently supported numeric formats: - Int literal - Double literal */ func isNumber() -> Bool { if (self.regex.matchesPattern(Regex.integerMatchingPattern) || self.regex.matchesPattern(Regex.floatMatchingPattern)) && !self.regex.matchesPattern(Regex.nonNumericMatchingPattern) { return true } return false } /** Uses regular expressions to determine whether `self` can be considered a valid numeric form, and if so, returns the numeric value of `self` Currently supported numeric formats: - Int literal - Double literal - returns: An NSNumber value representing the numeric value contained within `self`. If `self` is not a valid numeric format, returns nil. */ func numericValue() -> NSNumber? { if self.isNumber() { if self.regex.matchesPattern(Regex.integerMatchingPattern) { return NSNumber(integer: Int(self)!) } if self.regex.matchesPattern(Regex.floatMatchingPattern) { return NSNumber(double: Double(self)!) } } return nil } } //Subscripts and slicing public extension String { /** */ public func substring(from: Int, _ to: Int) -> String { let a = startIndex.advancedBy(from) let b = startIndex.advancedBy(to) return self[a..<b] } /** Skips over the characters of `self` by `n` and returns a complete string formed by concatenating the substrings. */ public func everyNth(n: Int) -> String { if n > 0 { return String(characters.enumerate().filter({ $0.0 % n == 0 }).map({ $0.1 })) } else { return String(characters.reverse().enumerate().filter({ $0.0 % n == 0 }).map({ $0.1 })) } } /** Returns the character at index n of `self`. - returns: If `n` is positive, returns the character at index `n` of `self`. If `n` is negative, returns the character `n` steps from the end of `self`. */ public subscript(n: Int) -> String { if n >= 0 { let a = startIndex.advancedBy(n) return String(self[a]) } else { let a = startIndex.advancedBy(self.length + n) return String(self[a]) } } /** Allows for subscripting with Range<Int>. - parameters: - integerRange: A Range<Int> object representing the range of `self` to be returned. - returns: Returns the section of `self` from the start of `integerRange`, to the end of `integerRange`. */ public subscript(integerRange: Range<Int>) -> String { return self.substring(integerRange.startIndex, integerRange.endIndex) } public func slice(from from: Int = 0, to: Int? = nil, by: Int = 1) -> String { var _to = to var _from = from if to == nil { _to = self.length } if _to < 0 { _to = self.length + _to! } if from < 0 { _from = self.length + from } return self.substring(_from, _to!).everyNth(by) } }
mit
a6739a9839d71d730d314939dfeac120
22.372032
99
0.5324
4.788108
false
false
false
false
Polidea/RxBluetoothKit
Tests/Autogenerated/_Descriptor.generated.swift
1
5191
import Foundation import CoreBluetooth @testable import RxBluetoothKit import RxSwift /// _Descriptor is a class implementing ReactiveX which wraps CoreBluetooth functions related to interaction with /// [CBDescriptorMock](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBDescriptor_Class/) /// Descriptors provide more information about a characteristic’s value. class _Descriptor { /// Intance of CoreBluetooth descriptor class let descriptor: CBDescriptorMock /// _Characteristic to which this descriptor belongs. let characteristic: _Characteristic /// The Bluetooth UUID of the `_Descriptor` instance. var uuid: CBUUID { return descriptor.uuid } /// The value of the descriptor. It can be written and read through functions on `_Descriptor` instance. var value: Any? { return descriptor.value } init(descriptor: CBDescriptorMock, characteristic: _Characteristic) { self.descriptor = descriptor self.characteristic = characteristic } convenience init(descriptor: CBDescriptorMock, peripheral: _Peripheral) { let service = _Service(peripheral: peripheral, service: descriptor.characteristic.service) let characteristic = _Characteristic(characteristic: descriptor.characteristic, service: service) self.init(descriptor: descriptor, characteristic: characteristic) } /// Function that allow to observe writes that happened for descriptor. /// - Returns: Observable that emits `next` with `_Descriptor` instance every time when write has happened. /// It's **infinite** stream, so `.complete` is never called. /// /// Observable can ends with following errors: /// * `_BluetoothError.descriptorWriteFailed` /// * `_BluetoothError.peripheralDisconnected` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func observeWrite() -> Observable<_Descriptor> { return characteristic.service.peripheral.observeWrite(for: self) } /// Function that triggers write of data to descriptor. Write is called after subscribtion to `Observable` is made. /// - Parameter data: `Data` that'll be written to `_Descriptor` instance /// - Returns: `Single` that emits `Next` with `_Descriptor` instance, once value is written successfully. /// /// Observable can ends with following errors: /// * `_BluetoothError.descriptorWriteFailed` /// * `_BluetoothError.peripheralDisconnected` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func writeValue(_ data: Data) -> Single<_Descriptor> { return characteristic.service.peripheral.writeValue(data, for: self) } /// Function that allow to observe value updates for `_Descriptor` instance. /// - Returns: Observable that emits `next` with `_Descriptor` instance every time when value has changed. /// It's **infinite** stream, so `.complete` is never called. /// /// Observable can ends with following errors: /// * `_BluetoothError.descriptorReadFailed` /// * `_BluetoothError.peripheralDisconnected` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func observeValueUpdate() -> Observable<_Descriptor> { return characteristic.service.peripheral.observeValueUpdate(for: self) } /// Function that triggers read of current value of the `_Descriptor` instance. /// Read is called after subscription to `Observable` is made. /// - Returns: `Single` which emits `next` with given descriptor when value is ready to read. /// /// Observable can ends with following errors: /// * `_BluetoothError.descriptorReadFailed` /// * `_BluetoothError.peripheralDisconnected` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func readValue() -> Single<_Descriptor> { return characteristic.service.peripheral.readValue(for: self) } } extension _Descriptor: Equatable {} /// Compare two descriptors. Descriptors are the same when their UUIDs are the same. /// /// - parameter lhs: First descriptor to compare /// - parameter rhs: Second descriptor to compare /// - returns: True if both descriptor are the same. func == (lhs: _Descriptor, rhs: _Descriptor) -> Bool { return lhs.descriptor == rhs.descriptor }
apache-2.0
7ef571ca57e9285e526aee64e93dbf27
43.732759
121
0.70476
5.215075
false
false
false
false
dbruzzone/wishing-tree
iOS/Locate/Locate/AppDelegate.swift
1
6100
// // AppDelegate.swift // Locate // // Created by Davide Bruzzone on 11/6/15. // Copyright © 2015 Bitwise Samurai. 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.bitwisesamurai.Locate" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Locate", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
gpl-3.0
ff8643075a8f8f38caf022ef308d7f23
53.945946
291
0.71979
5.881389
false
false
false
false
tidepool-org/nutshell-ios
Nutshell/DataModel/CoreData/User.swift
1
1116
// // User.swift // // // Created by Brian King on 9/14/15. // // import Foundation import CoreData import SwiftyJSON class User: NSManagedObject { class func fromJSON(_ json: JSON, moc: NSManagedObjectContext) -> User? { if let entityDescription = NSEntityDescription.entity(forEntityName: "User", in: moc) { let me = User(entity: entityDescription, insertInto: nil) me.userid = json["userid"].string me.username = json["username"].string me.fullName = json["fullName"].string me.token = json["token"].string return me } return nil } func processProfileJSON(_ json: JSON) { NSLog("profile json: \(json)") fullName = json["fullName"].string if fullName != nil { self.managedObjectContext?.refresh(self, mergeChanges: true) NSLog("Added full name from profile: \(fullName)") } let patient = json["patient"] let isDSA = patient != JSON.null accountIsDSA = NSNumber.init(value: isDSA) } }
bsd-2-clause
54264c5fd6d0b5f16c253cc6e7740893
26.9
95
0.578853
4.555102
false
false
false
false
superk589/DereGuide
DereGuide/View/ValueStepper.swift
2
15529
// // ValueStepper.swift // http://github.com/BalestraPatrick/ValueStepper // // Created by Patrick Balestra on 2/16/16. // Copyright © 2016 Patrick Balestra. All rights reserved. // import UIKit import SnapKit /// Button tags /// /// - decrease: decrease button has tag 0. /// - increase: increase button has tag 1. private enum Button: Int { case decrease case increase } @IBDesignable class ValueStepper: UIControl { // MARK - Public variables /// Current value and sends UIControlEventValueChanged when modified. @IBInspectable public var value: Double = 0.0 { didSet { if value > maximumValue || value < minimumValue { // Value is possibly out of range, it means we're setting up the values so discard any update to the UI. } else if oldValue != value { sendActions(for: .valueChanged) setState() } setFormattedValue(value) } } /// Minimum value that must be less than the maximum value. @IBInspectable public var minimumValue: Double = 0.0 { didSet { setState() } } /// Maximum value that must be greater than the minimum value. @IBInspectable public var maximumValue: Double = 1.0 { didSet { setState() } } /// When set to true, the user can tap the label and manually enter a value. @IBInspectable public var enableManualEditing: Bool = false { didSet { valueLabel.isUserInteractionEnabled = enableManualEditing } } /// The value added/subtracted when one of the two buttons is pressed. @IBInspectable public var stepValue: Double = 0.1 /// When set to true, keeping a button pressed will continuously increase/decrease the value every 0.1s. @IBInspectable public var autorepeat: Bool = true /// Describes the format of the value. public var numberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.maximumFractionDigits = 2 return formatter }() { didSet { setFormattedValue(value) } } // Default width of the stepper. Taken from the official UIStepper object. public let defaultWidth = 141.0 // Default height of the stepper. Taken from the official UIStepper object. public let defaultHeight = 29.0 // MARK - Private variables /// Decrease button positioned on the left of the stepper. internal let decreaseButton: UIButton = { let button = UIButton(type: UIButton.ButtonType.custom) button.backgroundColor = .clear button.tag = Button.decrease.rawValue return button }() /// Increase button positioned on the right of the stepper. internal let increaseButton: UIButton = { let button = UIButton(type: UIButton.ButtonType.custom) button.backgroundColor = .clear button.tag = Button.increase.rawValue return button }() /// Value label that displays the current value displayed at the center of the stepper. private(set) var valueLabel: UILabel = { let label = UILabel() label.textAlignment = .center label.backgroundColor = .clear label.font = .systemFont(ofSize: 16) label.minimumScaleFactor = 0.5 label.adjustsFontSizeToFitWidth = true return label }() private(set) var descriptionLabel: UILabel = { let label = UILabel() label.textAlignment = .center label.backgroundColor = .clear label.numberOfLines = 2 label.font = .systemFont(ofSize: 10) label.minimumScaleFactor = 0.5 label.adjustsFontSizeToFitWidth = true return label }() // Decrease (-) button layer. Declared here because we can change its color when not enabled. private var decreaseLayer = CAShapeLayer() // Increase (+) button layer. Declared here because we can change its color when not enabled. private var increaseLayer = CAShapeLayer() // Left separator. private var leftSeparator = CAShapeLayer() // Right separator. private var rightSeparator = CAShapeLayer() // Timer used in case that autorepeat is true to change the value continuously. private weak var continuousTimer: Timer? { didSet { if let timer = oldValue { timer.invalidate() } } } // MARK: Initializers override init(frame: CGRect) { // Override frame with default width and height let frameWithDefaultSize = CGRect(x: Double(frame.origin.x), y: Double(frame.origin.y), width: defaultWidth, height: defaultHeight) super.init(frame: frameWithDefaultSize) setUp() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUp() } private func setUp() { backgroundColor = .white let stackView = UIStackView(arrangedSubviews: [valueLabel, descriptionLabel]) stackView.distribution = .equalSpacing stackView.spacing = 3 stackView.axis = .vertical addSubview(decreaseButton) addSubview(increaseButton) addSubview(stackView) decreaseButton.snp.makeConstraints { (make) in make.top.bottom.left.equalToSuperview() make.width.equalTo(decreaseButton.snp.height) } increaseButton.snp.makeConstraints { (make) in make.right.top.bottom.equalToSuperview() make.width.equalTo(decreaseButton.snp.height) } stackView.snp.makeConstraints { (make) in make.left.equalTo(decreaseButton.snp.right) make.right.equalTo(increaseButton.snp.left) make.center.equalToSuperview() } // Control events decreaseButton.addTarget(self, action: #selector(decrease(_:)), for: [.touchUpInside, .touchCancel]) increaseButton.addTarget(self, action: #selector(increase(_:)), for: [.touchUpInside, .touchCancel]) increaseButton.addTarget(self, action: #selector(stopContinuous(_:)), for: .touchUpOutside) decreaseButton.addTarget(self, action: #selector(stopContinuous(_:)), for: .touchUpOutside) decreaseButton.addTarget(self, action: #selector(selected(_:)), for: .touchDown) increaseButton.addTarget(self, action: #selector(selected(_:)), for: .touchDown) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(labelPressed(_:))) valueLabel.addGestureRecognizer(tapGesture) setFormattedValue(value) } // MARK: Storyboard preview setup override open func prepareForInterfaceBuilder() { setUp() } override public static var requiresConstraintBasedLayout: Bool { get { return true } } // MARK: Lifecycle open override func draw(_ rect: CGRect) { // Size constants let sliceWidth = bounds.height let sliceHeight = bounds.height let thickness = 1.0 as CGFloat let iconSize: CGFloat = sliceHeight * 0.6 // Layer customizations layer.borderColor = tintColor.cgColor layer.borderWidth = 1.0 layer.cornerRadius = 4.0 backgroundColor = .clear clipsToBounds = true let leftPath = UIBezierPath() // Left separator line leftPath.move(to: CGPoint(x: sliceWidth, y: 0.0)) leftPath.addLine(to: CGPoint(x: sliceWidth, y: sliceHeight)) tintColor.setStroke() leftPath.stroke() // Set left separator layer leftSeparator.path = leftPath.cgPath leftSeparator.strokeColor = tintColor.cgColor layer.addSublayer(leftSeparator) // Right separator line let rightPath = UIBezierPath() rightPath.move(to: CGPoint(x: bounds.width - sliceWidth, y: 0.0)) rightPath.addLine(to: CGPoint(x: bounds.width - sliceWidth, y: sliceHeight)) tintColor.setStroke() rightPath.stroke() // Set right separator layer rightSeparator.path = rightPath.cgPath rightSeparator.strokeColor = tintColor.cgColor layer.addSublayer(rightSeparator) // - path let decreasePath = UIBezierPath() decreasePath.lineWidth = thickness // Horizontal + line decreasePath.move(to: CGPoint(x: (sliceWidth - iconSize) / 2 + 0.5, y: sliceHeight / 2 + 0.5)) decreasePath.addLine(to: CGPoint(x: (sliceWidth - iconSize) / 2 + 0.5 + iconSize, y: sliceHeight / 2 + 0.5)) tintColor.setStroke() decreasePath.stroke() // Create layer so that we can dynamically change its color when not enabled decreaseLayer.path = decreasePath.cgPath decreaseLayer.strokeColor = tintColor.cgColor layer.addSublayer(decreaseLayer) // + path let increasePath = UIBezierPath() increasePath.lineWidth = thickness // Horizontal + line increasePath.move(to: CGPoint(x: (sliceWidth - iconSize) / 2 + 0.5 + bounds.width - sliceWidth, y: sliceHeight / 2 + 0.5)) increasePath.addLine(to: CGPoint(x: (sliceWidth - iconSize) / 2 + 0.5 + iconSize + bounds.width - sliceWidth, y: sliceHeight / 2 + 0.5)) // Vertical + line increasePath.move(to: CGPoint(x: sliceWidth / 2 + 0.5 + bounds.width - sliceWidth, y: (sliceHeight / 2) - (iconSize / 2) + 0.5)) increasePath.addLine(to: CGPoint(x: sliceWidth / 2 + 0.5 + bounds.width - sliceWidth, y: (sliceHeight / 2) + (iconSize / 2) + 0.5)) tintColor.setStroke() increasePath.stroke() // Create layer so that we can dynamically change its color when not enabled increaseLayer.path = increasePath.cgPath increaseLayer.strokeColor = tintColor.cgColor layer.addSublayer(increaseLayer) // Set initial buttons state setState() } // MARK: Control Events @objc internal func decrease(_ sender: UIButton) { sender.backgroundColor = UIColor(white: 1.0, alpha: 0.0) continuousTimer = nil decreaseValue() } @objc internal func increase(_ sender: UIButton) { sender.backgroundColor = UIColor(white: 1.0, alpha: 0.0) continuousTimer = nil increaseValue() } @objc internal func continuousIncrement(_ timer: Timer) { // Check which one of the two buttons was continuously pressed let userInfo = timer.userInfo as! Dictionary<String, AnyObject> guard let sender = userInfo["sender"] as? UIButton else { return } if sender.tag == Button.decrease.rawValue { decreaseValue() } else { increaseValue() } } @objc func selected(_ sender: UIButton) { // Start a timer to handle the continuous pressed case if autorepeat { let timer = Timer.init(fireAt: Date().addingTimeInterval(0.5), interval: 0.1, target: self, selector: #selector(continuousIncrement(_:)), userInfo: ["sender": sender], repeats: true) RunLoop.main.add(timer, forMode: RunLoop.Mode.default) self.continuousTimer = timer } sender.backgroundColor = UIColor(white: 1.0, alpha: 0.1) } @objc func stopContinuous(_ sender: UIButton) { // When dragged outside, stop the timer. continuousTimer = nil } func increaseValue() { let roundedValue = value.rounded(digits: numberFormatter.maximumFractionDigits) if roundedValue + stepValue <= maximumValue && roundedValue + stepValue >= minimumValue { value = roundedValue + stepValue } } func decreaseValue() { let roundedValue = value.rounded(digits: numberFormatter.maximumFractionDigits) if roundedValue - stepValue <= maximumValue && roundedValue - stepValue >= minimumValue { value = roundedValue - stepValue } } @objc func labelPressed(_ sender: UITapGestureRecognizer) { let alertController = UIAlertController(title: "Enter a value", message: nil, preferredStyle: .alert) alertController.addTextField { textField in textField.placeholder = "Value" textField.keyboardType = .decimalPad } alertController.addAction(UIAlertAction(title: "Confirm", style: .default) { (_) in if let newValue = Double((alertController.textFields?[0].text)!) as Double? { if newValue >= self.minimumValue || newValue <= self.maximumValue { self.value = newValue } } }) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel) { (_) in }) getTopMostViewController()?.present(alertController, animated: true, completion: nil) } // MARK: Actions // Set correct state of the buttons (in case we reached the minimum or maximum value). private func setState() { if value >= maximumValue { increaseButton.isEnabled = false decreaseButton.isEnabled = true increaseLayer.strokeColor = UIColor.lightGray.cgColor continuousTimer = nil } else if value <= minimumValue { decreaseButton.isEnabled = false increaseButton.isEnabled = true decreaseLayer.strokeColor = UIColor.lightGray.cgColor continuousTimer = nil } else { increaseButton.isEnabled = true decreaseButton.isEnabled = true increaseLayer.strokeColor = tintColor.cgColor decreaseLayer.strokeColor = tintColor.cgColor } } // Display the value with the private func setFormattedValue(_ value: Double) { valueLabel.text = numberFormatter.string(from: NSNumber(value: value)) } // Update all the subviews tintColor properties. open override func tintColorDidChange() { layer.borderColor = tintColor.cgColor valueLabel.textColor = tintColor leftSeparator.strokeColor = tintColor.cgColor rightSeparator.strokeColor = tintColor.cgColor increaseLayer.strokeColor = tintColor.cgColor decreaseLayer.strokeColor = tintColor.cgColor } // MARK: Helpers func getTopMostViewController() -> UIViewController? { if var topController = UIApplication.shared.keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } return topController } return nil } } extension Double { /// Rounds a double to `digits` decimal places. func rounded(digits: Int) -> Double { let behavior = NSDecimalNumberHandler(roundingMode: NSDecimalNumber.RoundingMode.bankers, scale: Int16(digits), raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true) return NSDecimalNumber(value: self).rounding(accordingToBehavior: behavior).doubleValue } }
mit
a35a1978f93d50f546450722a2174dd2
35.796209
220
0.627061
5.036653
false
false
false
false
S7Vyto/Mobile
iOS/SVNewsletter/SVNewsletter/Modules/Newsletter/Wireframe/NewsletterWireframe.swift
1
2759
// // NewsletterWireframe.swift // SVNewsletter // // Created by Sam on 21/11/2016. // Copyright © 2016 Semyon Vyatkin. All rights reserved. // import Foundation import UIKit protocol NewsletterWireframeProtocol { func presentDetailsInterface(for newsletter: NewsEntity) func configurateDetailsInteface(_ controller: NewsletterDetailsViewController) func showLoadingIndicator() func dismissLoadingIndicator() } class NewsletterWireframe: NewsletterWireframeProtocol { weak var newsletterController: NewsletterViewController? var rootWireframe: Wireframe? let loadingIndicator = LoadingViewController.indicator let newsletterPresenter: NewsletterPresenter let detailsWireframe = NewsletterDetailsWireframe() init() { let newsletterInteractor = NewsletterInteractor() newsletterPresenter = NewsletterPresenter() newsletterPresenter.interactor = newsletterInteractor newsletterPresenter.wireframe = self newsletterInteractor.interactorOutput = newsletterPresenter } func presentNewsletterListView(_ window: UIWindow?) { newsletterController = rootWireframe?.viewControllerWith(name: "NewsletterViewController") as? NewsletterViewController newsletterController?.presenter = newsletterPresenter newsletterPresenter.newsletterListView = newsletterController assert(newsletterController != nil, "Controller can't be empty") rootWireframe?.showRootViewController(newsletterController!, in: window) } // MARK: - NewsletterWireframe Protocol func showLoadingIndicator() { assert(newsletterController != nil, "Controller can't be empty") loadingIndicator.showFrom(newsletterController!, with: "Обновление новостей") } func dismissLoadingIndicator() { loadingIndicator.dismiss() } func presentExceptionMessage(_ exceptionMsg: String) { let controller = UIAlertController(title: "Error", message: exceptionMsg, preferredStyle: .alert) let done = UIAlertAction(title: "OK", style: .default, handler: nil) controller.addAction(done) newsletterController?.present(controller, animated: true, completion: nil) } func presentDetailsInterface(for newsletter: NewsEntity) { detailsWireframe.detailsPresenter.newsletter = newsletter detailsWireframe.sourceController = newsletterController detailsWireframe.presentNewsletterDetails() } func configurateDetailsInteface(_ controller: NewsletterDetailsViewController) { detailsWireframe.configurateDetailsInterface(controller) } }
apache-2.0
56f92a8f40f930df2d2e4e225ed4f355
35.052632
127
0.722628
5.310078
false
false
false
false
bamzy/goQueer-iOS
GoQueer/AnnotationView.swift
1
922
// // AnnotationView.swift // AKSwiftSlideMenu // // Created by Lion User on 2017-05-22. // Copyright © 2017 Kode. All rights reserved. // import MapKit class AnnotationView: MKAnnotationView{ override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let hitView = super.hitTest(point, with: event) if (hitView != nil) { self.superview?.bringSubview(toFront: self) } return hitView } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let rect = self.bounds; var isInside: Bool = rect.contains(point); if(!isInside) { for view in self.subviews { isInside = view.frame.contains(point); if isInside { break; } } } return isInside; } }
mit
1761b3ab47f4237c263fe43b869a8a88
23.891892
78
0.528773
4.492683
false
true
false
false
magnetsystems/message-ios
Source/Poll/MMXPollAnswer.swift
1
2423
/* * Copyright (c) 2015 Magnet Systems, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ import MagnetMaxCore func + <K, V> (left: Dictionary<K, V>, right: Dictionary<K, V>) -> Dictionary<K, V> { var l = left for (k, v) in right { l.updateValue(v, forKey: k) } return l } @objc public class MMXPollAnswer: MMModel, MMXPayload { //MARK: Public Variables public static var contentType: String { return "object/MMXPollAnswer"} //Poll Attributes public var pollID: String = "" public var name: String = "" public var question : String = "" //Poll Options public var previousSelection: [MMXPollOption]? public var currentSelection = [MMXPollOption]() public var userID: String = "" public override init!() { super.init() } public init(_ poll: MMXPoll, selectedOptions:[MMXPollOption], previousSelection:[MMXPollOption]?) { self.pollID = poll.pollID! self.name = poll.name self.question = poll.question self.currentSelection = selectedOptions self.previousSelection = previousSelection super.init() } required public init(dictionary dictionaryValue: [NSObject : AnyObject]!) throws { try super.init(dictionary: dictionaryValue) } required public init!(coder: NSCoder!) { super.init(coder: coder) } //MARK: Overrides public override class func attributeMappings() -> [NSObject : AnyObject]! { return (super.attributeMappings() ?? [:]) + ["pollID" as NSString: "pollId", "userID" as NSString: "userId"] } public override class func listAttributeTypes() -> [NSObject : AnyObject]! { return (super.listAttributeTypes() ?? [:]) + ["currentSelection" as NSString: MMXPollOption.self, "previousSelection" as NSString: MMXPollOption.self] } }
apache-2.0
e3b546fc668bcfc9c61f1d9ad0532c86
32.652778
158
0.661577
4.381555
false
false
false
false
Geor9eLau/WorkHelper
Carthage/Checkouts/SwiftCharts/Examples/Examples/CandleStickInteractiveExample.swift
1
15217
// // CandleStickInteractiveExample.swift // SwiftCharts // // Created by ischuetz on 04/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit import SwiftCharts class CandleStickInteractiveExample: UIViewController { fileprivate var chart: Chart? // arc override func viewDidLoad() { super.viewDidLoad() let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) var readFormatter = DateFormatter() readFormatter.dateFormat = "dd.MM.yyyy" var displayFormatter = DateFormatter() displayFormatter.dateFormat = "MMM dd" let date = {(str: String) -> Date in return readFormatter.date(from: str)! } let calendar = Calendar.current let dateWithComponents = {(day: Int, month: Int, year: Int) -> Date in var components = DateComponents() components.day = day components.month = month components.year = year return calendar.date(from: components)! } func filler(_ date: Date) -> ChartAxisValueDate { let filler = ChartAxisValueDate(date: date, formatter: displayFormatter) filler.hidden = true return filler } let chartPoints = [ ChartPointCandleStick(date: date("01.10.2015"), formatter: displayFormatter, high: 40, low: 37, open: 39.5, close: 39), ChartPointCandleStick(date: date("02.10.2015"), formatter: displayFormatter, high: 39.8, low: 38, open: 39.5, close: 38.4), ChartPointCandleStick(date: date("03.10.2015"), formatter: displayFormatter, high: 43, low: 39, open: 41.5, close: 42.5), ChartPointCandleStick(date: date("04.10.2015"), formatter: displayFormatter, high: 48, low: 42, open: 44.6, close: 44.5), ChartPointCandleStick(date: date("05.10.2015"), formatter: displayFormatter, high: 45, low: 41.6, open: 43, close: 44), ChartPointCandleStick(date: date("06.10.2015"), formatter: displayFormatter, high: 46, low: 42.6, open: 44, close: 46), ChartPointCandleStick(date: date("07.10.2015"), formatter: displayFormatter, high: 47.5, low: 41, open: 42, close: 45.5), ChartPointCandleStick(date: date("08.10.2015"), formatter: displayFormatter, high: 50, low: 46, open: 46, close: 49), ChartPointCandleStick(date: date("09.10.2015"), formatter: displayFormatter, high: 45, low: 41, open: 44, close: 43.5), ChartPointCandleStick(date: date("11.10.2015"), formatter: displayFormatter, high: 47, low: 35, open: 45, close: 39), ChartPointCandleStick(date: date("12.10.2015"), formatter: displayFormatter, high: 45, low: 33, open: 44, close: 40), ChartPointCandleStick(date: date("13.10.2015"), formatter: displayFormatter, high: 43, low: 36, open: 41, close: 38), ChartPointCandleStick(date: date("14.10.2015"), formatter: displayFormatter, high: 42, low: 31, open: 38, close: 39), ChartPointCandleStick(date: date("15.10.2015"), formatter: displayFormatter, high: 39, low: 34, open: 37, close: 36), ChartPointCandleStick(date: date("16.10.2015"), formatter: displayFormatter, high: 35, low: 32, open: 34, close: 33.5), ChartPointCandleStick(date: date("17.10.2015"), formatter: displayFormatter, high: 32, low: 29, open: 31.5, close: 31), ChartPointCandleStick(date: date("18.10.2015"), formatter: displayFormatter, high: 31, low: 29.5, open: 29.5, close: 30), ChartPointCandleStick(date: date("19.10.2015"), formatter: displayFormatter, high: 29, low: 25, open: 25.5, close: 25), ChartPointCandleStick(date: date("20.10.2015"), formatter: displayFormatter, high: 28, low: 24, open: 26.7, close: 27.5), ChartPointCandleStick(date: date("21.10.2015"), formatter: displayFormatter, high: 28.5, low: 25.3, open: 26, close: 27), ChartPointCandleStick(date: date("22.10.2015"), formatter: displayFormatter, high: 30, low: 28, open: 28, close: 30), ChartPointCandleStick(date: date("25.10.2015"), formatter: displayFormatter, high: 31, low: 29, open: 31, close: 31), ChartPointCandleStick(date: date("26.10.2015"), formatter: displayFormatter, high: 31.5, low: 29.2, open: 29.6, close: 29.6), ChartPointCandleStick(date: date("27.10.2015"), formatter: displayFormatter, high: 30, low: 27, open: 29, close: 28.5), ChartPointCandleStick(date: date("28.10.2015"), formatter: displayFormatter, high: 32, low: 30, open: 31, close: 30.6), ChartPointCandleStick(date: date("29.10.2015"), formatter: displayFormatter, high: 35, low: 31, open: 31, close: 33) ] func generateDateAxisValues(_ month: Int, year: Int) -> [ChartAxisValueDate] { let date = dateWithComponents(1, month, year) let calendar = Calendar.current let monthDays = calendar.range(of: .day, in: .month, for: date)! let arr = CountableRange<Int>(monthDays) return arr.map {day in let date = dateWithComponents(day, month, year) let axisValue = ChartAxisValueDate(date: date, formatter: displayFormatter, labelSettings: labelSettings) axisValue.hidden = !(day % 5 == 0) return axisValue } } let xValues = generateDateAxisValues(10, year: 2015) let yValues = stride(from: 20, through: 55, by: 5).map {ChartAxisValueDouble(Double($0), labelSettings: labelSettings)} let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings)) let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())) let defaultChartFrame = ExamplesDefaults.chartFrame(self.view.bounds) let infoViewHeight: CGFloat = 50 let chartFrame = CGRect(x: defaultChartFrame.origin.x, y: defaultChartFrame.origin.y + infoViewHeight, width: defaultChartFrame.width, height: defaultChartFrame.height - infoViewHeight) let coordsSpace = ChartCoordsSpaceRightBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame) let viewGenerator = {(chartPointModel: ChartPointLayerModel<ChartPointCandleStick>, layer: ChartPointsViewsLayer<ChartPointCandleStick, ChartCandleStickView>, chart: Chart) -> ChartCandleStickView? in let (chartPoint, screenLoc) = (chartPointModel.chartPoint, chartPointModel.screenLoc) let x = screenLoc.x let highScreenY = screenLoc.y let lowScreenY = layer.modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.low)).y let openScreenY = layer.modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.open)).y let closeScreenY = layer.modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.close)).y let (rectTop, rectBottom, fillColor) = closeScreenY < openScreenY ? (closeScreenY, openScreenY, UIColor.white) : (openScreenY, closeScreenY, UIColor.black) let v = ChartCandleStickView(lineX: screenLoc.x, width: Env.iPad ? 10 : 5, top: highScreenY, bottom: lowScreenY, innerRectTop: rectTop, innerRectBottom: rectBottom, fillColor: fillColor, strokeWidth: Env.iPad ? 1 : 0.5) v.isUserInteractionEnabled = false return v } let candleStickLayer = ChartPointsCandleStickViewsLayer<ChartPointCandleStick, ChartCandleStickView>(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, viewGenerator: viewGenerator) let infoView = InfoWithIntroView(frame: CGRect(x: 10, y: 70, width: self.view.frame.size.width, height: infoViewHeight)) self.view.addSubview(infoView) let trackerLayer = ChartPointsTrackerLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, locChangedFunc: {[weak candleStickLayer, weak infoView] screenLoc in candleStickLayer?.highlightChartpointView(screenLoc: screenLoc) if let chartPoint = candleStickLayer?.chartPointsForScreenLocX(screenLoc.x).first { infoView?.showChartPoint(chartPoint) } else { infoView?.clear() } }, lineColor: UIColor.red, lineWidth: Env.iPad ? 1 : 0.6) let settings = ChartGuideLinesLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayer = ChartGuideLinesLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings, onlyVisibleX: true) let dividersSettings = ChartDividersLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth, start: Env.iPad ? 7 : 3, end: 0, onlyVisibleValues: true) let dividersLayer = ChartDividersLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: dividersSettings) let chart = Chart( frame: chartFrame, layers: [ xAxis, yAxis, guidelinesLayer, dividersLayer, candleStickLayer, trackerLayer ] ) self.view.addSubview(chart.view) self.chart = chart } } private class InfoView: UIView { let statusView: UIView let dateLabel: UILabel let lowTextLabel: UILabel let highTextLabel: UILabel let openTextLabel: UILabel let closeTextLabel: UILabel let lowLabel: UILabel let highLabel: UILabel let openLabel: UILabel let closeLabel: UILabel override init(frame: CGRect) { let itemHeight: CGFloat = 40 let y = (frame.height - itemHeight) / CGFloat(2) self.statusView = UIView(frame: CGRect(x: 0, y: y, width: itemHeight, height: itemHeight)) self.statusView.layer.borderColor = UIColor.black.cgColor self.statusView.layer.borderWidth = 1 self.statusView.layer.cornerRadius = Env.iPad ? 13 : 8 let font = ExamplesDefaults.labelFont self.dateLabel = UILabel() self.dateLabel.font = font self.lowTextLabel = UILabel() self.lowTextLabel.text = "Low:" self.lowTextLabel.font = font self.lowLabel = UILabel() self.lowLabel.font = font self.highTextLabel = UILabel() self.highTextLabel.text = "High:" self.highTextLabel.font = font self.highLabel = UILabel() self.highLabel.font = font self.openTextLabel = UILabel() self.openTextLabel.text = "Open:" self.openTextLabel.font = font self.openLabel = UILabel() self.openLabel.font = font self.closeTextLabel = UILabel() self.closeTextLabel.text = "Close:" self.closeTextLabel.font = font self.closeLabel = UILabel() self.closeLabel.font = font super.init(frame: frame) self.addSubview(self.statusView) self.addSubview(self.dateLabel) self.addSubview(self.lowTextLabel) self.addSubview(self.lowLabel) self.addSubview(self.highTextLabel) self.addSubview(self.highLabel) self.addSubview(self.openTextLabel) self.addSubview(self.openLabel) self.addSubview(self.closeTextLabel) self.addSubview(self.closeLabel) } fileprivate override func didMoveToSuperview() { let views = [self.statusView, self.dateLabel, self.highTextLabel, self.highLabel, self.lowTextLabel, self.lowLabel, self.openTextLabel, self.openLabel, self.closeTextLabel, self.closeLabel] for v in views { v.translatesAutoresizingMaskIntoConstraints = false } let namedViews = views.enumerated().map{index, view in ("v\(index)", view) } var viewsDict = Dictionary<String, UIView>() for namedView in namedViews { viewsDict[namedView.0] = namedView.1 } let circleDiameter: CGFloat = Env.iPad ? 26 : 15 let labelsSpace: CGFloat = Env.iPad ? 10 : 5 let hConstraintStr = namedViews[1..<namedViews.count].reduce("H:|[v0(\(circleDiameter))]") {str, tuple in "\(str)-(\(labelsSpace))-[\(tuple.0)]" } let vConstraits = namedViews.flatMap {NSLayoutConstraint.constraints(withVisualFormat: "V:|-(18)-[\($0.0)(\(circleDiameter))]", options: NSLayoutFormatOptions(), metrics: nil, views: viewsDict)} self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: hConstraintStr, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDict) + vConstraits) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func showChartPoint(_ chartPoint: ChartPointCandleStick) { let color = chartPoint.open > chartPoint.close ? UIColor.black : UIColor.white self.statusView.backgroundColor = color self.dateLabel.text = chartPoint.x.labels.first?.text ?? "" self.lowLabel.text = "\(chartPoint.low)" self.highLabel.text = "\(chartPoint.high)" self.openLabel.text = "\(chartPoint.open)" self.closeLabel.text = "\(chartPoint.close)" } func clear() { self.statusView.backgroundColor = UIColor.clear } } private class InfoWithIntroView: UIView { var introView: UIView! var infoView: InfoView! override init(frame: CGRect) { super.init(frame: frame) } fileprivate override func didMoveToSuperview() { let label = UILabel(frame: CGRect(x: 0, y: self.bounds.origin.y, width: self.bounds.width, height: self.bounds.height)) label.text = "Drag the line to see chartpoint data" label.font = ExamplesDefaults.labelFont label.backgroundColor = UIColor.white self.introView = label self.infoView = InfoView(frame: self.bounds) self.addSubview(self.infoView) self.addSubview(self.introView) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func animateIntroAlpha(_ alpha: CGFloat) { UIView.animate(withDuration: 0.1, animations: { self.introView.alpha = alpha }) } func showChartPoint(_ chartPoint: ChartPointCandleStick) { self.animateIntroAlpha(0) self.infoView.showChartPoint(chartPoint) } func clear() { self.animateIntroAlpha(1) self.infoView.clear() } }
mit
25139ea40e10f733aecb35d83dce753a
46.702194
231
0.639942
4.454625
false
false
false
false
64characters/Telephone
UseCases/Contact.swift
1
1365
// // Contact.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 64 Characters // // Telephone is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Telephone is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // public struct Contact { public let name: String public let phones: [Phone] public let emails: [Email] public init(name: String, phones: [Phone], emails: [Email]) { self.name = name self.phones = phones self.emails = emails } public struct Phone { public let number: String public let label: String public init(number: String, label: String) { self.number = number self.label = label } } public struct Email { public let address: String public let label: String public init(address: String, label: String) { self.address = address self.label = label } } }
gpl-3.0
3e1688dd7b7a74768c54754ab1448086
26.816327
72
0.639032
4.326984
false
false
false
false
benlangmuir/swift
stdlib/public/core/Misc.swift
9
5081
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Extern C functions //===----------------------------------------------------------------------===// // FIXME: Once we have an FFI interface, make these have proper function bodies /// Returns if `x` is a power of 2. @_transparent public // @testable func _isPowerOf2(_ x: UInt) -> Bool { if x == 0 { return false } // Note: use unchecked subtraction because we have checked that `x` is not // zero. return x & (x &- 1) == 0 } /// Returns if `x` is a power of 2. @_transparent public // @testable func _isPowerOf2(_ x: Int) -> Bool { if x <= 0 { return false } // Note: use unchecked subtraction because we have checked that `x` is not // `Int.min`. return x & (x &- 1) == 0 } #if _runtime(_ObjC) @_transparent public func _autorelease(_ x: AnyObject) { Builtin.retain(x) Builtin.autorelease(x) } #endif @available(SwiftStdlib 5.7, *) @_silgen_name("swift_getFunctionFullNameFromMangledName") public // SPI (Distributed) func _getFunctionFullNameFromMangledNameImpl( _ mangledName: UnsafePointer<UInt8>, _ mangledNameLength: UInt ) -> (UnsafePointer<UInt8>, UInt) /// Given a function's mangled name, return a human readable name. /// Used e.g. by Distributed.RemoteCallTarget to hide mangled names. @available(SwiftStdlib 5.7, *) public // SPI (Distributed) func _getFunctionFullNameFromMangledName(mangledName: String) -> String? { let mangledNameUTF8 = Array(mangledName.utf8) let (stringPtr, count) = mangledNameUTF8.withUnsafeBufferPointer { (mangledNameUTF8) in return _getFunctionFullNameFromMangledNameImpl( mangledNameUTF8.baseAddress!, UInt(mangledNameUTF8.endIndex)) } guard count > 0 else { return nil } return String._fromUTF8Repairing( UnsafeBufferPointer(start: stringPtr, count: Int(count))).0 } // FIXME(ABI)#51 : this API should allow controlling different kinds of // qualification separately: qualification with module names and qualification // with type names that we are nested in. // But we can place it behind #if _runtime(_Native) and remove it from ABI on // Apple platforms, deferring discussions mentioned above. @_silgen_name("swift_getTypeName") public func _getTypeName(_ type: Any.Type, qualified: Bool) -> (UnsafePointer<UInt8>, Int) /// Returns the demangled qualified name of a metatype. @_semantics("typeName") public // @testable func _typeName(_ type: Any.Type, qualified: Bool = true) -> String { let (stringPtr, count) = _getTypeName(type, qualified: qualified) return String._fromUTF8Repairing( UnsafeBufferPointer(start: stringPtr, count: count)).0 } @available(SwiftStdlib 5.3, *) @_silgen_name("swift_getMangledTypeName") public func _getMangledTypeName(_ type: Any.Type) -> (UnsafePointer<UInt8>, Int) /// Returns the mangled name for a given type. @available(SwiftStdlib 5.3, *) public // SPI func _mangledTypeName(_ type: Any.Type) -> String? { let (stringPtr, count) = _getMangledTypeName(type) guard count > 0 else { return nil } let (result, repairsMade) = String._fromUTF8Repairing( UnsafeBufferPointer(start: stringPtr, count: count)) _precondition(!repairsMade, "repairs made to _mangledTypeName, this is not expected since names should be valid UTF-8") return result } /// Lookup a class given a name. Until the demangled encoding of type /// names is stabilized, this is limited to top-level class names (Foo.bar). public // SPI(Foundation) func _typeByName(_ name: String) -> Any.Type? { let nameUTF8 = Array(name.utf8) return nameUTF8.withUnsafeBufferPointer { (nameUTF8) in return _getTypeByMangledNameUntrusted(nameUTF8.baseAddress!, UInt(nameUTF8.endIndex)) } } @_silgen_name("swift_stdlib_getTypeByMangledNameUntrusted") internal func _getTypeByMangledNameUntrusted( _ name: UnsafePointer<UInt8>, _ nameLength: UInt) -> Any.Type? @_silgen_name("swift_getTypeByMangledNameInEnvironment") public func _getTypeByMangledNameInEnvironment( _ name: UnsafePointer<UInt8>, _ nameLength: UInt, genericEnvironment: UnsafeRawPointer?, genericArguments: UnsafeRawPointer?) -> Any.Type? @_silgen_name("swift_getTypeByMangledNameInContext") public func _getTypeByMangledNameInContext( _ name: UnsafePointer<UInt8>, _ nameLength: UInt, genericContext: UnsafeRawPointer?, genericArguments: UnsafeRawPointer?) -> Any.Type? /// Prevents performance diagnostics in the passed closure. @_alwaysEmitIntoClient @_semantics("no_performance_analysis") public func _unsafePerformance<T>(_ c: () -> T) -> T { return c() }
apache-2.0
a9b7e611137befe4b4f1b6b97a74b57e
31.570513
121
0.687069
4.134255
false
false
false
false
justinsacbibit/JSPoppingOverlay-Swift
JSPoppingOverlay-Swift/JSPoppingOverlay/JSPoppingOverlay.swift
1
6628
// // JSPoppingOverlay.swift // JSPoppingOverlay-Swift // // Created by Justin Sacbibit on 2014-08-24. // Copyright (c) 2014 Justin Sacbibit. All rights reserved. // import UIKit class JSPoppingOverlay: UIView { private var isPopping = false private var containerView: UIView private var backgroundOverlayView: UIView private var poppingImageView: UIImageView private var textLabel: UILabel private var _backgroundOverlayAlpha: CGFloat var backgroundOverlayColor: UIColor { get { return self.backgroundOverlayView.backgroundColor! } set(backgroundOverlayColor) { self.backgroundOverlayView.backgroundColor = backgroundOverlayColor } } var backgroundOverlayAlpha: CGFloat { get { return self._backgroundOverlayAlpha } set(backgroundOverlayAlpha) { self._backgroundOverlayAlpha = backgroundOverlayAlpha self.backgroundOverlayView.alpha = backgroundOverlayAlpha } } var textColor: UIColor { get { return self.textLabel.textColor } set(textColor) { self.textLabel.textColor = textColor } } var font: UIFont { get { return self.textLabel.font } set(font) { self.textLabel.font = font } } var successImage: UIImage? var errorImage: UIImage? var customImage: UIImage? var animationDuration: NSTimeInterval = 0.2 var duration: NSTimeInterval = 0.5 override init() { self.backgroundOverlayView = UIView() self.backgroundOverlayView.backgroundColor = UIColor.blackColor() self._backgroundOverlayAlpha = 0.75 self.backgroundOverlayView.alpha = self._backgroundOverlayAlpha self.containerView = UIView() self.poppingImageView = UIImageView() self.poppingImageView.contentMode = UIViewContentMode.Center self.poppingImageView.backgroundColor = UIColor.clearColor() self.textLabel = UILabel() self.textLabel.textColor = UIColor.whiteColor() self.textLabel.textAlignment = NSTextAlignment.Center self.textLabel.numberOfLines = 1 self.textLabel.font = UIFont(name: "HelveticaNeue-Light", size: 14.0) self.successImage = UIImage(named: "success") self.errorImage = UIImage(named: "error") super.init(frame: frame) self.addSubview(self.backgroundOverlayView) self.addSubview(self.containerView) self.containerView.addSubview(self.poppingImageView) self.containerView.addSubview(self.textLabel) self.layer.masksToBounds = true self.clipsToBounds = true } required init(coder: NSCoder) { fatalError("NSCoding not supported") } func isVisible() -> Bool { return self.isPopping } func showOverlay(#image: UIImage?, onView view: UIView, withMessage message: NSString?) { if (image == nil && message == nil) { fatalError("Attempt to be shown without content") } if (self.isPopping) { return; } self.isPopping = true self.frame = view.bounds var frame = CGRect() frame.origin.x = 0.0 frame.origin.y = 0.0 frame.size.width = CGRectGetWidth(self.bounds) frame.size.height = CGRectGetHeight(self.bounds) self.backgroundOverlayView.frame = frame if image != nil { self.poppingImageView.image = image frame.size.height = self.poppingImageView.image.size.height } else { frame.size.height = 0.0 } self.poppingImageView.frame = frame var scale: CGFloat = 1.8 self.poppingImageView.transform = CGAffineTransformMakeScale(scale, scale) var topPadding: CGFloat = (message != nil && image != nil) ? 10.0 : 0.0 frame.origin.y = CGRectGetMaxY(frame) + topPadding if let unwrappedMessage = message? { frame.size.height = unwrappedMessage.sizeWithAttributes([NSFontAttributeName: self.font]).height self.textLabel.frame = frame self.textLabel.text = message } else { self.textLabel.frame = CGRectZero } frame.size.height = CGRectGetHeight(self.poppingImageView.bounds) + topPadding + CGRectGetHeight(self.textLabel.bounds) frame.origin.y = (CGRectGetHeight(self.bounds) - frame.size.height) / 2.0 self.containerView.frame = frame view.addSubview(self) UIView.animateWithDuration(self.animationDuration, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.2, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in self.poppingImageView.transform = CGAffineTransformIdentity }) { (finished) -> Void in UIView.animateWithDuration(self.animationDuration, delay: self.duration, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in self.backgroundOverlayView.alpha = 0.0 self.poppingImageView.alpha = 0.0 self.poppingImageView.transform = CGAffineTransformMakeScale(0.2, 0.2) frame.origin.y = CGRectGetMaxY(self.bounds) self.textLabel.frame = frame self.textLabel.alpha = 0.0 }, completion: { (finished) -> Void in self.removeFromSuperview() self.reset() }) } } func showCustomImage(onView view: UIView, withMessage message: NSString?) { self.showOverlay(image: self.customImage, onView: view, withMessage: message) } func showSuccess(onView view: UIView, withMessage message: NSString?) { self.showOverlay(image: self.successImage, onView: view, withMessage: message) } func showError(onView view: UIView, withMessage message: NSString?) { self.showOverlay(image: self.errorImage, onView: view, withMessage: message) } func hideImmediately() { self.removeFromSuperview() } private func reset() { self.backgroundOverlayView.alpha = self.backgroundOverlayAlpha self.poppingImageView.alpha = 1.0 self.poppingImageView.transform = CGAffineTransformIdentity self.textLabel.alpha = 1.0 self.isPopping = true } }
mit
73b19253824b0a8ea447d882dd45fff8
33.701571
200
0.622963
4.913269
false
false
false
false
geosor/SymondsStudentApp
Sources/SSACore/Timetable/Day.swift
1
4494
// // Day.swift // SSACore // // Created by Søren Mortensen on 16/12/2017. // Copyright © 2017 Søren Mortensen, George Taylor. All rights reserved. // import Foundation /// A day of the week. /// /// This enum is fully equipped for specialised use in tracking the days of the week on which particular /// `TimetableItem`s take place. This includes the raw values of the cases, which represent days of the week, /// `Day.today`, which returns the day of the week at the current moment, and the methods `dateThisWeek(from:)` and /// `dayThisWeek(for:)`, which are used for converting between `Day`s and `Date`s. /// /// - SeeAlso: `TimetableItem` public enum Day: Int, CustomStringConvertible { case monday = 0, tuesday, wednesday, thursday, friday, saturday, sunday // MARK: - Static Properties /// The day of the week for today. public static var today: Day { var weekday = calendar.component(.weekday, from: calendar.today()) - 2 // Change Sunday to 6 instead of -1, so that the numbers (and therefore the days' raw values) reflect how many // days they are after the start of the week (Monday). if weekday == -1 { weekday += 7 } let day = Day(rawValue: weekday)! return day } /// The days of the week in an array, going from Monday to Sunday. public static var week: [Day] = [.monday, .tuesday, .wednesday, .thursday, .friday, .saturday, .sunday] internal static var calendar: CalendarProtocol = Calendar.current // MARK: - Static Functions /// Calculates this week's date for a particular day of the week, going backwards if necessary. /// /// - Parameter day: The day of the week for which to calculate the date. /// - Returns: The date of that day of the week. Note that this is the *start of the day* on that date. public static func dateThisWeek(from day: Day) -> Date { let difference = day.rawValue - Day.today.rawValue return calendar.startOfDay(for: calendar.today()).addingTimeInterval(60 * 60 * 24 * TimeInterval(difference)) } /// Returns the weekday of a date within this week. If the provided date is not within this week, returns `nil`. /// /// - Parameter date: The date to convert. /// - Returns: The day of the week if the provided date is within this week; otherwise, `nil`. public static func dayThisWeek(for date: Date) -> Day? { let dateToday = dateThisWeek(from: .today) let otherDate = calendar.startOfDay(for: date) let differenceSeconds = otherDate.timeIntervalSince(dateToday) let differenceDays = Int(differenceSeconds / 60 / 60 / 24) guard differenceDays >= -today.rawValue && differenceDays <= 7 - today.rawValue else { return nil } return Day(rawValue: today.rawValue + differenceDays) } // MARK: - CustomStringConvertible /// :nodoc: public var description: String { switch self { case .monday: return "Monday" case .tuesday: return "Tuesday" case .wednesday: return "Wednesday" case .thursday: return "Thursday" case .friday: return "Friday" case .saturday: return "Saturday" case .sunday: return "Sunday" } } } // MARK: - Comparable extension Day: Comparable { /// :nodoc: public static func < (lhs: Day, rhs: Day) -> Bool { let lhsWeekday = lhs == .sunday ? lhs.rawValue + 7 : lhs.rawValue let rhsWeekday = rhs == .sunday ? lhs.rawValue + 7 : rhs.rawValue return lhsWeekday < rhsWeekday } /// :nodoc: public static func <= (lhs: Day, rhs: Day) -> Bool { let lhsWeekday = lhs == .sunday ? lhs.rawValue + 7 : lhs.rawValue let rhsWeekday = rhs == .sunday ? lhs.rawValue + 7 : rhs.rawValue return lhsWeekday <= rhsWeekday } /// :nodoc: public static func >= (lhs: Day, rhs: Day) -> Bool { let lhsWeekday = lhs == .sunday ? lhs.rawValue + 7 : lhs.rawValue let rhsWeekday = rhs == .sunday ? lhs.rawValue + 7 : rhs.rawValue return lhsWeekday >= rhsWeekday } /// :nodoc: public static func > (lhs: Day, rhs: Day) -> Bool { let lhsWeekday = lhs == .sunday ? lhs.rawValue + 7 : lhs.rawValue let rhsWeekday = rhs == .sunday ? lhs.rawValue + 7 : rhs.rawValue return lhsWeekday > rhsWeekday } }
mit
a39855aecf780706d7e8878671eab8bf
36.739496
118
0.623914
4.248817
false
false
false
false
ancilmarshall/iOS
General/TextViewKeyboardResize/TextViewKeyboardResize/ResizableTextView.swift
1
1035
// // ResizableTextView.swift // TextViewKeyboardResize // // Created by Ancil on 8/4/15. // Copyright (c) 2015 Ancil Marshall. All rights reserved. // import UIKit /* NOTE & ACKNOWLEDGEMENT This great and concise code is taken from GitHub Nikita2k/resizableTextView code, and converted by me into Swift */ class ResizableTextView: UITextView { override func updateConstraints() { //println("updateConstraints - Text") var contentSize = sizeThatFits(CGSizeMake(frame.size.width, CGFloat.max)) if let allConstraints = constraints() as? [NSLayoutConstraint] { for constraint in allConstraints { if constraint.firstAttribute == NSLayoutAttribute.Height { constraint.constant = contentSize.height break } } } super.updateConstraints() } override func layoutSubviews() { //println("layoutSubviews - Text") super.layoutSubviews() } }
gpl-2.0
2152f85757509899e3283ea8ad8698a6
25.538462
81
0.619324
4.905213
false
false
false
false
iaagg/Saturn
Saturn/Classes/SaturnCounter.swift
1
3786
// // SaturnCounter.swift // Pods // // Created by Alexey Getman on 22/10/2016. // // import UIKit public enum DateCraftingResultType { //In this case Saturn has calculated time properly and you can rely on it. case CraftedDateIsReliable //In this case Saturn tried to calculate time properly, but there is a chance that it is not accurate. case CraftedDateIsUnreliable //In this case Saturn can't count time properly due to some reasons. You should try to make a sync point to make time counting possible. case CraftingReliableDateIsImpossible } class SaturnCounter: NSObject { public class func getCalculatedAtomicTime(result: (Double, DateCraftingResultType) -> ()) { let saturnData = SaturnStorage.storage().saturnData var calculatedAtomicTime: Double = 0 let currentAtomicTime = SaturnTimeMine.getAtomicTime() var resultType: DateCraftingResultType = .CraftedDateIsReliable switch SaturnJustice.justice().verdict { case .DeviceRebooted: calculatedAtomicTime += saturnData.lastSyncedBootAtomicTime calculatedAtomicTime = addUnsyncTime(toTime: calculatedAtomicTime) calculatedAtomicTime += currentAtomicTime; break case .DeviceWasNotRebooted: //If we have any unsynced data -> there were any reboot already in past before syncronization // // So all atomic time consits of: |Last synced boot time| + |All saved unsynced boots time exept last| + |Current atomic time since reboot| if saturnData.arrayOfUnsyncedBootsAtomicTime.count > 0 { calculatedAtomicTime += saturnData.lastSyncedBootAtomicTime calculatedAtomicTime = addUnsyncTimeExeptLast(toTime: calculatedAtomicTime) calculatedAtomicTime += currentAtomicTime; //We don't have any unsynced data -> // // So |Current atomic time since reboot| is actual } else { calculatedAtomicTime = currentAtomicTime } break case .NotSure: calculatedAtomicTime = currentAtomicTime resultType = .CraftedDateIsUnreliable break } result(calculatedAtomicTime, resultType) } //Adds all saved unsynced boots time (time of working after reboot) private class func addUnsyncTime(toTime time:Double) -> Double { var receivedTime = time let saturnData = SaturnStorage.storage().saturnData if saturnData.arrayOfUnsyncedBootsAtomicTime.count > 0 { for (_, value) in saturnData.arrayOfUnsyncedBootsAtomicTime.enumerated() { receivedTime += (value as! NSNumber).doubleValue } } return receivedTime } //Adds all saved unsynced boots time (time of working after reboot) exept last private class func addUnsyncTimeExeptLast(toTime time: Double) -> Double { var receivedTime = time let saturnData = SaturnStorage.storage().saturnData if saturnData.arrayOfUnsyncedBootsAtomicTime.count > 0 { let lastUnsyncTimeIndex: NSInteger = saturnData.arrayOfUnsyncedBootsAtomicTime.count - 1 for (index, _) in saturnData.arrayOfUnsyncedBootsAtomicTime.enumerated() { if index == lastUnsyncTimeIndex { break; } receivedTime += (saturnData.arrayOfUnsyncedBootsAtomicTime[index] as! NSNumber).doubleValue } } return time; } }
mit
71bf387b772d8d566326e87e4800c24b
36.117647
152
0.625198
4.936115
false
false
false
false
getsocial-im/getsocial-ios-sdk
example/GetSocialDemo/Views/Communities/Groups/MyGroups/MyGroupsViewController.swift
1
8830
// // GenericPagingViewController.swift // GetSocialDemo // // Copyright © 2020 GetSocial BV. All rights reserved. // import UIKit protocol MyGroupTableViewControllerDelegate { func onShowFeed(_ ofGroupId: String) func onShowPolls(_ ofGroupId: String) func onShowAnnouncementsPolls(_ ofGroupId: String) func onShowGroupMembers(_ ofGroupId: String, role: Role) func onPostActivity(_ groupId: String) func onCreatePoll(_ groupId: String) func onEditGroup(_ group: Group) } class MyGroupsViewController: UIViewController { var viewModel: MyGroupsModel = MyGroupsModel() var delegate: MyGroupTableViewControllerDelegate? var loadingOlders: Bool = false var tableView: UITableView = UITableView() override func viewDidLoad() { super.viewDidLoad() self.tableView.backgroundColor = UIDesign.Colors.viewBackground self.tableView.register(GroupTableViewCell.self, forCellReuseIdentifier: "grouptableviewcell") self.tableView.allowsSelection = false self.title = "Groups" self.viewModel.onInitialDataLoaded = { self.hideActivityIndicatorView() self.tableView.reloadData() } self.viewModel.onDidOlderLoad = { needReload in self.hideActivityIndicatorView() self.loadingOlders = false if needReload { self.tableView.reloadData() } } self.viewModel.onError = { error in self.hideActivityIndicatorView() self.showAlert(withText: error) } self.viewModel.groupFollowed = { itemIndex in self.hideActivityIndicatorView() let indexToReload = IndexPath.init(row: itemIndex, section: 0) self.tableView.reloadRows(at: [indexToReload], with: .automatic) self.showAlert(withText: "Group followed") } self.viewModel.groupUnfollowed = { itemIndex in self.hideActivityIndicatorView() let indexToReload = IndexPath.init(row: itemIndex, section: 0) self.tableView.reloadRows(at: [indexToReload], with: .automatic) self.showAlert(withText: "Group unfollowed") } self.viewModel.onGroupDeleted = { itemIndex in self.hideActivityIndicatorView() let indexToReload = IndexPath.init(row: itemIndex, section: 0) self.tableView.deleteRows(at: [indexToReload], with: .automatic) self.showAlert(withText: "Group removed") } self.viewModel.onGroupLeft = { itemIndex in self.hideActivityIndicatorView() let indexToDelete = IndexPath.init(row: itemIndex, section: 0) self.tableView.deleteRows(at: [indexToDelete], with: .automatic) self.showAlert(withText: "Group left") } self.viewModel.onInviteAccepted = { itemIndex in self.hideActivityIndicatorView() let indexToReload = IndexPath.init(row: itemIndex, section: 0) self.tableView.reloadRows(at: [indexToReload], with: .automatic) self.showAlert(withText: "Invitation accepted") } self.tableView.dataSource = self self.tableView.delegate = self self.view.addSubview(self.tableView) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.executeQuery() } override func viewWillLayoutSubviews() { layoutTableView() } internal func layoutTableView() { tableView.translatesAutoresizingMaskIntoConstraints = false let top = tableView.topAnchor.constraint(equalTo: self.view.topAnchor) let left = tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor) let right = tableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor) let bottom = tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor) NSLayoutConstraint.activate([left, top, right, bottom]) } private func executeQuery() { self.showActivityIndicatorView() self.viewModel.loadEntries() } func scrollViewDidScroll(_ scrollView: UIScrollView) { let actualPosition = scrollView.contentOffset.y let contentHeight = scrollView.contentSize.height - scrollView.frame.size.height if actualPosition > 0 && self.viewModel.numberOfEntries() > 0 && actualPosition > contentHeight && !self.loadingOlders { self.loadingOlders = true self.showActivityIndicatorView() self.viewModel.loadOlder() } } } extension MyGroupsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 170 } } extension MyGroupsViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.viewModel.numberOfEntries() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "grouptableviewcell") as? GroupTableViewCell let item = self.viewModel.entry(at: indexPath.row) cell?.update(group: item) cell?.delegate = self return cell ?? UITableViewCell() } } extension MyGroupsViewController: GroupTableViewCellDelegate { func onShowAction(_ groupId: String, isFollowed: Bool) { let actionSheet = UIAlertController.init(title: "Available actions", message: nil, preferredStyle: .actionSheet) if let group = self.viewModel.findGroup(groupId) { let role = group.membership?.role let status = group.membership?.status actionSheet.addAction(UIAlertAction.init(title: "Details", style: .default, handler: { _ in self.showAlert(withText: group.description) })) if !group.settings.isPrivate || status == .member { actionSheet.addAction(UIAlertAction.init(title: "Show Feed", style: .default, handler: { _ in self.delegate?.onShowFeed(groupId) })) actionSheet.addAction(UIAlertAction.init(title: "Activities with Polls", style: .default, handler: { _ in self.delegate?.onShowPolls(groupId) })) actionSheet.addAction(UIAlertAction.init(title: "Announcements with Polls", style: .default, handler: { _ in self.delegate?.onShowAnnouncementsPolls(groupId) })) } if status == .member { if let role = role { actionSheet.addAction(UIAlertAction.init(title: "Show Members", style: .default, handler: { _ in self.delegate?.onShowGroupMembers(groupId, role: role) })) } if group.settings.isActionAllowed(action: .post) { actionSheet.addAction(UIAlertAction.init(title: "Post", style: .default, handler: { _ in self.delegate?.onPostActivity(groupId) })) } if group.settings.isActionAllowed(action: .post) { actionSheet.addAction(UIAlertAction.init(title: "Create Poll", style: .default, handler: { _ in self.delegate?.onCreatePoll(groupId) })) } if role == .admin || role == .owner { actionSheet.addAction(UIAlertAction.init(title: "Edit", style: .default, handler: { _ in self.delegate?.onEditGroup(group) })) actionSheet.addAction(UIAlertAction.init(title: "Delete", style: .default, handler: { _ in self.viewModel.deleteGroup(groupId) })) } actionSheet.addAction(UIAlertAction.init(title: isFollowed ? "Unfollow" : "Follow", style: .default, handler: { _ in self.showActivityIndicatorView() self.viewModel.followGroup(groupId) })) } if status == .invitationPending { actionSheet.addAction(UIAlertAction.init(title: "Approve invitation", style: .default, handler: { _ in self.showActivityIndicatorView() self.viewModel.acceptInvite(groupId, membership: group.membership!) })) } if group.membership?.role != .owner { actionSheet.addAction(UIAlertAction.init(title: "Leave", style: .default, handler: { _ in self.viewModel.leaveGroup(groupId) })) } } actionSheet.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil)) self.present(actionSheet, animated: true, completion: nil) } }
apache-2.0
6a2a281f33b9b35487bc7d60ef843fa7
40.065116
128
0.635406
4.880597
false
false
false
false
chris-schwartz/ios-swift-flickr-client
FlickrClient/FlickrConfiguration.swift
1
1525
// // FlickrConfiguration.swift // ImageRequest // // Created by Chris Schwartz on 5/10/16. // Copyright © 2016 SchwartzCode. All rights reserved. // import Foundation struct FlickrApiConfiguration { enum ResponseFormat : CustomStringConvertible{ case JSON, XML; var description : String { switch self { case.JSON: return "json" case.XML: return "rest" } } } let apiKey : String let secret : String let responseFormat : ResponseFormat let timeoutInterval : NSTimeInterval? let cachingPolicy : NSURLRequestCachePolicy? init(apiKey flickrApiKey: String, secret: String, responseFormat: ResponseFormat, timeoutInterval: NSTimeInterval?, cachingPolicy: NSURLRequestCachePolicy?) { self.apiKey = flickrApiKey self.secret = secret self.responseFormat = responseFormat self.timeoutInterval = timeoutInterval self.cachingPolicy = cachingPolicy } init(apiKey flickrApiKey: String, secret: String, responseFormat: ResponseFormat, timeoutInterval: NSTimeInterval?) { self.init(apiKey: flickrApiKey, secret: secret, responseFormat: responseFormat, timeoutInterval: timeoutInterval, cachingPolicy: nil) } init(apiKey flickrApiKey: String, secret: String, responseFormat: ResponseFormat) { self.init(apiKey: flickrApiKey, secret: secret, responseFormat: responseFormat, timeoutInterval: nil) } }
mit
214c53f82915df86c1c60acde36fc7cf
32.152174
141
0.674541
5.046358
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-ios-demo
AwesomeAdsDemo/LoginController.swift
1
2218
import UIKit import RxCocoa import RxSwift import SuperAwesome class LoginController: SABaseViewController { fileprivate let maxContraintHeight: CGFloat = 67.0 fileprivate let minContraintHeight: CGFloat = 0.0 @IBOutlet weak var mainLogo: UIImageView! @IBOutlet weak var usernameField: SATextField! @IBOutlet weak var passwordField: SATextField! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var topContraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() loginButton.setTitle("page_login_button_login".localized, for: .normal) usernameField.placeholder = "page_login_textfield_user_placeholder".localized passwordField.placeholder = "page_login_textfield_password_placeholder".localized } @IBAction func loginAction(_ sender: Any) { store?.dispatch(Event.LoadingJwtToken) let username = usernameField.text ?? "" let password = passwordField.text ?? "" store?.dispatch(Event.loginUser(withUsername: username, andPassword: password)) } override func handle(_ state: AppState) { let loginState = state.loginState topContraint.constant = loginState.isEditing ? minContraintHeight : maxContraintHeight loginButton.isHidden = loginState.isLoading activityIndicator.isHidden = !loginState.isLoading if loginState.loginError { authError() } if loginState.jwtToken != nil { performSegue("LoginToLoad") } } } extension LoginController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { store?.dispatch(Event.EditLoginDetails) } } extension LoginController { fileprivate func authError () { Alert.show( title: "page_login_popup_more_title".localized, message: "page_login_popup_more_message".localized, presenter: self, confirmButtonTitle: "page_login_popup_more_ok_button".localized, confirmAction: nil ) } }
apache-2.0
ee5e816b6c69494d2191991f16a9c248
30.239437
94
0.666366
5.122402
false
false
false
false
svyatoslav-reshetnikov/EPCalendarPicker
EPCalendar/EPCalendarPicker/EPCalendarPicker.swift
1
14961
// // EPCalendarPicker.swift // EPCalendar // // Created by Prabaharan Elangovan on 02/11/15. // Copyright © 2015 Prabaharan Elangovan. All rights reserved. // import UIKit private let reuseIdentifier = "Cell" @objc public protocol EPCalendarPickerDelegate{ @objc optional func epCalendarPicker(_: EPCalendarPicker, didCancel error : NSError) @objc optional func epCalendarPicker(_: EPCalendarPicker, didSelectDate date : Date) @objc optional func epCalendarPicker(_: EPCalendarPicker, didSelectMultipleDate dates : [Date]) } public class EPCalendarPicker: UICollectionViewController { public var calendarDelegate : EPCalendarPickerDelegate? public var multiSelectEnabled: Bool public var showsTodaysButton: Bool = true fileprivate var arrSelectedDates = [Date]() public var tintColor: UIColor public var dayDisabledTintColor: UIColor public var weekdayTintColor: UIColor public var weekendTintColor: UIColor public var todayTintColor: UIColor public var dateSelectionColor: UIColor public var monthTitleColor: UIColor // new options public var startDate: Date? public var endDate: Date? public var hightlightsToday: Bool = true public var hideDaysFromOtherMonth: Bool = false public var barTintColor: UIColor public var backgroundImage: UIImage? public var backgroundColor: UIColor? public var datesCount: Int? fileprivate(set) public var startYear: Int fileprivate(set) public var endYear: Int override public func viewDidLoad() { super.viewDidLoad() // setup Navigationbar navigationController?.navigationBar.tintColor = tintColor navigationController?.navigationBar.barTintColor = barTintColor navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: tintColor] // setup collectionview collectionView?.delegate = self collectionView?.backgroundColor = UIColor.clear collectionView?.showsHorizontalScrollIndicator = false collectionView?.showsVerticalScrollIndicator = false // Register cell classes collectionView!.register(UINib(nibName: "EPCalendarCell1", bundle: Bundle(for: EPCalendarPicker.self )), forCellWithReuseIdentifier: reuseIdentifier) collectionView!.register(UINib(nibName: "EPCalendarHeaderView", bundle: Bundle(for: EPCalendarPicker.self )), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header") inititlizeBarButtons() DispatchQueue.main.async { self.scrollToToday() } if backgroundImage != nil { collectionView!.backgroundView = UIImageView(image: backgroundImage) } else if backgroundColor != nil { collectionView?.backgroundColor = backgroundColor } else { collectionView?.backgroundColor = UIColor.white } } func inititlizeBarButtons(){ let cancelButton = UIBarButtonItem(title: "Отмена", style: .plain, target: self, action: #selector(EPCalendarPicker.onTouchCancelButton)) self.navigationItem.leftBarButtonItem = cancelButton var arrayBarButtons = [UIBarButtonItem]() if multiSelectEnabled { let doneButton = UIBarButtonItem(title: "Готово", style: .done, target: self, action: #selector(EPCalendarPicker.onTouchDoneButton)) arrayBarButtons.append(doneButton) } if showsTodaysButton { let todayButton = UIBarButtonItem(title: "Today", style: .plain, target: self, action:#selector(EPCalendarPicker.onTouchTodayButton)) arrayBarButtons.append(todayButton) todayButton.tintColor = todayTintColor } self.navigationItem.rightBarButtonItems = arrayBarButtons } public convenience init(){ self.init(startYear: EPDefaults.startYear, endYear: EPDefaults.endYear, multiSelection: EPDefaults.multiSelection, selectedDates: nil); } public convenience init(startYear: Int, endYear: Int) { self.init(startYear:startYear, endYear:endYear, multiSelection: EPDefaults.multiSelection, selectedDates: nil) } public convenience init(multiSelection: Bool) { self.init(startYear: EPDefaults.startYear, endYear: EPDefaults.endYear, multiSelection: multiSelection, selectedDates: nil) } public convenience init(startYear: Int, endYear: Int, multiSelection: Bool) { self.init(startYear: EPDefaults.startYear, endYear: EPDefaults.endYear, multiSelection: multiSelection, selectedDates: nil) } public init(startYear: Int, endYear: Int, multiSelection: Bool, selectedDates: [Date]?) { self.startYear = startYear self.endYear = endYear self.multiSelectEnabled = multiSelection //Text color initializations self.tintColor = EPDefaults.tintColor self.barTintColor = EPDefaults.barTintColor self.dayDisabledTintColor = EPDefaults.dayDisabledTintColor self.weekdayTintColor = EPDefaults.weekdayTintColor self.weekendTintColor = EPDefaults.weekendTintColor self.dateSelectionColor = EPDefaults.dateSelectionColor self.monthTitleColor = EPDefaults.monthTitleColor self.todayTintColor = EPDefaults.todayTintColor //Layout creation let layout = UICollectionViewFlowLayout() //layout.sectionHeadersPinToVisibleBounds = true // If you want make a floating header enable this property(Avaialble after iOS9) layout.minimumInteritemSpacing = 1 layout.minimumLineSpacing = 1 layout.headerReferenceSize = EPDefaults.headerSize if let _ = selectedDates { self.arrSelectedDates.append(contentsOf: selectedDates!) } super.init(collectionViewLayout: layout) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: UICollectionViewDataSource override public func numberOfSections(in collectionView: UICollectionView) -> Int { // #warning Incomplete implementation, return the number of sections if startYear > endYear { return 0 } let numberOfMonths = 12 * (endYear - startYear) + 12 return numberOfMonths } override public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let startDate = Date(year: startYear, month: 1, day: 1) let firstDayOfMonth = startDate.dateByAddingMonths(section) let addingPrefixDaysWithMonthDyas = ( firstDayOfMonth.numberOfDaysInMonth() + firstDayOfMonth.weekday() - Calendar.current.firstWeekday ) let addingSuffixDays = addingPrefixDaysWithMonthDyas%7 var totalNumber = addingPrefixDaysWithMonthDyas if addingSuffixDays != 0 { totalNumber = totalNumber + (7 - addingSuffixDays) } return totalNumber } override public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! EPCalendarCell1 let calendarStartDate = Date(year:startYear, month: 1, day: 1) let firstDayOfThisMonth = calendarStartDate.dateByAddingMonths(indexPath.section) let prefixDays = ( firstDayOfThisMonth.weekday() - Calendar.current.firstWeekday) if indexPath.row >= prefixDays { cell.isCellSelectable = true let currentDate = firstDayOfThisMonth.dateByAddingDays(indexPath.row-prefixDays) let nextMonthFirstDay = firstDayOfThisMonth.dateByAddingDays(firstDayOfThisMonth.numberOfDaysInMonth()-1) cell.currentDate = currentDate cell.lblDay.text = "\(currentDate.day())" if arrSelectedDates.filter({ $0.isDateSameDay(currentDate) }).count > 0 && (firstDayOfThisMonth.month() == currentDate.month()) { cell.selectedForLabelColor(dateSelectionColor) } else{ cell.deSelectedForLabelColor(weekdayTintColor) if cell.currentDate.isSaturday() || cell.currentDate.isSunday() { cell.lblDay.textColor = weekendTintColor } if (currentDate > nextMonthFirstDay) { cell.isCellSelectable = false if hideDaysFromOtherMonth { cell.lblDay.textColor = UIColor.clear } else { cell.lblDay.textColor = self.dayDisabledTintColor } } if currentDate.isToday() && hightlightsToday { cell.setTodayCellColor(todayTintColor) } if startDate != nil { if Calendar.current.startOfDay(for: cell.currentDate as Date) < NSCalendar.current.startOfDay(for: startDate! as Date) { cell.isCellSelectable = false cell.lblDay.textColor = self.dayDisabledTintColor } } if endDate != nil { if Calendar.current.startOfDay(for: cell.currentDate as Date) > NSCalendar.current.startOfDay(for: endDate! as Date) { cell.isCellSelectable = false cell.lblDay.textColor = self.dayDisabledTintColor } } } } else { cell.deSelectedForLabelColor(weekdayTintColor) cell.isCellSelectable = false let previousDay = firstDayOfThisMonth.dateByAddingDays(-( prefixDays - indexPath.row)) cell.currentDate = previousDay cell.lblDay.text = "\(previousDay.day())" if hideDaysFromOtherMonth { cell.lblDay.textColor = UIColor.clear } else { cell.lblDay.textColor = self.dayDisabledTintColor } } cell.backgroundColor = UIColor.clear return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { let rect = UIScreen.main.bounds let screenWidth = rect.size.width - 7 return CGSize(width: screenWidth/7, height: screenWidth/7); } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(5, 0, 5, 0); //top,left,bottom,right } override public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader { let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header", for: indexPath) as! EPCalendarHeaderView let startDate = Date(year: startYear, month: 1, day: 1) let firstDayOfMonth = startDate.dateByAddingMonths(indexPath.section) header.lblTitle.text = firstDayOfMonth.monthNameFull() header.lblTitle.textColor = monthTitleColor header.updateWeekdaysLabelColor(weekdayTintColor) header.updateWeekendLabelColor(weekendTintColor) header.backgroundColor = UIColor.clear return header; } return UICollectionReusableView() } override public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! EPCalendarCell1 if !multiSelectEnabled && cell.isCellSelectable! { calendarDelegate?.epCalendarPicker!(self, didSelectDate: cell.currentDate) cell.selectedForLabelColor(dateSelectionColor) dismiss(animated: true, completion: nil) return } if cell.isCellSelectable! { if arrSelectedDates.filter({ $0.isDateSameDay(cell.currentDate) }).count == 0 { arrSelectedDates.append(cell.currentDate) cell.selectedForLabelColor(dateSelectionColor) if cell.currentDate.isToday() { cell.setTodayCellColor(dateSelectionColor) } } else { arrSelectedDates = arrSelectedDates.filter(){ return !($0.isDateSameDay(cell.currentDate)) } if cell.currentDate.isSaturday() || cell.currentDate.isSunday() { cell.deSelectedForLabelColor(weekendTintColor) } else { cell.deSelectedForLabelColor(weekdayTintColor) } if cell.currentDate.isToday() && hightlightsToday{ cell.setTodayCellColor(todayTintColor) } } } if arrSelectedDates.count > datesCount! { arrSelectedDates.removeFirst() collectionView.reloadData() } } //MARK: Button Actions internal func onTouchCancelButton() { //TODO: Create a cancel delegate calendarDelegate?.epCalendarPicker!(self, didCancel: NSError(domain: "EPCalendarPickerErrorDomain", code: 2, userInfo: [ NSLocalizedDescriptionKey: "User Canceled Selection"])) dismiss(animated: true, completion: nil) } internal func onTouchDoneButton() { //gathers all the selected dates and pass it to the delegate calendarDelegate?.epCalendarPicker!(self, didSelectMultipleDate: arrSelectedDates) dismiss(animated: true, completion: nil) } internal func onTouchTodayButton() { scrollToToday() } public func scrollToToday () { let today = Date() scrollToMonthForDate(today) } public func scrollToMonthForDate (_ date: Date) { let month = date.month() let year = date.year() let section = ((year - startYear) * 12) + month let indexPath = IndexPath(row:1, section: section-1) self.collectionView?.scrollToIndexpathByShowingHeader(indexPath) } }
mit
5b3116dbee91f1d605febcb53e7d7b3e
39.84153
214
0.646575
5.49155
false
false
false
false
eweill/Forge
Forge/Forge/DepthwiseConvolution.swift
2
5244
/* Copyright (c) 2016-2017 M.I. Hollemans 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 Metal import MetalPerformanceShaders import Accelerate /** Depth-wise convolution Applies a different convolution kernel to each input channel. Only a single kernel is applied to each input channel and so the number of output channels is the same as the number of input channels. A depth-wise convolution only performs filtering; it doesn't combine channels to create new features like a regular convolution does. - Note: On iOS 11 and up, use MPSCNNDepthWiseConvolutionDescriptor instead. */ public class DepthwiseConvolutionKernel: ForgeKernel { let pipeline: MTLComputePipelineState let weightsBuffer: MTLBuffer let biasBuffer: MTLBuffer /** Creates a new DepthwiseConvolution object. - Parameters: - channelMultiplier: If this is M, then each input channel has M kernels applied to it, resulting in M output channels for each input channel. Default is 1. - relu: If true, applies a ReLU to the output. Default is false. - kernelWeights: The weights should be arranged in memory like this: `[featureChannels][kernelHeight][kernelWidth]`. - biasTerms: One bias term per channel (optional). */ public init(device: MTLDevice, kernelWidth: Int, kernelHeight: Int, featureChannels: Int, strideInPixelsX: Int = 1, strideInPixelsY: Int = 1, channelMultiplier: Int = 1, neuronFilter: MPSCNNNeuron?, kernelWeights: UnsafePointer<Float>, biasTerms: UnsafePointer<Float>?) { precondition(kernelWidth == 3 && kernelHeight == 3, "Only 3x3 kernels are currently supported") precondition(channelMultiplier == 1, "Channel multipliers are not supported yet") let outputSlices = (featureChannels + 3) / 4 let paddedOutputChannels = outputSlices * 4 let count = paddedOutputChannels * kernelHeight * kernelWidth weightsBuffer = device.makeBuffer(length: MemoryLayout<Float16>.stride * count)! let ptr = UnsafeMutablePointer(mutating: kernelWeights) let copyCount = featureChannels * kernelHeight * kernelWidth float32to16(input: ptr, output: weightsBuffer.contents(), count: copyCount) biasBuffer = makeBuffer(device: device, channelFormat: .float16, outputFeatureChannels: featureChannels, biasTerms: biasTerms) var params = KernelParams() let constants = MTLFunctionConstantValues() configureNeuronType(filter: neuronFilter, constants: constants, params: &params) var stride = [ UInt16(strideInPixelsX), UInt16(strideInPixelsY) ] constants.setConstantValue(&stride, type: .ushort2, withName: "stride") let functionName: String if featureChannels <= 4 { functionName = "depthwiseConv3x3" } else { functionName = "depthwiseConv3x3_array" } pipeline = makeFunction(device: device, name: functionName, constantValues: constants, useForgeLibrary: true) super.init(device: device, neuron: neuronFilter, params: params) } public override func encode(commandBuffer: MTLCommandBuffer, sourceImage: MPSImage, destinationImage: MPSImage) { // TODO: set the KernelParams based on clipRect, destinationFeatureChannelOffset, edgeMode params.inputOffsetX = Int16(offset.x); params.inputOffsetY = Int16(offset.y); params.inputOffsetZ = Int16(offset.z); if let encoder = commandBuffer.makeComputeCommandEncoder() { encoder.setComputePipelineState(pipeline) encoder.setTexture(sourceImage.texture, index: 0) encoder.setTexture(destinationImage.texture, index: 1) encoder.setBytes(&params, length: MemoryLayout<KernelParams>.size, index: 0) encoder.setBuffer(weightsBuffer, offset: 0, index: 1) encoder.setBuffer(biasBuffer, offset: 0, index: 2) encoder.dispatch(pipeline: pipeline, image: destinationImage) encoder.endEncoding() } if let image = sourceImage as? MPSTemporaryImage { image.readCount -= 1 } } }
mit
737fceaf3359e42916eb8369db723516
40.952
99
0.709573
4.707361
false
false
false
false
MainasuK/Bangumi-M
Percolator/Percolator/User.swift
1
5550
// // BangumiUser.swift // Percolator // // Created by Cirno MainasuK on 2015-5-15. // Copyright (c) 2015年 Cirno MainasuK. All rights reserved. // import Foundation import SwiftyJSON import KeychainAccess struct User { let id: Int let auth: String let authEncode: String fileprivate let url: String fileprivate let username: String let nickname: String let avatar: Avatar fileprivate let sign: String // Fail fast - make sure error handle correctly init(json: JSON) { auth = json[BangumiKey.auth].stringValue authEncode = json[BangumiKey.authEncode].stringValue let avatarDict = json[BangumiKey.avatar].dictionaryValue avatar = Avatar(avatarDict: avatarDict) id = json[BangumiKey.id].int! nickname = json[BangumiKey.nickname].stringValue sign = json[BangumiKey.sign].stringValue url = json[BangumiKey.url].stringValue username = json[BangumiKey.username].stringValue } init?() { consolePrint("Restroe user from UserDefaults…") guard User.isLogin() else { consolePrint("… failed") return nil } let standard = UserDefaults.standard id = standard.integer(forKey: UserDefaultsKey.userID) auth = standard.string(forKey: UserDefaultsKey.userAuth)! authEncode = standard.string(forKey: UserDefaultsKey.userAuthEncode)! url = standard.string(forKey: UserDefaultsKey.userURL)! username = standard.string(forKey: UserDefaultsKey.username)! nickname = standard.string(forKey: UserDefaultsKey.userNickname)! let large = standard.string(forKey: UserDefaultsKey.userLargeAvatar)! let medium = standard.string(forKey: UserDefaultsKey.userMediumAvatar)! let small = standard.string(forKey: UserDefaultsKey.userSmallAvatar)! avatar = Avatar(largeURL: large, mediumURL: medium, smallURL: small) sign = standard.string(forKey: UserDefaultsKey.userSign)! consolePrint("… successed") } } extension User { func saveInfo(with email: String, password: String) { consolePrint("Save user info to UserDeaults and KeychainWrapper") let keychain = Keychain(service: "https://api.bgm.tv") let standard = UserDefaults.standard standard.set(true, forKey: UserDefaultsKey.hasLoginKey) standard.set(id, forKey: UserDefaultsKey.userID) standard.set(auth, forKey: UserDefaultsKey.userAuth) standard.set(authEncode, forKey: UserDefaultsKey.userAuthEncode) standard.set(url, forKey: UserDefaultsKey.userURL) standard.set(username, forKey: UserDefaultsKey.username) standard.set(nickname, forKey: UserDefaultsKey.userNickname) standard.set(avatar.largeUrl, forKey: UserDefaultsKey.userLargeAvatar) standard.set(avatar.mediumUrl, forKey: UserDefaultsKey.userMediumAvatar) standard.set(avatar.smallUrl, forKey: UserDefaultsKey.userSmallAvatar) standard.set(sign, forKey: UserDefaultsKey.userSign) standard.set(email, forKey: UserDefaultsKey.userEmail) standard.synchronize() keychain["password"] = password } func updateAuth() { consolePrint("Update user auth…") let standard = UserDefaults.standard let keychain = Keychain(service: "https://api.bgm.tv") guard let email = standard.string(forKey: UserDefaultsKey.userEmail), let pass = keychain["password"] else { consolePrint("… can not get email or password") return } BangumiRequest.shared.userLogin(email, password: pass) { (user: Result<User>) in do { let user = try user.resolve() consolePrint("… fetch user auth success, save it") user.saveInfo(with: email, password: pass) BangumiRequest.shared.user = user } catch { consolePrint("… request occur error: \(error)") } } } } extension User { static func isLogin() -> Bool { return UserDefaults.standard.bool(forKey: UserDefaultsKey.hasLoginKey) } static func removeInfo() { consolePrint("Remove user info") let keychain = Keychain(service: "https://api.bgm.tv") let standard = UserDefaults.standard // Always Remove flag and value together to make sure restore could correctly standard.set(false, forKey: UserDefaultsKey.hasLoginKey) standard.set(nil, forKey: UserDefaultsKey.userID) standard.set(nil, forKey: UserDefaultsKey.userAuth) standard.set(nil, forKey: UserDefaultsKey.userAuthEncode) standard.set(nil, forKey: UserDefaultsKey.userURL) standard.set(nil, forKey: UserDefaultsKey.username) standard.set(nil, forKey: UserDefaultsKey.userNickname) standard.set(nil, forKey: UserDefaultsKey.userLargeAvatar) standard.set(nil, forKey: UserDefaultsKey.userMediumAvatar) standard.set(nil, forKey: UserDefaultsKey.userSmallAvatar) standard.set(nil, forKey: UserDefaultsKey.userSign) standard.set(nil, forKey: UserDefaultsKey.userEmail) standard.synchronize() keychain["password"] = nil } }
mit
cf6d4bc6e53fda94dd7a21d3c92e4d03
33.372671
88
0.64185
4.62709
false
false
false
false
jkolb/midnightbacon
Carthage/Checkouts/FranticApparatus/FranticApparatus/Promise.swift
1
13258
// Copyright (c) 2016 Justin Kolb - http://franticapparatus.net // // 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. public enum PromiseError : ErrorType { case CycleDetected case ContextUnavailable } private class PendingInfo<T> { var promiseToKeepAlive: AnyObject? var onFulfilled: [(T) -> Void] = [] var onRejected: [(ErrorType) -> Void] = [] private init() { self.promiseToKeepAlive = nil } private init<P>(waitForPromise: Promise<P>) { self.promiseToKeepAlive = waitForPromise } func waitForPromise<P>(promise: Promise<P>) { self.promiseToKeepAlive = promise } func fulfilled(value: T) { let handlers = onFulfilled dispatch_async(dispatch_get_main_queue()) { for handler in handlers { handler(value) } } } func rejected(reason: ErrorType) { let handlers = onRejected dispatch_async(dispatch_get_main_queue()) { for handler in handlers { handler(reason) } } } } private enum State<T> { case Pending(PendingInfo<T>) case Fulfilled(T) case Rejected(ErrorType) } public class Promise<T> { private var state: State<T> private let lock = NSLock() public init(@noescape _ resolver: (fulfill: (T) -> Void, reject: (ErrorType) -> Void, isCancelled: () -> Bool) -> Void) { state = .Pending(PendingInfo()) let weakFulfill: (T) -> Void = { [weak self] (value) -> Void in guard let strongSelf = self else { return } Promise<T>.resolve(strongSelf)(Promise<T>(value)) } let weakReject: (ErrorType) -> Void = { [weak self] (reason) -> Void in guard let strongSelf = self else { return } Promise<T>.resolve(strongSelf)(Promise<T>(error: reason)) } let isCancelled: () -> Bool = { [weak self] in return self == nil } resolver(fulfill: weakFulfill, reject: weakReject, isCancelled: isCancelled) } public init(_ value: T) { state = .Fulfilled(value) } public init(error: ErrorType) { state = .Rejected(error) } private init<P>(waitForPromise: Promise<P>) { state = .Pending(PendingInfo(waitForPromise: waitForPromise)) } private func synchronize(@noescape synchronized: () -> Void) { lock.lock() defer { lock.unlock() } synchronized() } private func resolve(promise: Promise<T>) { promise.synchronize { switch promise.state { case .Fulfilled(let value): fulfillWithValue(value) case .Rejected(let reason): rejectWithReason(reason) case .Pending(let info): waitForPromise(promise, promiseInfo: info) } } } private func fulfillWithValue(value: T) { synchronize { switch state { case .Pending(let info): state = .Fulfilled(value) info.fulfilled(value) default: fatalError("Duplicate attempt to resolve promise") } } } private func rejectWithReason(reason: ErrorType) { synchronize { switch state { case .Pending(let info): state = .Rejected(reason) info.rejected(reason) default: fatalError("Duplicate attempt to resolve promise") } } } private func waitForPromise(promise: Promise<T>, promiseInfo: PendingInfo<T>) { if promise === self { rejectWithReason(PromiseError.CycleDetected) return } synchronize { switch state { case .Pending(let info): promiseInfo.onFulfilled.append { [weak self] (value) -> Void in guard let strongSelf = self else { return } strongSelf.resolve(Promise<T>(value)) } promiseInfo.onRejected.append { [weak self] (reason) -> Void in guard let strongSelf = self else { return } strongSelf.resolve(Promise<T>(error: reason)) } info.waitForPromise(promise) default: fatalError("Attempting to wait on a promise after already being resolved") } } } public func then<R>(onFulfilled onFulfilled: (T) throws -> Promise<R>, onRejected: (ErrorType) throws -> Promise<R>) -> Promise<R> { let promise = Promise<R>(waitForPromise: self) let fulfiller: (T) -> Void = { [weak promise] (value) -> Void in guard let strongPromise = promise else { return } do { strongPromise.resolve(try onFulfilled(value)) } catch { strongPromise.resolve(Promise<R>(error: error)) } } let rejecter: (ErrorType) -> Void = { [weak promise] (reason) -> Void in guard let strongPromise = promise else { return } do { strongPromise.resolve(try onRejected(reason)) } catch { strongPromise.resolve(Promise<R>(error: error)) } } synchronize { switch state { case .Pending(let info): info.onFulfilled.append(fulfiller) info.onRejected.append(rejecter) case .Fulfilled(let value): dispatch_async(dispatch_get_main_queue()) { fulfiller(value) } case .Rejected(let reason): dispatch_async(dispatch_get_main_queue()) { rejecter(reason) } } } return promise } public func then<R>(onFulfilled onFulfilled: (T) throws -> R, onRejected: (ErrorType) throws -> R) -> Promise<R> { return then( onFulfilled: { (value) -> Promise<R> in return Promise<R>(try onFulfilled(value)) }, onRejected: { (reason) -> Promise<R> in return Promise<R>(try onRejected(reason)) } ) } public func then(onFulfilled: (T) throws -> Void) -> Promise<T> { return then( onFulfilled: { (value) -> T in try onFulfilled(value) return value }, onRejected: { (reason) -> T in throw reason } ) } public func thenWithContext<C: AnyObject>(context: C, _ onFulfilled: (C, T) throws -> Void) -> Promise<T> { return then( onFulfilled: { [weak context] (value) -> T in if let strongContext = context { try onFulfilled(strongContext, value) } return value }, onRejected: { (reason) -> T in throw reason } ) } public func then<R>(onFulfilled: (T) throws -> R) -> Promise<R> { return then( onFulfilled: onFulfilled, onRejected: { (reason) -> R in throw reason } ) } public func then<R>(onFulfilled: (T) throws -> Promise<R>) -> Promise<R> { return then( onFulfilled: onFulfilled, onRejected: { (reason) -> Promise<R> in throw reason } ) } public func thenWithContext<C: AnyObject, R>(context: C, _ onFulfilled: (C, T) throws -> R) -> Promise<R> { return then( onFulfilled: { [weak context] (value) -> R in if let strongContext = context { return try onFulfilled(strongContext, value) } else { throw PromiseError.ContextUnavailable } }, onRejected: { (reason) -> R in throw reason } ) } public func thenWithContext<C: AnyObject, R>(context: C, _ onFulfilled: (C, T) throws -> Promise<R>) -> Promise<R> { return then( onFulfilled: { [weak context] (value) -> Promise<R> in if let strongContext = context { return try onFulfilled(strongContext, value) } else { throw PromiseError.ContextUnavailable } }, onRejected: { (reason) -> Promise<R> in throw reason } ) } public func handle(onRejected: (ErrorType) throws -> Void) -> Promise<T> { return then( onFulfilled: { (value) -> T in return value }, onRejected: { (reason) -> T in try onRejected(reason) throw reason } ) } public func handleWithContext<C: AnyObject>(context: C, _ onRejected: (C, ErrorType) throws -> Void) -> Promise<T> { return then( onFulfilled: { (value) -> T in return value }, onRejected: { [weak context] (reason) -> T in if let strongContext = context { try onRejected(strongContext, reason) } throw reason } ) } public func recover(onRejected: (ErrorType) throws -> T) -> Promise<T> { return then( onFulfilled: { (value) -> T in return value }, onRejected: onRejected ) } public func recover(onRejected: (ErrorType) throws -> Promise<T>) -> Promise<T> { return then( onFulfilled: { (value) -> Promise<T> in return Promise<T>(value) }, onRejected: onRejected ) } public func recoverWithContext<C: AnyObject>(context: C, _ onRejected: (C, ErrorType) throws -> T) -> Promise<T> { return then( onFulfilled: { (value) -> T in return value }, onRejected: { [weak context] (reason) -> T in if let strongContext = context { return try onRejected(strongContext, reason) } else { throw PromiseError.ContextUnavailable } } ) } public func recoverWithContext<C: AnyObject>(context: C, _ onRejected: (C, ErrorType) throws -> Promise<T>) -> Promise<T> { return then( onFulfilled: { (value) -> Promise<T> in return Promise<T>(value) }, onRejected: { [weak context] (reason) -> Promise<T> in if let strongContext = context { return try onRejected(strongContext, reason) } else { throw PromiseError.ContextUnavailable } } ) } public func finally(onFinally: () -> Void) -> Promise<T> { return then( onFulfilled: { (value) -> T in onFinally() return value }, onRejected: { (reason) -> T in onFinally() throw reason } ) } public func finallyWithContext<C: AnyObject>(context: C, _ onFinally: (C) -> Void) -> Promise<T> { return then( onFulfilled: { [weak context] (value) -> T in if let strongContext = context { onFinally(strongContext) } return value }, onRejected: { [weak context] (reason) -> T in if let strongContext = context { onFinally(strongContext) } throw reason } ) } }
mit
fafed9094676f5e34b18621218259795
31.495098
136
0.51056
4.952559
false
false
false
false
NghiaTranUIT/Unofficial-Uber-macOS
UberGoCore/UberGoCore/ReceiptObj.swift
1
1354
// // ReceiptObj.swift // UberGoCore // // Created by Nghia Tran on 8/17/17. // Copyright © 2017 Nghia Tran. All rights reserved. // import Unbox public final class ReceiptObj: Unboxable { // MARK: - Variable public let requestID: String public let totalCharge: String public let totalOwed: Float? public let totalFare: String public let currencyCode: String public let chargeAdjustments: [String] public let duration: String public let distance: String public let distanceLabel: String // MARK: - Init public required init(unboxer: Unboxer) throws { requestID = try unboxer.unbox(key: Constants.Object.Receipt.RequestID) totalCharge = try unboxer.unbox(key: Constants.Object.Receipt.TotalCharged) totalOwed = unboxer.unbox(key: Constants.Object.Receipt.TotalOwed) totalFare = try unboxer.unbox(key: Constants.Object.Receipt.TotalFare) currencyCode = try unboxer.unbox(key: Constants.Object.Receipt.CurrencyCode) chargeAdjustments = try unboxer.unbox(key: Constants.Object.Receipt.ChargeAdjustments) duration = try unboxer.unbox(key: Constants.Object.Receipt.Duration) distance = try unboxer.unbox(key: Constants.Object.Receipt.Distance) distanceLabel = try unboxer.unbox(key: Constants.Object.Receipt.DistanceLabel) } }
mit
8c32d565cf7f5ff57c2ac1830ef8fb27
36.583333
94
0.719143
4.281646
false
false
false
false
twostraws/betterbeeb
BetterBeeb/ReaderContentViewController.swift
1
5258
// // ReaderContentViewController.swift // BetterBeeb // // Created by Hudzilla on 15/10/2014. // Copyright (c) 2014 Paul Hudson. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import MediaPlayer import UIKit class ReaderContentViewController: UIViewController, UIWebViewDelegate { var story: Story! var webView: UIWebView! override func loadView() { super.loadView() webView = UIWebView() webView.setTranslatesAutoresizingMaskIntoConstraints(false) view.addSubview(webView) webView.delegate = self webView.backgroundColor = UIColor.beebStoryBackground() let viewsDictionary = ["webView" : webView] view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[webView]|", options: .allZeros, metrics: nil, views: viewsDictionary)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[webView]|", options: .allZeros, metrics: nil, views: viewsDictionary)) } override func viewDidLoad() { super.viewDidLoad() var template = stringFromResource("template.html") var titleString = "<h1>\(story.title)</h1>" var formattedDate: String! = nil var timeSincePublished = NSDate().timeIntervalSinceDate(story.updated) if timeSincePublished < 60 * 60 * 9 { var roundedHours = Int(floor(timeSincePublished / (60 * 60))) if roundedHours == 0 { var roundedMinutes = Int(floor(timeSincePublished / 60)) if roundedMinutes == 0 { formattedDate = "moments ago" } else if roundedMinutes == 1 { formattedDate = "1 minute ago" } else { formattedDate = "\(roundedMinutes) minutes ago" } } else if roundedHours == 1 { formattedDate = "1 hour ago" } else { formattedDate = "\(roundedHours) hours ago" } } else { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "d MMM yyyy HH:mm" dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT") formattedDate = dateFormatter.stringFromDate(story.updated) + " GMT" } var lastUpdatedString = "Last updated \(formattedDate)" let dateComponents = NSCalendar.currentCalendar().components(.CalendarUnitYear, fromDate: NSDate()) var html = NSString(format: template, "", "iPhone", "", "", titleString, lastUpdatedString, story.content, "BBC &copy; \(dateComponents.year)") webView.loadHTMLString(html, baseURL: NSBundle.mainBundle().resourceURL) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) webView.scrollView.scrollsToTop = true } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // we must disable scrolls to top as we browse away from this page, otherwise there will be more than one // view will scrollsToTop enabled and thus iOS will do nothing. webView.scrollView.scrollsToTop = false } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if let urlString: NSString = request.URL.absoluteString { if urlString.hasPrefix("bbcvideo://") { let idx = urlString.rangeOfString("bbc.co.uk").location var url: NSString = "http://" + urlString.substringFromIndex(idx) url = url.stringByReplacingOccurrencesOfString("%7bdevice%7d", withString: "iphone") url = url.stringByReplacingOccurrencesOfString("%7bbandwidth%7d", withString: "wifi") var err: NSErrorPointer = nil let str: NSString! = NSString(contentsOfURL: NSURL(string: url), usedEncoding: nil, error: err) if err != nil || str == nil { let ac = UIAlertController(title: "Playback error", message: "There was a problem playing the movie; please check your connection and try again.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(ac, animated: true, completion: nil) return false } let vc = MPMoviePlayerViewController(contentURL: NSURL(string: str)) presentMoviePlayerViewControllerAnimated(vc) return false } } if navigationType == .LinkClicked { // any other types of links we want to open externally UIApplication.sharedApplication().openURL(request.URL) return false } return true } }
mit
0878152881ead520c47c91889bbfa99d
36.557143
175
0.732408
4.281759
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/NaturalLanguageUnderstandingV1/Models/CategoriesModel.swift
1
3121
/** * (C) Copyright IBM Corp. 2021. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import IBMSwiftSDKCore /** Categories model. */ public struct CategoriesModel: Codable, Equatable { /** When the status is `available`, the model is ready to use. */ public enum Status: String { case starting = "starting" case training = "training" case deploying = "deploying" case available = "available" case error = "error" case deleted = "deleted" } /** An optional name for the model. */ public var name: String? /** An optional map of metadata key-value pairs to store with this model. */ public var userMetadata: [String: JSON]? /** The 2-letter language code of this model. */ public var language: String /** An optional description of the model. */ public var description: String? /** An optional version string. */ public var modelVersion: String? /** ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. */ public var workspaceID: String? /** The description of the version. */ public var versionDescription: String? /** The service features that are supported by the custom model. */ public var features: [String]? /** When the status is `available`, the model is ready to use. */ public var status: String /** Unique model ID. */ public var modelID: String /** dateTime indicating when the model was created. */ public var created: Date public var notices: [Notice]? /** dateTime of last successful model training. */ public var lastTrained: Date? /** dateTime of last successful model deployment. */ public var lastDeployed: Date? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case name = "name" case userMetadata = "user_metadata" case language = "language" case description = "description" case modelVersion = "model_version" case workspaceID = "workspace_id" case versionDescription = "version_description" case features = "features" case status = "status" case modelID = "model_id" case created = "created" case notices = "notices" case lastTrained = "last_trained" case lastDeployed = "last_deployed" } }
apache-2.0
31076f3a2020468b09de5de55cba709f
24.581967
108
0.635053
4.596465
false
false
false
false
diesmal/thisorthat
Carthage/Checkouts/PieCharts/PieCharts/Layer/Impl/PlainText/PiePlainTextLayer.swift
1
2612
// // PiePlainTextLayer.swift // PieCharts // // Created by Ivan Schuetz on 30/12/2016. // Copyright © 2016 Ivan Schuetz. All rights reserved. // import UIKit open class PiePlainTextLayerSettings: PieCustomViewsLayerSettings { public var label: PieChartLabelSettings = PieChartLabelSettings() } open class PiePlainTextLayer: PieChartLayer { public weak var chart: PieChart? public var settings: PiePlainTextLayerSettings = PiePlainTextLayerSettings() public var onNotEnoughSpace: ((UILabel, CGSize) -> Void)? fileprivate var sliceViews = [PieSlice: UILabel]() public var animator: PieViewLayerAnimator = AlphaPieViewLayerAnimator() public init() {} public func onEndAnimation(slice: PieSlice) { addItems(slice: slice) } public func addItems(slice: PieSlice) { guard sliceViews[slice] == nil else {return} let label: UILabel = settings.label.labelGenerator?(slice) ?? { let label = UILabel() label.backgroundColor = settings.label.bgColor label.textColor = settings.label.textColor label.font = settings.label.font return label }() let text = settings.label.textGenerator(slice) let size = (text as NSString).size(attributes: [NSFontAttributeName: settings.label.font]) let center = settings.viewRadius.map{slice.view.midPoint(radius: $0)} ?? slice.view.arcCenter let availableSize = CGSize(width: slice.view.maxRectWidth(center: center, height: size.height), height: size.height) if !settings.hideOnOverflow || availableSize.contains(size) { label.text = text label.sizeToFit() } else { onNotEnoughSpace?(label, availableSize) } label.center = center chart?.addSubview(label) animator.animate(label) sliceViews[slice] = label } public func onSelected(slice: PieSlice, selected: Bool) { guard let label = sliceViews[slice] else {print("Invalid state: slice not in dictionary"); return} let p = slice.view.calculatePosition(angle: slice.view.midAngle, p: label.center, offset: selected ? slice.view.selectedOffset : -slice.view.selectedOffset) UIView.animate(withDuration: 0.15) { label.center = p } } public func clear() { for (_, view) in sliceViews { view.removeFromSuperview() } sliceViews.removeAll() } }
apache-2.0
6bd9b9127e3cb1a428c7f499cf0e90b6
30.841463
164
0.625431
4.704505
false
false
false
false
frootloops/swift
test/DebugInfo/return.swift
1
1118
// RUN: %target-swift-frontend %s -g -emit-ir -o - | %FileCheck %s class X { init (i : Int64) { x = i } var x : Int64 } // CHECK: define {{.*}}ifelseexpr public func ifelseexpr() -> Int64 { var x = X(i:0) // CHECK: [[ALLOCA:%.*]] = alloca %T6return1XC* // CHECK: [[META:%.*]] = call %swift.type* @_T06return1XCMa() // CHECK: [[X:%.*]] = call {{.*}}%T6return1XC* @_T06return1XCACs5Int64V1i_tcfC( // CHECK-SAME: i64 0, %swift.type* swiftself [[META]]) // CHECK: store %T6return1XC* [[X]], %T6return1XC** [[ALLOCA]] // CHECK: @swift_rt_swift_release to void (%T6return1XC*)*)(%T6return1XC* [[X]]) if true { x.x += 1 } else { x.x -= 1 } // CHECK: [[X:%.*]] = load %T6return1XC*, %T6return1XC** [[ALLOCA]] // CHECK: @swift_rt_swift_release to void (%T6return1XC*)*)(%T6return1XC* [[X]]) // CHECK-SAME: , !dbg ![[RELEASE:.*]] // The ret instruction should be in the same scope as the return expression. // CHECK: ret{{.*}}, !dbg ![[RELEASE]] return x.x // CHECK: ![[RELEASE]] = !DILocation(line: [[@LINE]], column: 3 }
apache-2.0
7af85df6786018ff24c752463e1886e3
36.266667
89
0.545617
2.973404
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/PersistentContext.swift
2
2357
// // PersistentContext.swift // Neocom // // Created by Artem Shimanski on 09.08.2018. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import CoreData import Futures public protocol PersistentContext { var managedObjectContext: NSManagedObjectContext {get} // func existingObject<T: NSManagedObject>(with objectID: NSManagedObjectID) throws -> T? // func save() throws -> Void // func performAndWait<T>(_ block: () throws -> T) throws -> T // func performAndWait<T>(_ block: () -> T) -> T // @discardableResult func perform<T>(_ block: @escaping () throws -> T) -> Future<T> init(managedObjectContext: NSManagedObjectContext) } extension PersistentContext { func existingObject<T: NSManagedObject>(with objectID: NSManagedObjectID) throws -> T { let value = (try managedObjectContext.existingObject(with: objectID)) guard let result = value as? T else { throw NCError.castError(from: type(of: value), to: T.self) } return result } func save() throws -> Void { if managedObjectContext.hasChanges { try managedObjectContext.save() } } func performAndWait<T>(_ block: () throws -> T) throws -> T { var result: T? var err: Error? managedObjectContext.performAndWait { do { result = try block() } catch { err = error } } if let error = err { throw error } return result! } func performAndWait<T>(_ block: () -> T) -> T { var result: T? managedObjectContext.performAndWait { result = block() } return result! } @discardableResult func perform<T>(_ block: @escaping () throws -> T) -> Future<T> { let promise = Promise<T>() managedObjectContext.perform { do { let result = try block() try self.save() try promise.fulfill(result) } catch { try? promise.fail(error) } } return promise.future } @discardableResult func perform<T>(_ block: @escaping () throws -> Future<T>) -> Future<T> { let promise = Promise<T>() managedObjectContext.perform { do { try block().then { result in self.managedObjectContext.perform { do { try self.save() try promise.fulfill(result) } catch { try? promise.fail(error) } } }.catch { try? promise.fail($0) } } catch { try? promise.fail(error) } } return promise.future } }
lgpl-2.1
c6d50a89cb0c263ddc8e4d207919eb09
21.653846
100
0.64601
3.516418
false
false
false
false
prcela/NKNetworkKit
Pod/Classes/NKProcessorInfo.swift
1
2261
// // NKInfo.swift // NetworkKit // // Created by Kresimir Prcela on 15/07/15. // Copyright (c) 2015 prcela. All rights reserved. // import Reachability public let NKNotificationRequestError = "NotificationRequestError" /* Class that holds info about all actual downloading requests and errors that appeared during single application run. Singleton instance of this class is using network reachability closures in order to automatically continue stopped downloads. */ public class NKProcessorInfo: NSObject { public static var shared = NKProcessorInfo() public var errors:[NKRequestError] = [] public var downloads:[NKFileDownloadInfo] = [] override init() { super.init() let reach = Reachability.reachabilityForInternetConnection() reach.reachableBlock = {(reach) in // continue suspended downloads with resume data for fdi in self.downloads { if (fdi.task.state == .Suspended || fdi.task.state == .Completed) { let session = NSURLSession(configuration: NKProcessor.defaultConfiguration, delegate: fdi, delegateQueue: nil) NSLog("Resuming download: \(fdi.url)") if fdi.resumeData != nil { fdi.task = session.downloadTaskWithResumeData(fdi.resumeData!) } else { fdi.task = session.downloadTaskWithURL(fdi.url) } fdi.task.resume() } } } reach.startNotifier() } public func infoForUrl(url:NSURL) -> NKFileDownloadInfo? { for fdi in downloads { if fdi.url.absoluteString == url.absoluteString { return fdi } } return nil } func infoForTask(task: NSURLSessionDownloadTask) -> (Int,NKFileDownloadInfo)? { for (idx,fdi) in enumerate(downloads) { if fdi.task == task { return (idx,fdi) } } return nil } }
mit
6d8bdf8d7883c20ed765158c223a6368
26.573171
125
0.541353
5.046875
false
false
false
false
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/AssistantV1/Assistant.swift
1
128189
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** The IBM Watson Assistant service combines machine learning, natural language understanding, and integrated dialog tools to create conversation flows between your apps and your users. */ public class Assistant { /// The base URL to use when contacting the service. public var serviceURL = "https://gateway.watsonplatform.net/assistant/api" /// The default HTTP headers for all requests to the service. public var defaultHeaders = [String: String]() private let credentials: Credentials private let domain = "com.ibm.watson.developer-cloud.AssistantV1" private let version: String /** Create a `Assistant` object. - parameter username: The username used to authenticate with the service. - parameter password: The password used to authenticate with the service. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. */ public init(username: String, password: String, version: String) { self.credentials = .basicAuthentication(username: username, password: password) self.version = version } /** If the response or data represents an error returned by the Watson Assistant service, then return NSError with information about the error that occured. Otherwise, return nil. - parameter response: the URL response returned from the service. - parameter data: Raw data returned from the service that may represent an error. */ private func responseToError(response: HTTPURLResponse?, data: Data?) -> NSError? { // First check http status code in response if let response = response { if (200..<300).contains(response.statusCode) { return nil } } // ensure data is not nil guard let data = data else { if let code = response?.statusCode { return NSError(domain: domain, code: code, userInfo: nil) } return nil // RestKit will generate error for this case } let code = response?.statusCode ?? 400 do { let json = try JSONWrapper(data: data) let message = try json.getString(at: "error") let userInfo = [NSLocalizedDescriptionKey: message] return NSError(domain: domain, code: code, userInfo: userInfo) } catch { return NSError(domain: domain, code: code, userInfo: nil) } } /** Get response to user input. Get a response to a user's input. There is no rate limit for this operation. - parameter workspaceID: Unique identifier of the workspace. - parameter request: The message to be sent. This includes the user's input, along with optional intents, entities, and context from the last response. - parameter nodesVisitedDetails: Whether to include additional diagnostic information about the dialog nodes that were visited during processing of the message. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func message( workspaceID: String, request: MessageRequest? = nil, nodesVisitedDetails: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (MessageResponse) -> Void) { // construct body guard let body = try? JSONEncoder().encodeIfPresent(request) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let nodesVisitedDetails = nodesVisitedDetails { let queryParameter = URLQueryItem(name: "nodes_visited_details", value: "\(nodesVisitedDetails)") queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)/message" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<MessageResponse>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** List workspaces. List the workspaces associated with a Watson Assistant service instance. This operation is limited to 500 requests per 30 minutes. For more information, see **Rate limiting**. - parameter pageLimit: The number of records to return in each page of results. - parameter includeCount: Whether to include information about the number of records returned. - parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). Supported values are `name`, `updated`, and `workspace_id`. - parameter cursor: A token identifying the page of results to retrieve. - parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func listWorkspaces( pageLimit: Int? = nil, includeCount: Bool? = nil, sort: String? = nil, cursor: String? = nil, includeAudit: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (WorkspaceCollection) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let pageLimit = pageLimit { let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)") queryParameters.append(queryParameter) } if let includeCount = includeCount { let queryParameter = URLQueryItem(name: "include_count", value: "\(includeCount)") queryParameters.append(queryParameter) } if let sort = sort { let queryParameter = URLQueryItem(name: "sort", value: sort) queryParameters.append(queryParameter) } if let cursor = cursor { let queryParameter = URLQueryItem(name: "cursor", value: cursor) queryParameters.append(queryParameter) } if let includeAudit = includeAudit { let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)") queryParameters.append(queryParameter) } // construct REST request let request = RestRequest( method: "GET", url: serviceURL + "/v1/workspaces", credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<WorkspaceCollection>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Create workspace. Create a workspace based on component objects. You must provide workspace components defining the content of the new workspace. This operation is limited to 30 requests per 30 minutes. For more information, see **Rate limiting**. - parameter properties: The content of the new workspace. The maximum size for this data is 50MB. If you need to import a larger workspace, consider importing the workspace without intents and entities and then adding them separately. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func createWorkspace( properties: CreateWorkspace? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Workspace) -> Void) { // construct body guard let body = try? JSONEncoder().encodeIfPresent(properties) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let request = RestRequest( method: "POST", url: serviceURL + "/v1/workspaces", credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Workspace>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Get information about a workspace. Get information about a workspace, optionally including all workspace content. With **export**=`false`, this operation is limited to 6000 requests per 5 minutes. With **export**=`true`, the limit is 20 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only information about the element itself. If **export**=`true`, all content, including subelements, is included. - parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func getWorkspace( workspaceID: String, export: Bool? = nil, includeAudit: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (WorkspaceExport) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let export = export { let queryParameter = URLQueryItem(name: "export", value: "\(export)") queryParameters.append(queryParameter) } if let includeAudit = includeAudit { let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)") queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<WorkspaceExport>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Update workspace. Update an existing workspace with new or modified data. You must provide component objects defining the content of the updated workspace. This operation is limited to 30 request per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter properties: Valid data defining the new and updated workspace content. The maximum size for this data is 50MB. If you need to import a larger amount of workspace data, consider importing components such as intents and entities using separate operations. - parameter append: Whether the new data is to be appended to the existing data in the workspace. If **append**=`false`, elements included in the new data completely replace the corresponding existing elements, including all subelements. For example, if the new data includes **entities** and **append**=`false`, all existing entities in the workspace are discarded and replaced with the new entities. If **append**=`true`, existing elements are preserved, and the new elements are added. If any elements in the new data collide with existing elements, the update request fails. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func updateWorkspace( workspaceID: String, properties: UpdateWorkspace? = nil, append: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Workspace) -> Void) { // construct body guard let body = try? JSONEncoder().encodeIfPresent(properties) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let append = append { let queryParameter = URLQueryItem(name: "append", value: "\(append)") queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Workspace>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Delete workspace. Delete a workspace from the service instance. This operation is limited to 30 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func deleteWorkspace( workspaceID: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping () -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "DELETE", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseVoid(responseToError: responseToError) { (response: RestResponse) in switch response.result { case .success: success() case .failure(let error): failure?(error) } } } /** List intents. List the intents for a workspace. With **export**=`false`, this operation is limited to 2000 requests per 30 minutes. With **export**=`true`, the limit is 400 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only information about the element itself. If **export**=`true`, all content, including subelements, is included. - parameter pageLimit: The number of records to return in each page of results. - parameter includeCount: Whether to include information about the number of records returned. - parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). Supported values are `name`, `updated`, and `workspace_id`. - parameter cursor: A token identifying the page of results to retrieve. - parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func listIntents( workspaceID: String, export: Bool? = nil, pageLimit: Int? = nil, includeCount: Bool? = nil, sort: String? = nil, cursor: String? = nil, includeAudit: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (IntentCollection) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let export = export { let queryParameter = URLQueryItem(name: "export", value: "\(export)") queryParameters.append(queryParameter) } if let pageLimit = pageLimit { let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)") queryParameters.append(queryParameter) } if let includeCount = includeCount { let queryParameter = URLQueryItem(name: "include_count", value: "\(includeCount)") queryParameters.append(queryParameter) } if let sort = sort { let queryParameter = URLQueryItem(name: "sort", value: sort) queryParameters.append(queryParameter) } if let cursor = cursor { let queryParameter = URLQueryItem(name: "cursor", value: cursor) queryParameters.append(queryParameter) } if let includeAudit = includeAudit { let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)") queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)/intents" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<IntentCollection>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Create intent. Create a new intent. This operation is limited to 2000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter intent: The name of the intent. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - It must be no longer than 128 characters. - parameter description: The description of the intent. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. - parameter examples: An array of user input examples for the intent. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func createIntent( workspaceID: String, intent: String, description: String? = nil, examples: [CreateExample]? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Intent) -> Void) { // construct body let createIntentRequest = CreateIntent(intent: intent, description: description, examples: examples) guard let body = try? JSONEncoder().encode(createIntentRequest) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/intents" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Intent>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Get intent. Get information about an intent, optionally including all intent content. With **export**=`false`, this operation is limited to 6000 requests per 5 minutes. With **export**=`true`, the limit is 400 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter intent: The intent name. - parameter export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only information about the element itself. If **export**=`true`, all content, including subelements, is included. - parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func getIntent( workspaceID: String, intent: String, export: Bool? = nil, includeAudit: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (IntentExport) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let export = export { let queryParameter = URLQueryItem(name: "export", value: "\(export)") queryParameters.append(queryParameter) } if let includeAudit = includeAudit { let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)") queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)/intents/\(intent)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<IntentExport>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Update intent. Update an existing intent with new or modified data. You must provide component objects defining the content of the updated intent. This operation is limited to 2000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter intent: The intent name. - parameter newIntent: The name of the intent. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - It must be no longer than 128 characters. - parameter newDescription: The description of the intent. - parameter newExamples: An array of user input examples for the intent. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func updateIntent( workspaceID: String, intent: String, newIntent: String? = nil, newDescription: String? = nil, newExamples: [CreateExample]? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Intent) -> Void) { // construct body let updateIntentRequest = UpdateIntent(intent: newIntent, description: newDescription, examples: newExamples) guard let body = try? JSONEncoder().encode(updateIntentRequest) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/intents/\(intent)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Intent>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Delete intent. Delete an intent from a workspace. This operation is limited to 2000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter intent: The intent name. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func deleteIntent( workspaceID: String, intent: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping () -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/intents/\(intent)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "DELETE", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseVoid(responseToError: responseToError) { (response: RestResponse) in switch response.result { case .success: success() case .failure(let error): failure?(error) } } } /** List user input examples. List the user input examples for an intent. This operation is limited to 2500 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter intent: The intent name. - parameter pageLimit: The number of records to return in each page of results. - parameter includeCount: Whether to include information about the number of records returned. - parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). Supported values are `name`, `updated`, and `workspace_id`. - parameter cursor: A token identifying the page of results to retrieve. - parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func listExamples( workspaceID: String, intent: String, pageLimit: Int? = nil, includeCount: Bool? = nil, sort: String? = nil, cursor: String? = nil, includeAudit: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (ExampleCollection) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let pageLimit = pageLimit { let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)") queryParameters.append(queryParameter) } if let includeCount = includeCount { let queryParameter = URLQueryItem(name: "include_count", value: "\(includeCount)") queryParameters.append(queryParameter) } if let sort = sort { let queryParameter = URLQueryItem(name: "sort", value: sort) queryParameters.append(queryParameter) } if let cursor = cursor { let queryParameter = URLQueryItem(name: "cursor", value: cursor) queryParameters.append(queryParameter) } if let includeAudit = includeAudit { let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)") queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)/intents/\(intent)/examples" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<ExampleCollection>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Create user input example. Add a new user input example to an intent. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter intent: The intent name. - parameter text: The text of a user input example. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 1024 characters. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func createExample( workspaceID: String, intent: String, text: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Example) -> Void) { // construct body let createExampleRequest = CreateExample(text: text) guard let body = try? JSONEncoder().encode(createExampleRequest) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/intents/\(intent)/examples" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Example>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Get user input example. Get information about a user input example. This operation is limited to 6000 requests per 5 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter intent: The intent name. - parameter text: The text of the user input example. - parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func getExample( workspaceID: String, intent: String, text: String, includeAudit: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Example) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let includeAudit = includeAudit { let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)") queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)/intents/\(intent)/examples/\(text)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Example>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Update user input example. Update the text of a user input example. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter intent: The intent name. - parameter text: The text of the user input example. - parameter newText: The text of the user input example. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 1024 characters. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func updateExample( workspaceID: String, intent: String, text: String, newText: String? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Example) -> Void) { // construct body let updateExampleRequest = UpdateExample(text: newText) guard let body = try? JSONEncoder().encode(updateExampleRequest) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/intents/\(intent)/examples/\(text)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Example>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Delete user input example. Delete a user input example from an intent. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter intent: The intent name. - parameter text: The text of the user input example. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func deleteExample( workspaceID: String, intent: String, text: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping () -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/intents/\(intent)/examples/\(text)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "DELETE", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseVoid(responseToError: responseToError) { (response: RestResponse) in switch response.result { case .success: success() case .failure(let error): failure?(error) } } } /** List counterexamples. List the counterexamples for a workspace. Counterexamples are examples that have been marked as irrelevant input. This operation is limited to 2500 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter pageLimit: The number of records to return in each page of results. - parameter includeCount: Whether to include information about the number of records returned. - parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). Supported values are `name`, `updated`, and `workspace_id`. - parameter cursor: A token identifying the page of results to retrieve. - parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func listCounterexamples( workspaceID: String, pageLimit: Int? = nil, includeCount: Bool? = nil, sort: String? = nil, cursor: String? = nil, includeAudit: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (CounterexampleCollection) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let pageLimit = pageLimit { let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)") queryParameters.append(queryParameter) } if let includeCount = includeCount { let queryParameter = URLQueryItem(name: "include_count", value: "\(includeCount)") queryParameters.append(queryParameter) } if let sort = sort { let queryParameter = URLQueryItem(name: "sort", value: sort) queryParameters.append(queryParameter) } if let cursor = cursor { let queryParameter = URLQueryItem(name: "cursor", value: cursor) queryParameters.append(queryParameter) } if let includeAudit = includeAudit { let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)") queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)/counterexamples" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<CounterexampleCollection>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Create counterexample. Add a new counterexample to a workspace. Counterexamples are examples that have been marked as irrelevant input. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter text: The text of a user input marked as irrelevant input. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters - It cannot consist of only whitespace characters - It must be no longer than 1024 characters. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func createCounterexample( workspaceID: String, text: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Counterexample) -> Void) { // construct body let createCounterexampleRequest = CreateCounterexample(text: text) guard let body = try? JSONEncoder().encode(createCounterexampleRequest) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/counterexamples" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Counterexample>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Get counterexample. Get information about a counterexample. Counterexamples are examples that have been marked as irrelevant input. This operation is limited to 6000 requests per 5 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter text: The text of a user input counterexample (for example, `What are you wearing?`). - parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func getCounterexample( workspaceID: String, text: String, includeAudit: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Counterexample) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let includeAudit = includeAudit { let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)") queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)/counterexamples/\(text)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Counterexample>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Update counterexample. Update the text of a counterexample. Counterexamples are examples that have been marked as irrelevant input. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter text: The text of a user input counterexample (for example, `What are you wearing?`). - parameter newText: The text of a user input counterexample. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func updateCounterexample( workspaceID: String, text: String, newText: String? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Counterexample) -> Void) { // construct body let updateCounterexampleRequest = UpdateCounterexample(text: newText) guard let body = try? JSONEncoder().encode(updateCounterexampleRequest) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/counterexamples/\(text)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Counterexample>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Delete counterexample. Delete a counterexample from a workspace. Counterexamples are examples that have been marked as irrelevant input. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter text: The text of a user input counterexample (for example, `What are you wearing?`). - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func deleteCounterexample( workspaceID: String, text: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping () -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/counterexamples/\(text)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "DELETE", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseVoid(responseToError: responseToError) { (response: RestResponse) in switch response.result { case .success: success() case .failure(let error): failure?(error) } } } /** List entities. List the entities for a workspace. With **export**=`false`, this operation is limited to 1000 requests per 30 minutes. With **export**=`true`, the limit is 200 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only information about the element itself. If **export**=`true`, all content, including subelements, is included. - parameter pageLimit: The number of records to return in each page of results. - parameter includeCount: Whether to include information about the number of records returned. - parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). Supported values are `name`, `updated`, and `workspace_id`. - parameter cursor: A token identifying the page of results to retrieve. - parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func listEntities( workspaceID: String, export: Bool? = nil, pageLimit: Int? = nil, includeCount: Bool? = nil, sort: String? = nil, cursor: String? = nil, includeAudit: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (EntityCollection) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let export = export { let queryParameter = URLQueryItem(name: "export", value: "\(export)") queryParameters.append(queryParameter) } if let pageLimit = pageLimit { let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)") queryParameters.append(queryParameter) } if let includeCount = includeCount { let queryParameter = URLQueryItem(name: "include_count", value: "\(includeCount)") queryParameters.append(queryParameter) } if let sort = sort { let queryParameter = URLQueryItem(name: "sort", value: sort) queryParameters.append(queryParameter) } if let cursor = cursor { let queryParameter = URLQueryItem(name: "cursor", value: cursor) queryParameters.append(queryParameter) } if let includeAudit = includeAudit { let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)") queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)/entities" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<EntityCollection>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Create entity. Create a new entity. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter properties: The content of the new entity. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func createEntity( workspaceID: String, properties: CreateEntity, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Entity) -> Void) { // construct body guard let body = try? JSONEncoder().encode(properties) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/entities" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Entity>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Get entity. Get information about an entity, optionally including all entity content. With **export**=`false`, this operation is limited to 6000 requests per 5 minutes. With **export**=`true`, the limit is 200 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter entity: The name of the entity. - parameter export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only information about the element itself. If **export**=`true`, all content, including subelements, is included. - parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func getEntity( workspaceID: String, entity: String, export: Bool? = nil, includeAudit: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (EntityExport) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let export = export { let queryParameter = URLQueryItem(name: "export", value: "\(export)") queryParameters.append(queryParameter) } if let includeAudit = includeAudit { let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)") queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<EntityExport>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Update entity. Update an existing entity with new or modified data. You must provide component objects defining the content of the updated entity. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter entity: The name of the entity. - parameter properties: The updated content of the entity. Any elements included in the new data will completely replace the equivalent existing elements, including all subelements. (Previously existing subelements are not retained unless they are also included in the new data.) For example, if you update the values for an entity, the previously existing values are discarded and replaced with the new values specified in the update. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func updateEntity( workspaceID: String, entity: String, properties: UpdateEntity, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Entity) -> Void) { // construct body guard let body = try? JSONEncoder().encode(properties) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Entity>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Delete entity. Delete an entity from a workspace. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter entity: The name of the entity. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func deleteEntity( workspaceID: String, entity: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping () -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "DELETE", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseVoid(responseToError: responseToError) { (response: RestResponse) in switch response.result { case .success: success() case .failure(let error): failure?(error) } } } /** List entity values. List the values for an entity. This operation is limited to 2500 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter entity: The name of the entity. - parameter export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only information about the element itself. If **export**=`true`, all content, including subelements, is included. - parameter pageLimit: The number of records to return in each page of results. - parameter includeCount: Whether to include information about the number of records returned. - parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). Supported values are `name`, `updated`, and `workspace_id`. - parameter cursor: A token identifying the page of results to retrieve. - parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func listValues( workspaceID: String, entity: String, export: Bool? = nil, pageLimit: Int? = nil, includeCount: Bool? = nil, sort: String? = nil, cursor: String? = nil, includeAudit: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (ValueCollection) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let export = export { let queryParameter = URLQueryItem(name: "export", value: "\(export)") queryParameters.append(queryParameter) } if let pageLimit = pageLimit { let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)") queryParameters.append(queryParameter) } if let includeCount = includeCount { let queryParameter = URLQueryItem(name: "include_count", value: "\(includeCount)") queryParameters.append(queryParameter) } if let sort = sort { let queryParameter = URLQueryItem(name: "sort", value: sort) queryParameters.append(queryParameter) } if let cursor = cursor { let queryParameter = URLQueryItem(name: "cursor", value: cursor) queryParameters.append(queryParameter) } if let includeAudit = includeAudit { let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)") queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<ValueCollection>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Add entity value. Create a new value for an entity. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter entity: The name of the entity. - parameter properties: The new entity value. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func createValue( workspaceID: String, entity: String, properties: CreateValue, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Value) -> Void) { // construct body guard let body = try? JSONEncoder().encode(properties) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Value>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Get entity value. Get information about an entity value. This operation is limited to 6000 requests per 5 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter entity: The name of the entity. - parameter value: The text of the entity value. - parameter export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only information about the element itself. If **export**=`true`, all content, including subelements, is included. - parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func getValue( workspaceID: String, entity: String, value: String, export: Bool? = nil, includeAudit: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (ValueExport) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let export = export { let queryParameter = URLQueryItem(name: "export", value: "\(export)") queryParameters.append(queryParameter) } if let includeAudit = includeAudit { let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)") queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values/\(value)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<ValueExport>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Update entity value. Update an existing entity value with new or modified data. You must provide component objects defining the content of the updated entity value. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter entity: The name of the entity. - parameter value: The text of the entity value. - parameter properties: The updated content of the entity value. Any elements included in the new data will completely replace the equivalent existing elements, including all subelements. (Previously existing subelements are not retained unless they are also included in the new data.) For example, if you update the synonyms for an entity value, the previously existing synonyms are discarded and replaced with the new synonyms specified in the update. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func updateValue( workspaceID: String, entity: String, value: String, properties: UpdateValue, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Value) -> Void) { // construct body guard let body = try? JSONEncoder().encode(properties) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values/\(value)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Value>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Delete entity value. Delete a value from an entity. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter entity: The name of the entity. - parameter value: The text of the entity value. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func deleteValue( workspaceID: String, entity: String, value: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping () -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values/\(value)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "DELETE", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseVoid(responseToError: responseToError) { (response: RestResponse) in switch response.result { case .success: success() case .failure(let error): failure?(error) } } } /** List entity value synonyms. List the synonyms for an entity value. This operation is limited to 2500 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter entity: The name of the entity. - parameter value: The text of the entity value. - parameter pageLimit: The number of records to return in each page of results. - parameter includeCount: Whether to include information about the number of records returned. - parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). Supported values are `name`, `updated`, and `workspace_id`. - parameter cursor: A token identifying the page of results to retrieve. - parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func listSynonyms( workspaceID: String, entity: String, value: String, pageLimit: Int? = nil, includeCount: Bool? = nil, sort: String? = nil, cursor: String? = nil, includeAudit: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (SynonymCollection) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let pageLimit = pageLimit { let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)") queryParameters.append(queryParameter) } if let includeCount = includeCount { let queryParameter = URLQueryItem(name: "include_count", value: "\(includeCount)") queryParameters.append(queryParameter) } if let sort = sort { let queryParameter = URLQueryItem(name: "sort", value: sort) queryParameters.append(queryParameter) } if let cursor = cursor { let queryParameter = URLQueryItem(name: "cursor", value: cursor) queryParameters.append(queryParameter) } if let includeAudit = includeAudit { let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)") queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values/\(value)/synonyms" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<SynonymCollection>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Add entity value synonym. Add a new synonym to an entity value. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter entity: The name of the entity. - parameter value: The text of the entity value. - parameter synonym: The text of the synonym. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func createSynonym( workspaceID: String, entity: String, value: String, synonym: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Synonym) -> Void) { // construct body let createSynonymRequest = CreateSynonym(synonym: synonym) guard let body = try? JSONEncoder().encode(createSynonymRequest) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values/\(value)/synonyms" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Synonym>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Get entity value synonym. Get information about a synonym of an entity value. This operation is limited to 6000 requests per 5 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter entity: The name of the entity. - parameter value: The text of the entity value. - parameter synonym: The text of the synonym. - parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func getSynonym( workspaceID: String, entity: String, value: String, synonym: String, includeAudit: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Synonym) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let includeAudit = includeAudit { let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)") queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values/\(value)/synonyms/\(synonym)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Synonym>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Update entity value synonym. Update an existing entity value synonym with new text. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter entity: The name of the entity. - parameter value: The text of the entity value. - parameter synonym: The text of the synonym. - parameter newSynonym: The text of the synonym. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func updateSynonym( workspaceID: String, entity: String, value: String, synonym: String, newSynonym: String? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Synonym) -> Void) { // construct body let updateSynonymRequest = UpdateSynonym(synonym: newSynonym) guard let body = try? JSONEncoder().encode(updateSynonymRequest) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values/\(value)/synonyms/\(synonym)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Synonym>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Delete entity value synonym. Delete a synonym from an entity value. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter entity: The name of the entity. - parameter value: The text of the entity value. - parameter synonym: The text of the synonym. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func deleteSynonym( workspaceID: String, entity: String, value: String, synonym: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping () -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values/\(value)/synonyms/\(synonym)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "DELETE", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseVoid(responseToError: responseToError) { (response: RestResponse) in switch response.result { case .success: success() case .failure(let error): failure?(error) } } } /** List dialog nodes. List the dialog nodes for a workspace. This operation is limited to 2500 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter pageLimit: The number of records to return in each page of results. - parameter includeCount: Whether to include information about the number of records returned. - parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). Supported values are `name`, `updated`, and `workspace_id`. - parameter cursor: A token identifying the page of results to retrieve. - parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func listDialogNodes( workspaceID: String, pageLimit: Int? = nil, includeCount: Bool? = nil, sort: String? = nil, cursor: String? = nil, includeAudit: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (DialogNodeCollection) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let pageLimit = pageLimit { let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)") queryParameters.append(queryParameter) } if let includeCount = includeCount { let queryParameter = URLQueryItem(name: "include_count", value: "\(includeCount)") queryParameters.append(queryParameter) } if let sort = sort { let queryParameter = URLQueryItem(name: "sort", value: sort) queryParameters.append(queryParameter) } if let cursor = cursor { let queryParameter = URLQueryItem(name: "cursor", value: cursor) queryParameters.append(queryParameter) } if let includeAudit = includeAudit { let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)") queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)/dialog_nodes" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<DialogNodeCollection>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Create dialog node. Create a new dialog node. This operation is limited to 500 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter properties: A CreateDialogNode object defining the content of the new dialog node. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func createDialogNode( workspaceID: String, properties: CreateDialogNode, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (DialogNode) -> Void) { // construct body guard let body = try? JSONEncoder().encode(properties) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/dialog_nodes" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<DialogNode>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Get dialog node. Get information about a dialog node. This operation is limited to 6000 requests per 5 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter dialogNode: The dialog node ID (for example, `get_order`). - parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func getDialogNode( workspaceID: String, dialogNode: String, includeAudit: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (DialogNode) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let includeAudit = includeAudit { let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)") queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)/dialog_nodes/\(dialogNode)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<DialogNode>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Update dialog node. Update an existing dialog node with new or modified data. This operation is limited to 500 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter dialogNode: The dialog node ID (for example, `get_order`). - parameter properties: The updated content of the dialog node. Any elements included in the new data will completely replace the equivalent existing elements, including all subelements. (Previously existing subelements are not retained unless they are also included in the new data.) For example, if you update the actions for a dialog node, the previously existing actions are discarded and replaced with the new actions specified in the update. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func updateDialogNode( workspaceID: String, dialogNode: String, properties: UpdateDialogNode, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (DialogNode) -> Void) { // construct body guard let body = try? JSONEncoder().encode(properties) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/dialog_nodes/\(dialogNode)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<DialogNode>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Delete dialog node. Delete a dialog node from a workspace. This operation is limited to 500 requests per 30 minutes. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter dialogNode: The dialog node ID (for example, `get_order`). - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func deleteDialogNode( workspaceID: String, dialogNode: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping () -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v1/workspaces/\(workspaceID)/dialog_nodes/\(dialogNode)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "DELETE", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseVoid(responseToError: responseToError) { (response: RestResponse) in switch response.result { case .success: success() case .failure(let error): failure?(error) } } } /** List log events in a workspace. List the events from the log of a specific workspace. If **cursor** is not specified, this operation is limited to 40 requests per 30 minutes. If **cursor** is specified, the limit is 120 requests per minute. For more information, see **Rate limiting**. - parameter workspaceID: Unique identifier of the workspace. - parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). Supported values are `name`, `updated`, and `workspace_id`. - parameter filter: A cacheable parameter that limits the results to those matching the specified filter. For more information, see the [documentation](https://console.bluemix.net/docs/services/conversation/filter-reference.html#filter-query-syntax). - parameter pageLimit: The number of records to return in each page of results. - parameter cursor: A token identifying the page of results to retrieve. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func listLogs( workspaceID: String, sort: String? = nil, filter: String? = nil, pageLimit: Int? = nil, cursor: String? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (LogCollection) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let sort = sort { let queryParameter = URLQueryItem(name: "sort", value: sort) queryParameters.append(queryParameter) } if let filter = filter { let queryParameter = URLQueryItem(name: "filter", value: filter) queryParameters.append(queryParameter) } if let pageLimit = pageLimit { let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)") queryParameters.append(queryParameter) } if let cursor = cursor { let queryParameter = URLQueryItem(name: "cursor", value: cursor) queryParameters.append(queryParameter) } // construct REST request let path = "/v1/workspaces/\(workspaceID)/logs" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<LogCollection>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** List log events in all workspaces. List the events from the logs of all workspaces in the service instance. If **cursor** is not specified, this operation is limited to 40 requests per 30 minutes. If **cursor** is specified, the limit is 120 requests per minute. For more information, see **Rate limiting**. - parameter filter: A cacheable parameter that limits the results to those matching the specified filter. You must specify a filter query that includes a value for `language`, as well as a value for `workspace_id` or `request.context.metadata.deployment`. For more information, see the [documentation](https://console.bluemix.net/docs/services/conversation/filter-reference.html#filter-query-syntax). - parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). Supported values are `name`, `updated`, and `workspace_id`. - parameter pageLimit: The number of records to return in each page of results. - parameter cursor: A token identifying the page of results to retrieve. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func listAllLogs( filter: String, sort: String? = nil, pageLimit: Int? = nil, cursor: String? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (LogCollection) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) queryParameters.append(URLQueryItem(name: "filter", value: filter)) if let sort = sort { let queryParameter = URLQueryItem(name: "sort", value: sort) queryParameters.append(queryParameter) } if let pageLimit = pageLimit { let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)") queryParameters.append(queryParameter) } if let cursor = cursor { let queryParameter = URLQueryItem(name: "cursor", value: cursor) queryParameters.append(queryParameter) } // construct REST request let request = RestRequest( method: "GET", url: serviceURL + "/v1/logs", credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<LogCollection>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Delete labeled data. Deletes all data associated with a specified customer ID. The method has no effect if no data is associated with the customer ID. You associate a customer ID with data by passing the `X-Watson-Metadata` header with a request that passes data. For more information about personal data and customer IDs, see [Information security](https://console.bluemix.net/docs/services/conversation/information-security.html). - parameter customerID: The customer ID for which all data is to be deleted. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func deleteUserData( customerID: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping () -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) queryParameters.append(URLQueryItem(name: "customer_id", value: customerID)) // construct REST request let request = RestRequest( method: "DELETE", url: serviceURL + "/v1/user_data", credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseVoid(responseToError: responseToError) { (response: RestResponse) in switch response.result { case .success: success() case .failure(let error): failure?(error) } } } }
mit
c0ccfd071be1169fbcbc65d61a86e69f
40.782595
152
0.634836
5.235196
false
false
false
false
mzp/OctoEye
Tests/Unit/Store/FileItemStoreSpec.swift
1
2566
// // FileItemStoreSpec.swift // Tests // // Created by mzp on 2017/09/09. // Copyright © 2017 mzp. All rights reserved. // import Nimble import Quick // swiftlint:disable function_body_length, force_try internal class FileItemStoreSPec: QuickSpec { func make(name: String, parent: FileItemIdentifier) -> GithubObjectItem { let owner = OwnerObject(login: "mzp") let repository = RepositoryObject(owner: owner, name: "OctoEye") let object = BlobObject(byteSize: 42) return GithubObjectItem( entryObject: EntryObject( repository: repository, oid: "oid", name: name, type: "blob", object: object), // swiftlint:disable:next force_unwrapping parent: parent)! } override func spec() { let subject = FileItemStore() beforeEach { JsonCache<String>.clearAll() } describe("root") { it("returns nothing") { expect(subject[.root]).to(beNil()) } it("cannot store anything") { expect { try subject.append(parent: .root, entries: [:]) }.notTo(throwAssertion()) } } describe("repository") { let identifier = FileItemIdentifier.repository(owner: "mzp", name: "OctoEye") it("can store children") { try! subject.append(parent: identifier, entries: [ "foo": self.make(name: "foo", parent: identifier), "bar": self.make(name: "bar", parent: identifier) ]) let result = subject[.entry(owner: "mzp", name: "OctoEye", oid: "_", path: ["foo"])] expect(result?.filename) == "foo.show-extension" } } describe("repository") { let identifier = FileItemIdentifier.entry(owner: "mzp", name: "OctoEye", oid: "_", path: ["foo"]) it("returns non-store value") { expect(subject[identifier]).to(beNil()) } it("can store children") { try! subject.append(parent: identifier, entries: [ "bar": self.make(name: "bar", parent: identifier), "baz": self.make(name: "baz", parent: identifier) ]) let result = subject[.entry(owner: "mzp", name: "OctoEye", oid: "_", path: ["foo", "bar"])] expect(result?.filename) == "bar.show-extension" } } } }
mit
1078376769d4959bee52101f0ea01e1f
33.2
109
0.520858
4.392123
false
false
false
false
dfsilva/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Auth/AACountryViewController.swift
4
4759
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import UIKit public protocol AACountryViewControllerDelegate { func countriesController(_ countriesController: AACountryViewController, didChangeCurrentIso currentIso: String) } open class AACountryViewController: AATableViewController { fileprivate var _countries: NSDictionary! fileprivate var _letters: Array<String>! open var delegate: AACountryViewControllerDelegate? public init() { super.init(style: UITableViewStyle.plain) self.title = AALocalized("AuthCountryTitle") let cancelButtonItem = UIBarButtonItem(title: AALocalized("NavigationCancel"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(AAViewController.dismissController)) self.navigationItem.setLeftBarButton(cancelButtonItem, animated: false) self.content = ACAllEvents_Auth.auth_PICK_COUNTRY() } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = 44.0 tableView.sectionIndexBackgroundColor = UIColor.clear } fileprivate func countries() -> NSDictionary { if (_countries == nil) { let countries = NSMutableDictionary() for (_, iso) in ABPhoneField.sortedIsoCodes().enumerated() { let countryName = ABPhoneField.countryNameByCountryCode()[iso as! String] as! String let phoneCode = ABPhoneField.callingCodeByCountryCode()[iso as! String] as! String // if (self.searchBar.text.length == 0 || [countryName rangeOfString:self.searchBar.text options:NSCaseInsensitiveSearch].location != NSNotFound) let countryLetter = countryName.substring(to: countryName.characters.index(countryName.startIndex, offsetBy: 1)) if (countries[countryLetter] == nil) { countries[countryLetter] = NSMutableArray() } (countries[countryLetter]! as AnyObject).add([countryName, iso, phoneCode]) } _countries = countries; } return _countries; } fileprivate func letters() -> Array<String> { if (_letters == nil) { _letters = (countries().allKeys as! [String]).sorted(by: { (a: String, b: String) -> Bool in return a < b }) } return _letters } open func sectionIndexTitlesForTableView(_ tableView: UITableView) -> [AnyObject]! { return letters() as [AnyObject] } open func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { return index } open override func numberOfSections(in tableView: UITableView) -> Int { return letters().count; } open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let letter = letters()[section] let cs = countries().object(forKey: letter) as! NSArray return cs.count } open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: AAAuthCountryCell = tableView.dequeueCell(indexPath) let letter = letters()[(indexPath as NSIndexPath).section] let countryData = (countries().object(forKey: letter) as! NSArray)[(indexPath as NSIndexPath).row] as! [String] cell.setTitle(countryData[0]) cell.setCode("+\(countryData[2])") cell.setSearchMode(false) return cell } open func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let letter = letters()[(indexPath as NSIndexPath).section] let countryData = (countries().object(forKey: letter) as! NSArray)[(indexPath as NSIndexPath).row] as! [String] delegate?.countriesController(self, didChangeCurrentIso: countryData[1]) dismissController() } open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 25.0 } open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return letters()[section] } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) UIApplication.shared.setStatusBarStyle(.default, animated: true) } }
agpl-3.0
bacee373713122b56e12f3fea60b75ec
37.691057
190
0.641942
5.258564
false
false
false
false
reactive-swift/Event
Sources/Event/SignalNode.swift
1
1598
//===--- SignalNode.swift ----------------------------------------------===// //Copyright (c) 2016 Crossroad Labs s.r.o. // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //===----------------------------------------------------------------------===// import Foundation import ExecutionContext public protocol SignalNodeProtocol : SignalStreamProtocol, SignalEndpoint { } open class SignalNode<T> : SignalStream<T>, SignalNodeProtocol { public init(context: ExecutionContextProtocol = ExecutionContext.current) { super.init(context: context, recycle: {}) } public func signal(signature:Set<Int>, payload:Payload) { self.emit(signal: (signature, payload)) } } public extension SignalNodeProtocol { public func emit(payload:Payload) { self <= payload } } public extension SignalNodeProtocol { public func bind<SN : SignalNodeProtocol>(to node: SN) -> Off where SN.Payload == Payload { let forth = pour(to: node) let back = subscribe(to: node) return { forth() back() } } }
apache-2.0
d9bbca366f8cadb72fc9f3aafd7d6679
30.96
95
0.632666
4.591954
false
false
false
false
khizkhiz/swift
validation-test/Evolution/test_enum_change_size.swift
2
2312
// RUN: %target-resilience-test // REQUIRES: executable_test import StdlibUnittest import enum_change_size // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate import SwiftPrivatePthreadExtras #if _runtime(_ObjC) import ObjectiveC #endif var EnumChangeSizeTest = TestSuite("EnumChangeSize") public func getMySingletonEnumValues(c: ChangeSize) -> [SingletonEnum?] { return [.X(c), nil] } EnumChangeSizeTest.test("SingletonEnum") { do { let c = ChangeSize(value: 123) for e in [getMySingletonEnumValues(c), getSingletonEnumValues(c)] { let b: [Int] = e.map { switch $0 { case .some(.X(let cc)): expectEqual(c.value, cc.value) return 0 case .none: return 1 } } expectEqual(b, [0, 1]) } } } public func getMySinglePayloadEnumValues(c: ChangeSize) -> [SinglePayloadEnum?] { return [.X(c), .Y, .Z, nil] } EnumChangeSizeTest.test("SinglePayloadEnum") { do { let c = ChangeSize(value: 123) for e in [getMySinglePayloadEnumValues(c), getSinglePayloadEnumValues(c)] { let b: [Int] = e.map { switch $0 { case .some(.X(let cc)): expectEqual(c.value, cc.value) return 0 case .some(.Y): return 1 case .some(.Z): return 2 case .none: return 3 } } expectEqual(b, [0, 1, 2, 3]) } } } public func getMyMultiPayloadEnumValues(c: ChangeSize, _ d: ChangeSize) -> [MultiPayloadEnum?] { return [.X(c), .Y(d), .Z, nil] } EnumChangeSizeTest.test("MultiPayloadEnum") { do { let c = ChangeSize(value: 123) let d = ChangeSize(value: 321) for e in [getMyMultiPayloadEnumValues(c, d), getMultiPayloadEnumValues(c, d)] { let b: [Int] = e.map { switch $0 { case .some(.X(let cc)): expectEqual(c.value, cc.value) return 0 case .some(.Y(let dd)): expectEqual(d.value, dd.value) return 1 case .some(.Z): return 2 case .none: return 3 } } expectEqual(b, [0, 1, 2, 3]) } } } runAllTests()
apache-2.0
523ef99d87e877461e8eb1dcb6fff273
22.591837
83
0.591696
3.567901
false
true
false
false
cuappdev/podcast-ios
old/Podcast/Player.swift
1
19813
import UIKit import AVFoundation import MediaPlayer import Kingfisher class ListeningDuration { var id: String var currentProgress: Double? var percentageListened: Double var realDuration: Double? init(id: String, currentProgress: Double, percentageListened: Double, realDuration: Double?) { self.id = id self.currentProgress = currentProgress self.percentageListened = percentageListened self.realDuration = realDuration } } protocol PlayerDelegate: class { func updateUIForEpisode(episode: Episode) func updateUIForPlayback() func updateUIForEmptyPlayer() } enum PlayerRate: Float { case one = 1 case zero_5 = 0.5 case one_25 = 1.25 case one_5 = 1.5 case one_75 = 1.75 case two = 2 func toString() -> String { switch self { case .one, .two: return String(Int(self.rawValue)) + "x" default: return "\(self.rawValue)x" } } // no zero included b/c that's a pause static func values() -> [PlayerRate] { return [.zero_5, .one, .one_25, .one_5, one_75, .two] } } class Player: NSObject { static let sharedInstance = Player() private override init() { player = AVPlayer() if #available(iOS 10, *) { player.automaticallyWaitsToMinimizeStalling = false } autoplayEnabled = true currentItemPrepared = false isScrubbing = false savedRate = .one super.init() configureCommands() } deinit { removeCurrentItemStatusObserver() removeTimeObservers() } weak var delegate: PlayerDelegate? // Mark: KVO variables private var playerItemContext: UnsafeMutableRawPointer? private var timeObserverToken: Any? // Mark: Playback variables/methods private var player: AVPlayer private(set) var currentEpisode: Episode? private var currentTimeAt: Double = 0.0 private var currentEpisodePercentageListened: Double = 0.0 private var nowPlayingInfo: [String: Any]? private var artworkImage: MPMediaItemArtwork? private var autoplayEnabled: Bool private var currentItemPrepared: Bool var savePreferences: Bool = false var trimSilence: Bool = false var listeningDurations: [String: ListeningDuration] = [:] var isScrubbing: Bool var isPlaying: Bool { get { return player.rate != 0.0 || (!currentItemPrepared && autoplayEnabled && (player.currentItem != nil)) } } var savedRate: PlayerRate func resetUponLogout() { saveListeningDurations() listeningDurations = [:] reset() pause() } func playEpisode(episode: Episode) { if currentEpisode?.id == episode.id { currentEpisode?.currentProgress = getProgress() // if the same episode was set we just toggle the player togglePlaying() return } saveListeningDurations() // save preferences if let currentUser = System.currentUser, let seriesId = currentEpisode?.seriesID { if savePreferences { let prefs = SeriesPreferences(playerRate: savedRate, trimSilences: trimSilence) UserPreferences.savePreference(preference: prefs, for: currentUser, and: seriesId) } else { // we aren't saving prefs UserPreferences.removePreference(for: currentUser, and: seriesId) } } var url: URL? if DownloadManager.shared.isDownloaded(episode.id) { if episode.audioURL != nil { url = DownloadManager.shared.fileUrl(for: episode) } else if let httpURL = episode.audioURL { url = httpURL } } else { if let httpURL = episode.audioURL { url = httpURL } } guard let u = url else { print("Episode \(episode.title) mp3URL is nil. Unable to play.") return } if player.status == AVPlayerStatus.failed { if let error = player.error { print(error) } player = AVPlayer() if #available(iOS 10, *) { player.automaticallyWaitsToMinimizeStalling = false } } // cleanup any previous AVPlayerItem pause() removeCurrentItemStatusObserver() if let listeningDuration = listeningDurations[episode.id] { // if we've played this episode before if let currentProgress = listeningDuration.currentProgress { currentTimeAt = currentProgress // played this episode before and have valid current progress } else { currentTimeAt = 0.0 } } else { // never played this episode before, use episodes saved currentProgress listeningDurations[episode.id] = ListeningDuration(id: episode.id, currentProgress: episode.currentProgress, percentageListened: 0, realDuration: nil) currentTimeAt = episode.currentProgress } // swap epsiodes currentEpisode?.isPlaying = false episode.isPlaying = true currentEpisode = episode updateNowPlayingArtwork() reset() // load saved preferences for this series if they exist if let savedPref = UserPreferences.userToSeriesPreference(for: System.currentUser!, seriesId: currentEpisode!.seriesID) { savedRate = savedPref.playerRate trimSilence = savedPref.trimSilences savePreferences = true } let asset = AVAsset(url: u) let playerItem = AVPlayerItem(asset: asset, automaticallyLoadedAssetKeys: ["playable"]) playerItem.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [.old, .new], context: &playerItemContext) player.replaceCurrentItem(with: playerItem) updateNowPlayingInfo() delegate?.updateUIForEpisode(episode: currentEpisode!) delegate?.updateUIForPlayback() NotificationCenter.default.addObserver(self, selector: #selector(updateNowPlayingInfo), name: .AVPlayerItemTimeJumped, object: nil) } @objc func play() { if let currentItem = player.currentItem { if currentItem.status == .readyToPlay { try! AVAudioSession.sharedInstance().setActive(true) setProgress(progress: currentTimeAt, completion: { self.player.play() self.player.rate = self.savedRate.rawValue }) setSpeed(rate: savedRate) delegate?.updateUIForPlayback() updateNowPlayingInfo() addTimeObservers() } else { autoplayEnabled = true } } } @objc func pause() { currentTimeAt = getProgress() updateNowPlayingInfo() if let currentItem = player.currentItem { guard let rate = PlayerRate(rawValue: player.rate) else { return } if currentItem.status == .readyToPlay { savedRate = rate player.pause() updateNowPlayingInfo() removeTimeObservers() delegate?.updateUIForPlayback() } else { autoplayEnabled = false } } } func togglePlaying() { if isPlaying { pause() } else { play() } delegate?.updateUIForPlayback() } func reset() { autoplayEnabled = true currentItemPrepared = false isScrubbing = false setSpeed(rate: UserPreferences.defaultPlayerRate) savePreferences = false trimSilence = false } func skip(seconds: Double) { guard let currentItem = player.currentItem else { return } let newTime = CMTimeAdd(currentItem.currentTime(), CMTime(seconds: seconds, preferredTimescale: CMTimeScale(1.0))) player.currentItem?.seek(to: newTime, completionHandler: { success in self.currentTimeAt = self.getProgress() self.updateNowPlayingInfo() }) if newTime > CMTime(seconds: 0.0, preferredTimescale: CMTimeScale(1.0)) { self.currentTimeAt = self.getProgress() delegate?.updateUIForPlayback() } } func setSpeed(rate: PlayerRate) { savedRate = rate if isPlaying { player.rate = rate.rawValue } delegate?.updateUIForPlayback() } func getSpeed() -> PlayerRate { return savedRate } func getProgress() -> Double { if let currentItem = player.currentItem { let currentTime = currentItem.currentTime() let durationTime = currentItem.duration if !durationTime.isIndefinite && durationTime.seconds != 0 { return currentTime.seconds / durationTime.seconds } } return 0.0 } func getDuration() -> Double { guard let currentItem = player.currentItem else { return 0.0 } return currentItem.duration.seconds } func setProgress(progress: Double, completion: (() -> ())? = nil) { if let duration = player.currentItem?.duration { if !duration.isIndefinite { player.currentItem!.seek(to: CMTime(seconds: duration.seconds * min(max(progress, 0.0), 1.0), preferredTimescale: CMTimeScale(1.0)), completionHandler: { (_) in completion?() self.isScrubbing = false self.currentTimeAt = self.getProgress() self.delegate?.updateUIForPlayback() self.updateNowPlayingInfo() }) } } } func seekTo(_ position: TimeInterval) { if let _ = player.currentItem { updateCurrentPercentageListened() let newPosition = CMTimeMakeWithSeconds(position, 1) player.seek(to: newPosition, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero, completionHandler: { (_) in self.currentTimeAt = self.getProgress() self.delegate?.updateUIForPlayback() self.updateNowPlayingInfo() }) } } // Configures the Remote Command Center for our player. Should only be called once (in init) func configureCommands() { UIApplication.shared.beginReceivingRemoteControlEvents() let commandCenter = MPRemoteCommandCenter.shared() commandCenter.pauseCommand.addTarget(self, action: #selector(Player.pause)) commandCenter.playCommand.addTarget(self, action: #selector(Player.play)) commandCenter.skipForwardCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in self.skip(seconds: 30) return .success } commandCenter.skipForwardCommand.preferredIntervals = [30] commandCenter.skipBackwardCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in self.skip(seconds: -30) return .success } commandCenter.skipBackwardCommand.preferredIntervals = [30] commandCenter.changePlaybackPositionCommand.addTarget(self, action: #selector(Player.handleChangePlaybackPositionCommandEvent(event:))) } @objc func handleChangePlaybackPositionCommandEvent(event: MPChangePlaybackPositionCommandEvent) -> MPRemoteCommandHandlerStatus { seekTo(event.positionTime) return .success } // Updates information in Notfication Center/Lockscreen info @objc func updateNowPlayingInfo() { guard let episode = currentEpisode else { configureNowPlaying(info: nil) return } var nowPlayingInfo = [ MPMediaItemPropertyTitle: episode.title, MPMediaItemPropertyArtist: episode.seriesTitle, MPMediaItemPropertyAlbumTitle: episode.seriesTitle, MPNowPlayingInfoPropertyPlaybackRate: NSNumber(value: savedRate.rawValue), MPNowPlayingInfoPropertyElapsedPlaybackTime: NSNumber(value: CMTimeGetSeconds(currentItemElapsedTime())), MPMediaItemPropertyPlaybackDuration: NSNumber(value: CMTimeGetSeconds(currentItemDuration())), ] as [String : Any] if let image = artworkImage { nowPlayingInfo[MPMediaItemPropertyArtwork] = image } configureNowPlaying(info: nowPlayingInfo) } // Updates the now playing artwork. func updateNowPlayingArtwork() { guard let episode = currentEpisode, let url = episode.smallArtworkImageURL else { return } ImageCache.default.retrieveImage(forKey: episode.id, options: nil) { image, cacheType in if let image = image { //In this code snippet, the `cacheType` is .disk self.artworkImage = MPMediaItemArtwork(boundsSize: CGSize(width: image.size.width, height: image.size.height), requestHandler: { _ in image }) self.updateNowPlayingInfo() } else { ImageDownloader.default.downloadImage(with: url, options: [], progressBlock: nil) { (imageDown, error, url, data) in if let imageDown = imageDown { ImageCache.default.store(imageDown, forKey: episode.id) self.artworkImage = MPMediaItemArtwork(boundsSize: CGSize(width: imageDown.size.width, height: imageDown.size.height), requestHandler: { _ in imageDown }) self.updateNowPlayingInfo() } } } } } // Configures the MPNowPlayingInfoCenter func configureNowPlaying(info: [String : Any]?) { self.nowPlayingInfo = info MPNowPlayingInfoCenter.default().nowPlayingInfo = info } // Warning: these next three functions should only be used to set UI element values func currentItemDuration() -> CMTime { guard let duration = player.currentItem?.duration else { return CMTime(seconds: 0.0, preferredTimescale: CMTimeScale(1.0)) } return duration.isIndefinite ? CMTime(seconds: 0.0, preferredTimescale: CMTimeScale(1.0)) : duration } func currentItemElapsedTime() -> CMTime { return player.currentItem?.currentTime() ?? CMTime(seconds: 0.0, preferredTimescale: CMTimeScale(1.0)) } func currentItemRemainingTime() -> CMTime { guard let duration = player.currentItem?.duration else { return CMTime(seconds: 0.0, preferredTimescale: CMTimeScale(1.0)) } let elapsedTime = currentItemElapsedTime() return CMTimeSubtract(duration, elapsedTime) } // Mark: KVO methods func addTimeObservers() { timeObserverToken = player.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1.0, Int32(NSEC_PER_SEC)), queue: DispatchQueue.main, using: { [weak self] _ in self?.delegate?.updateUIForPlayback() self?.updateNowPlayingInfo() }) NotificationCenter.default.addObserver(self, selector: #selector(currentItemDidPlayToEndTime), name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem) } func removeTimeObservers() { guard let token = timeObserverToken else { return } player.removeTimeObserver(token) timeObserverToken = nil NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem) } func removeCurrentItemStatusObserver() { // observeValue(...) will take care of removing AVPlayerItem.status observer once it is // readyToPlay, so we only need to remove observer if AVPlayerItem isn't readyToPlay yet if let currentItem = player.currentItem { if currentItem.status != .readyToPlay { currentItem.removeObserver(self, forKeyPath: #keyPath(AVPlayer.status), context: &playerItemContext) } } } @objc func currentItemDidPlayToEndTime() { removeTimeObservers() delegate?.updateUIForPlayback() updateNowPlayingInfo() } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { // Only handle observations for the playerItemContext guard context == &playerItemContext else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } if keyPath == #keyPath(AVPlayerItem.status) { let status: AVPlayerItemStatus if let statusNumber = change?[.newKey] as? NSNumber { status = AVPlayerItemStatus(rawValue: statusNumber.intValue)! } else { status = .unknown } switch status { case .readyToPlay: print("AVPlayerItem ready to play") currentItemPrepared = true if autoplayEnabled { play() } case .failed: print("Failed to load AVPlayerItem") return case .unknown: print("Unknown AVPlayerItemStatus") return } // remove observer after having reading the AVPlayerItem status player.currentItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), context: &playerItemContext) } } func updateCurrentPercentageListened() { currentEpisodePercentageListened += abs(getProgress() - currentTimeAt) currentTimeAt = getProgress() } func saveListeningDurations() { if let current = currentEpisode { if let listeningDuration = listeningDurations[current.id] { listeningDuration.currentProgress = getProgress().isNaN ? nil : getProgress() current.currentProgress = listeningDuration.currentProgress != nil ? listeningDuration.currentProgress! : current.currentProgress listeningDuration.realDuration = getDuration().isNaN ? nil : getDuration() // don't send invalid duration updateCurrentPercentageListened() listeningDuration.percentageListened = listeningDuration.percentageListened + currentEpisodePercentageListened currentEpisodePercentageListened = 0 } else { print("Trying to save an episode never played before: \(current.title)") } } let endpointRequest = SaveListeningDurationEndpointRequest(listeningDurations: listeningDurations) endpointRequest.success = { _ in print("Successfully saved listening duration history") } endpointRequest.failure = { _ in print("Unsuccesfully saved listening duration history") } System.endpointRequestQueue.addOperation(endpointRequest) } }
mit
9060e2abac95805e0fd71ca133490195
37.028791
176
0.602382
5.49293
false
false
false
false
bparish628/iFarm-Health
iOS/iFarm-Health/Pods/Charts/Source/Charts/Utils/ChartColorTemplates.swift
11
7927
// // ChartColorTemplates.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class ChartColorTemplates: NSObject { @objc open class func liberty () -> [NSUIColor] { return [ NSUIColor(red: 207/255.0, green: 248/255.0, blue: 246/255.0, alpha: 1.0), NSUIColor(red: 148/255.0, green: 212/255.0, blue: 212/255.0, alpha: 1.0), NSUIColor(red: 136/255.0, green: 180/255.0, blue: 187/255.0, alpha: 1.0), NSUIColor(red: 118/255.0, green: 174/255.0, blue: 175/255.0, alpha: 1.0), NSUIColor(red: 42/255.0, green: 109/255.0, blue: 130/255.0, alpha: 1.0) ] } @objc open class func joyful () -> [NSUIColor] { return [ NSUIColor(red: 217/255.0, green: 80/255.0, blue: 138/255.0, alpha: 1.0), NSUIColor(red: 254/255.0, green: 149/255.0, blue: 7/255.0, alpha: 1.0), NSUIColor(red: 254/255.0, green: 247/255.0, blue: 120/255.0, alpha: 1.0), NSUIColor(red: 106/255.0, green: 167/255.0, blue: 134/255.0, alpha: 1.0), NSUIColor(red: 53/255.0, green: 194/255.0, blue: 209/255.0, alpha: 1.0) ] } @objc open class func pastel () -> [NSUIColor] { return [ NSUIColor(red: 64/255.0, green: 89/255.0, blue: 128/255.0, alpha: 1.0), NSUIColor(red: 149/255.0, green: 165/255.0, blue: 124/255.0, alpha: 1.0), NSUIColor(red: 217/255.0, green: 184/255.0, blue: 162/255.0, alpha: 1.0), NSUIColor(red: 191/255.0, green: 134/255.0, blue: 134/255.0, alpha: 1.0), NSUIColor(red: 179/255.0, green: 48/255.0, blue: 80/255.0, alpha: 1.0) ] } @objc open class func colorful () -> [NSUIColor] { return [ NSUIColor(red: 193/255.0, green: 37/255.0, blue: 82/255.0, alpha: 1.0), NSUIColor(red: 255/255.0, green: 102/255.0, blue: 0/255.0, alpha: 1.0), NSUIColor(red: 245/255.0, green: 199/255.0, blue: 0/255.0, alpha: 1.0), NSUIColor(red: 106/255.0, green: 150/255.0, blue: 31/255.0, alpha: 1.0), NSUIColor(red: 179/255.0, green: 100/255.0, blue: 53/255.0, alpha: 1.0) ] } @objc open class func vordiplom () -> [NSUIColor] { return [ NSUIColor(red: 192/255.0, green: 255/255.0, blue: 140/255.0, alpha: 1.0), NSUIColor(red: 255/255.0, green: 247/255.0, blue: 140/255.0, alpha: 1.0), NSUIColor(red: 255/255.0, green: 208/255.0, blue: 140/255.0, alpha: 1.0), NSUIColor(red: 140/255.0, green: 234/255.0, blue: 255/255.0, alpha: 1.0), NSUIColor(red: 255/255.0, green: 140/255.0, blue: 157/255.0, alpha: 1.0) ] } @objc open class func material () -> [NSUIColor] { return [ NSUIColor(red: 46/255.0, green: 204/255.0, blue: 113/255.0, alpha: 1.0), NSUIColor(red: 241/255.0, green: 196/255.0, blue: 15/255.0, alpha: 1.0), NSUIColor(red: 231/255.0, green: 76/255.0, blue: 60/255.0, alpha: 1.0), NSUIColor(red: 52/255.0, green: 152/255.0, blue: 219/255.0, alpha: 1.0) ] } @objc open class func colorFromString(_ colorString: String) -> NSUIColor { let leftParenCharset: CharacterSet = CharacterSet(charactersIn: "( ") let commaCharset: CharacterSet = CharacterSet(charactersIn: ", ") let colorString = colorString.lowercased() if colorString.hasPrefix("#") { var argb: [UInt] = [255, 0, 0, 0] let colorString = colorString.unicodeScalars var length = colorString.count var index = colorString.startIndex let endIndex = colorString.endIndex index = colorString.index(after: index) length = length - 1 if length == 3 || length == 6 || length == 8 { var i = length == 8 ? 0 : 1 while index < endIndex { var c = colorString[index] index = colorString.index(after: index) var val = (c.value >= 0x61 && c.value <= 0x66) ? (c.value - 0x61 + 10) : c.value - 0x30 argb[i] = UInt(val) * 16 if length == 3 { argb[i] = argb[i] + UInt(val) } else { c = colorString[index] index = colorString.index(after: index) val = (c.value >= 0x61 && c.value <= 0x66) ? (c.value - 0x61 + 10) : c.value - 0x30 argb[i] = argb[i] + UInt(val) } i += 1 } } return NSUIColor(red: CGFloat(argb[1]) / 255.0, green: CGFloat(argb[2]) / 255.0, blue: CGFloat(argb[3]) / 255.0, alpha: CGFloat(argb[0]) / 255.0) } else if colorString.hasPrefix("rgba") { var a: Float = 1.0 var r: Int32 = 0 var g: Int32 = 0 var b: Int32 = 0 let scanner: Scanner = Scanner(string: colorString) scanner.scanString("rgba", into: nil) scanner.scanCharacters(from: leftParenCharset, into: nil) scanner.scanInt32(&r) scanner.scanCharacters(from: commaCharset, into: nil) scanner.scanInt32(&g) scanner.scanCharacters(from: commaCharset, into: nil) scanner.scanInt32(&b) scanner.scanCharacters(from: commaCharset, into: nil) scanner.scanFloat(&a) return NSUIColor( red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(a) ) } else if colorString.hasPrefix("argb") { var a: Float = 1.0 var r: Int32 = 0 var g: Int32 = 0 var b: Int32 = 0 let scanner: Scanner = Scanner(string: colorString) scanner.scanString("argb", into: nil) scanner.scanCharacters(from: leftParenCharset, into: nil) scanner.scanFloat(&a) scanner.scanCharacters(from: commaCharset, into: nil) scanner.scanInt32(&r) scanner.scanCharacters(from: commaCharset, into: nil) scanner.scanInt32(&g) scanner.scanCharacters(from: commaCharset, into: nil) scanner.scanInt32(&b) return NSUIColor( red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(a) ) } else if colorString.hasPrefix("rgb") { var r: Int32 = 0 var g: Int32 = 0 var b: Int32 = 0 let scanner: Scanner = Scanner(string: colorString) scanner.scanString("rgb", into: nil) scanner.scanCharacters(from: leftParenCharset, into: nil) scanner.scanInt32(&r) scanner.scanCharacters(from: commaCharset, into: nil) scanner.scanInt32(&g) scanner.scanCharacters(from: commaCharset, into: nil) scanner.scanInt32(&b) return NSUIColor( red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: 1.0 ) } return NSUIColor.clear } }
apache-2.0
9fb65a02ad83f4a7f74b6e5792821258
38.049261
157
0.508137
3.622943
false
false
false
false
xhacker/TagListView
TagListView/TagListView.swift
2
14488
// // TagListView.swift // TagListViewDemo // // Created by Dongyuan Liu on 2015-05-09. // Copyright (c) 2015 Ela. All rights reserved. // import UIKit @objc public protocol TagListViewDelegate { @objc optional func tagPressed(_ title: String, tagView: TagView, sender: TagListView) -> Void @objc optional func tagRemoveButtonPressed(_ title: String, tagView: TagView, sender: TagListView) -> Void } @IBDesignable open class TagListView: UIView { @IBInspectable open dynamic var textColor: UIColor = .white { didSet { tagViews.forEach { $0.textColor = textColor } } } @IBInspectable open dynamic var selectedTextColor: UIColor = .white { didSet { tagViews.forEach { $0.selectedTextColor = selectedTextColor } } } @IBInspectable open dynamic var tagLineBreakMode: NSLineBreakMode = .byTruncatingMiddle { didSet { tagViews.forEach { $0.titleLineBreakMode = tagLineBreakMode } } } @IBInspectable open dynamic var tagBackgroundColor: UIColor = UIColor.gray { didSet { tagViews.forEach { $0.tagBackgroundColor = tagBackgroundColor } } } @IBInspectable open dynamic var tagHighlightedBackgroundColor: UIColor? { didSet { tagViews.forEach { $0.highlightedBackgroundColor = tagHighlightedBackgroundColor } } } @IBInspectable open dynamic var tagSelectedBackgroundColor: UIColor? { didSet { tagViews.forEach { $0.selectedBackgroundColor = tagSelectedBackgroundColor } } } @IBInspectable open dynamic var cornerRadius: CGFloat = 0 { didSet { tagViews.forEach { $0.cornerRadius = cornerRadius } } } @IBInspectable open dynamic var borderWidth: CGFloat = 0 { didSet { tagViews.forEach { $0.borderWidth = borderWidth } } } @IBInspectable open dynamic var borderColor: UIColor? { didSet { tagViews.forEach { $0.borderColor = borderColor } } } @IBInspectable open dynamic var selectedBorderColor: UIColor? { didSet { tagViews.forEach { $0.selectedBorderColor = selectedBorderColor } } } @IBInspectable open dynamic var paddingY: CGFloat = 2 { didSet { defer { rearrangeViews() } tagViews.forEach { $0.paddingY = paddingY } } } @IBInspectable open dynamic var paddingX: CGFloat = 5 { didSet { defer { rearrangeViews() } tagViews.forEach { $0.paddingX = paddingX } } } @IBInspectable open dynamic var marginY: CGFloat = 2 { didSet { rearrangeViews() } } @IBInspectable open dynamic var marginX: CGFloat = 5 { didSet { rearrangeViews() } } @IBInspectable open dynamic var minWidth: CGFloat = 0 { didSet { rearrangeViews() } } @objc public enum Alignment: Int { case left case center case right case leading case trailing } @IBInspectable open var alignment: Alignment = .leading { didSet { rearrangeViews() } } @IBInspectable open dynamic var shadowColor: UIColor = .white { didSet { rearrangeViews() } } @IBInspectable open dynamic var shadowRadius: CGFloat = 0 { didSet { rearrangeViews() } } @IBInspectable open dynamic var shadowOffset: CGSize = .zero { didSet { rearrangeViews() } } @IBInspectable open dynamic var shadowOpacity: Float = 0 { didSet { rearrangeViews() } } @IBInspectable open dynamic var enableRemoveButton: Bool = false { didSet { defer { rearrangeViews() } tagViews.forEach { $0.enableRemoveButton = enableRemoveButton } } } @IBInspectable open dynamic var removeButtonIconSize: CGFloat = 12 { didSet { defer { rearrangeViews() } tagViews.forEach { $0.removeButtonIconSize = removeButtonIconSize } } } @IBInspectable open dynamic var removeIconLineWidth: CGFloat = 1 { didSet { defer { rearrangeViews() } tagViews.forEach { $0.removeIconLineWidth = removeIconLineWidth } } } @IBInspectable open dynamic var removeIconLineColor: UIColor = UIColor.white.withAlphaComponent(0.54) { didSet { defer { rearrangeViews() } tagViews.forEach { $0.removeIconLineColor = removeIconLineColor } } } @objc open dynamic var textFont: UIFont = .systemFont(ofSize: 12) { didSet { defer { rearrangeViews() } tagViews.forEach { $0.textFont = textFont } } } @IBOutlet open weak var delegate: TagListViewDelegate? open private(set) var tagViews: [TagView] = [] private(set) var tagBackgroundViews: [UIView] = [] private(set) var rowViews: [UIView] = [] private(set) var tagViewHeight: CGFloat = 0 private(set) var rows = 0 { didSet { invalidateIntrinsicContentSize() } } // MARK: - Interface Builder open override func prepareForInterfaceBuilder() { addTag("Welcome") addTag("to") addTag("TagListView").isSelected = true } // MARK: - Layout open override func layoutSubviews() { defer { rearrangeViews() } super.layoutSubviews() } private func rearrangeViews() { let views = tagViews as [UIView] + tagBackgroundViews + rowViews views.forEach { $0.removeFromSuperview() } rowViews.removeAll(keepingCapacity: true) var isRtl: Bool = false if #available(iOS 10.0, tvOS 10.0, *) { isRtl = effectiveUserInterfaceLayoutDirection == .rightToLeft } else if #available(iOS 9.0, *) { isRtl = UIView.userInterfaceLayoutDirection(for: semanticContentAttribute) == .rightToLeft } else if let shared = UIApplication.value(forKey: "sharedApplication") as? UIApplication { isRtl = shared.userInterfaceLayoutDirection == .leftToRight } var alignment = self.alignment if alignment == .leading { alignment = isRtl ? .right : .left } else if alignment == .trailing { alignment = isRtl ? .left : .right } var currentRow = 0 var currentRowView: UIView! var currentRowTagCount = 0 var currentRowWidth: CGFloat = 0 let frameWidth = frame.width let directionTransform = isRtl ? CGAffineTransform(scaleX: -1.0, y: 1.0) : CGAffineTransform.identity for (index, tagView) in tagViews.enumerated() { tagView.frame.size = tagView.intrinsicContentSize tagViewHeight = tagView.frame.height if currentRowTagCount == 0 || currentRowWidth + tagView.frame.width > frameWidth { currentRow += 1 currentRowWidth = 0 currentRowTagCount = 0 currentRowView = UIView() currentRowView.transform = directionTransform currentRowView.frame.origin.y = CGFloat(currentRow - 1) * (tagViewHeight + marginY) rowViews.append(currentRowView) addSubview(currentRowView) tagView.frame.size.width = min(tagView.frame.size.width, frameWidth) } let tagBackgroundView = tagBackgroundViews[index] tagBackgroundView.transform = directionTransform tagBackgroundView.frame.origin = CGPoint( x: currentRowWidth, y: 0) tagBackgroundView.frame.size = tagView.bounds.size tagView.frame.size.width = max(minWidth, tagView.frame.size.width) tagBackgroundView.layer.shadowColor = shadowColor.cgColor tagBackgroundView.layer.shadowPath = UIBezierPath(roundedRect: tagBackgroundView.bounds, cornerRadius: cornerRadius).cgPath tagBackgroundView.layer.shadowOffset = shadowOffset tagBackgroundView.layer.shadowOpacity = shadowOpacity tagBackgroundView.layer.shadowRadius = shadowRadius tagBackgroundView.addSubview(tagView) currentRowView.addSubview(tagBackgroundView) currentRowTagCount += 1 currentRowWidth += tagView.frame.width + marginX switch alignment { case .leading: fallthrough // switch must be exahutive case .left: currentRowView.frame.origin.x = 0 case .center: currentRowView.frame.origin.x = (frameWidth - (currentRowWidth - marginX)) / 2 case .trailing: fallthrough // switch must be exahutive case .right: currentRowView.frame.origin.x = frameWidth - (currentRowWidth - marginX) } currentRowView.frame.size.width = currentRowWidth currentRowView.frame.size.height = max(tagViewHeight, currentRowView.frame.height) } rows = currentRow invalidateIntrinsicContentSize() } // MARK: - Manage tags override open var intrinsicContentSize: CGSize { var height = CGFloat(rows) * (tagViewHeight + marginY) if rows > 0 { height -= marginY } return CGSize(width: frame.width, height: height) } private func createNewTagView(_ title: String) -> TagView { let tagView = TagView(title: title) tagView.textColor = textColor tagView.selectedTextColor = selectedTextColor tagView.tagBackgroundColor = tagBackgroundColor tagView.highlightedBackgroundColor = tagHighlightedBackgroundColor tagView.selectedBackgroundColor = tagSelectedBackgroundColor tagView.titleLineBreakMode = tagLineBreakMode tagView.cornerRadius = cornerRadius tagView.borderWidth = borderWidth tagView.borderColor = borderColor tagView.selectedBorderColor = selectedBorderColor tagView.paddingX = paddingX tagView.paddingY = paddingY tagView.textFont = textFont tagView.removeIconLineWidth = removeIconLineWidth tagView.removeButtonIconSize = removeButtonIconSize tagView.enableRemoveButton = enableRemoveButton tagView.removeIconLineColor = removeIconLineColor tagView.addTarget(self, action: #selector(tagPressed(_:)), for: .touchUpInside) tagView.removeButton.addTarget(self, action: #selector(removeButtonPressed(_:)), for: .touchUpInside) // On long press, deselect all tags except this one tagView.onLongPress = { [unowned self] this in self.tagViews.forEach { $0.isSelected = $0 == this } } return tagView } @discardableResult open func addTag(_ title: String) -> TagView { defer { rearrangeViews() } return addTagView(createNewTagView(title)) } @discardableResult open func addTags(_ titles: [String]) -> [TagView] { return addTagViews(titles.map(createNewTagView)) } @discardableResult open func addTagView(_ tagView: TagView) -> TagView { defer { rearrangeViews() } tagViews.append(tagView) tagBackgroundViews.append(UIView(frame: tagView.bounds)) return tagView } @discardableResult open func addTagViews(_ tagViewList: [TagView]) -> [TagView] { defer { rearrangeViews() } tagViewList.forEach { tagViews.append($0) tagBackgroundViews.append(UIView(frame: $0.bounds)) } return tagViews } @discardableResult open func insertTag(_ title: String, at index: Int) -> TagView { return insertTagView(createNewTagView(title), at: index) } @discardableResult open func insertTagView(_ tagView: TagView, at index: Int) -> TagView { defer { rearrangeViews() } tagViews.insert(tagView, at: index) tagBackgroundViews.insert(UIView(frame: tagView.bounds), at: index) return tagView } open func setTitle(_ title: String, at index: Int) { tagViews[index].titleLabel?.text = title } open func removeTag(_ title: String) { tagViews.reversed().filter({ $0.currentTitle == title }).forEach(removeTagView) } open func removeTagView(_ tagView: TagView) { defer { rearrangeViews() } tagView.removeFromSuperview() if let index = tagViews.firstIndex(of: tagView) { tagViews.remove(at: index) tagBackgroundViews.remove(at: index) } } open func removeAllTags() { defer { tagViews = [] tagBackgroundViews = [] rearrangeViews() } let views: [UIView] = tagViews + tagBackgroundViews views.forEach { $0.removeFromSuperview() } } open func selectedTags() -> [TagView] { return tagViews.filter { $0.isSelected } } // MARK: - Events @objc func tagPressed(_ sender: TagView!) { sender.onTap?(sender) delegate?.tagPressed?(sender.currentTitle ?? "", tagView: sender, sender: self) } @objc func removeButtonPressed(_ closeButton: CloseButton!) { if let tagView = closeButton.tagView { delegate?.tagRemoveButtonPressed?(tagView.currentTitle ?? "", tagView: tagView, sender: self) } } }
mit
71fa667487118646e3fbc3bffc860720
30.495652
135
0.579169
5.289522
false
false
false
false
wenghengcong/Coderpursue
BeeFun/BeeFun/View/Trending/ViewCell/CPFilterTableView.swift
1
13910
// // CPFilterTableView.swift // BeeFun // // Created by WengHengcong on 3/12/16. // Copyright © 2016 JungleSong. All rights reserved. // import UIKit /// 筛选视图的协议方法 protocol CPFilterTableViewProtocol: class { /// 选中了筛选视图中的类型 /// /// - Parameters: /// - row: <#row description#> /// - type: <#type description#> func didSelectTypeColoumn(_ row: Int, type: String) /// 选中了筛选视图中的值 /// /// - Parameters: /// - row: <#row description#> /// - type: <#type description#> /// - value: <#value description#> func didSelectValueColoumn(_ row: Int, type: String, value: String) func didTapSinceTime(since: String) } /// 筛选视图的列数 /// /// - two: 两列 /// - three: 三列 public enum CPFilterTableViewColumns: Int { case two = 2 case three = 3 } /// 筛选视图 class CPFilterTableView: UIView { let cellID = "FilterCell" weak var filterDelegate: CPFilterTableViewProtocol? /// 筛选视图的列数 var coloumn: CPFilterTableViewColumns = .two /// 每行的宽度组合(多个tableview) var rowWidths: [CGFloat] = [0, 0] /// 每行的高度组合(多个tableview) var rowHeights: [CGFloat] = [0.0, 0.0] var filterTypes: [String] = [] var filterData: [[String]] = [[]] { didSet { resetAllColoumnsData() } } let indexArr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] var mutipleSectionData: [[[String]]] = [[[]]] var mutipleSectionIndex: [[String]] = [] let sinceArr: [String] = ["daily".localized, "weekly".localized, "monthly".localized] /// 选中的since index var selSinceIndex = 0 let sinceBackV = UIView() let sinceLabel = UILabel() var sinceButtons: [UIButton] = [] let separateLine = UIView() /// 当前选中的类型:左边tableview时候的index var selTypeIndex = 0 /// 选择第二个表格的 section 和 row var selSecValueSectionIndex = 0 var selSecValueRowIndex = 0 /// 类型Table var firTableView: UITableView? /// 值Table var secTableView: UITableView? var tableviews: [UITableView] = [] let bottomView = UIView() // MARK: - view cycle override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - View func filterViewInit() { ftv_customView() } func ftv_customView() { for subs in self.subviews { subs.removeFromSuperview() } customSinceView() customTableView() customBottomView() layoutAllSubviews() } func customSinceView() { separateLine.backgroundColor = UIColor.bfLineBackgroundColor addSubview(separateLine) sinceLabel.font = UIFont.bfSystemFont(ofSize: 14.0) sinceLabel.text = "Since".localized sinceLabel.textAlignment = .center sinceLabel.textColor = UIColor.black sinceLabel.backgroundColor = UIColor.white sinceBackV.addSubview(sinceLabel) for (index, sinceTime) in sinceArr.enumerated() { let sinceTimeBtn = UIButton() sinceTimeBtn.setTitle(sinceTime, for: .normal) sinceTimeBtn.setTitleColor(UIColor.black, for: .normal) sinceTimeBtn.setTitleColor(UIColor.bfRedColor, for: .selected) sinceTimeBtn.titleLabel?.font = UIFont.bfSystemFont(ofSize: 14.0) sinceTimeBtn.backgroundColor = UIColor.white sinceTimeBtn.addTarget(self, action: #selector(tapSinceButton(sender:)), for: .touchUpInside) if index == 0 { sinceTimeBtn.isSelected = true } sinceBackV.addSubview(sinceTimeBtn) sinceButtons.append(sinceTimeBtn) } addSubview(sinceBackV) } func customTableView() { //如果column的数目与当前的宽度组合数目不对,直接返回 if (coloumn.rawValue != rowWidths.count) || (coloumn.rawValue != rowHeights.count) { print("check coloumns and the datasouce count is equal") return } firTableView = UITableView() secTableView = UITableView() self.addSubview(firTableView!) self.addSubview(secTableView!) tableviews.append(firTableView!) tableviews.append(secTableView!) for (index, tableView) in tableviews.enumerated() { tableView.dataSource = self tableView.delegate = self tableView.separatorStyle = .none tableView.rowHeight = rowHeights[index] if #available(iOS 11, *) { tableView.estimatedRowHeight = 0 tableView.estimatedSectionHeaderHeight = 0 tableView.estimatedSectionFooterHeight = 0 } tableView.register(UITableViewCell.self, forCellReuseIdentifier:cellID) tableView.sectionIndexColor = UIColor.bfLabelSubtitleTextColor } } func customBottomView() { bottomView.backgroundColor = UIColor.bfRedColor self.addSubview(bottomView) } func layoutAllSubviews() { let firColoumWidth = rowWidths[0] let sinceViewHeight: CGFloat = 40 sinceBackV.frame = CGRect(x: 0, y: 0, w: ScreenSize.width, h: sinceViewHeight) sinceLabel.frame = CGRect(x: 0, y: 0, w: firColoumWidth, h: sinceBackV.height) let separateH: CGFloat = 1 separateLine.frame = CGRect(x: 0, y: sinceBackV.bottom, w: sinceBackV.width, h: separateH) let btnW = (sinceBackV.width-firColoumWidth)/CGFloat(sinceArr.count) for (index, sinceTimeBtn) in sinceButtons.enumerated() { let x = btnW*CGFloat(index)+sinceLabel.right sinceTimeBtn.frame = CGRect(x: x, y: 0, w: btnW, h: sinceBackV.height) } let bottomHeight: CGFloat = 10 let tableHeight = self.height-40-bottomHeight let tableY = separateLine.bottom for (index, tableView) in tableviews.enumerated() { let width = rowWidths[index] if index == 0 { tableView.frame = CGRect(x: 0, y: tableY, width: width, height: tableHeight) tableView.backgroundColor = UIColor.bfViewBackgroundColor } else { let lastTableview = tableviews[index-1] tableView.frame = CGRect(x: lastTableview.right, y: tableY, width: width, height: tableHeight) tableView.backgroundColor = UIColor.white } } bottomView.frame = CGRect(x: 0, y: firTableView!.bottom, width: width, height: bottomHeight) } // MARK: - Reload /// 重新加载所有数据 func resetAllColoumnsData() { mutipleSectionData.removeAll() mutipleSectionIndex.removeAll() //开始处理N组数据,将其索引化 for typeData in filterData { //每个类型下的数据,比如language下的数据 var typeArr: [[String]] = [] var sectionIndexArr: [String] = [] for sectionIndex in indexArr { let sectionArr: [String] = typeData.filter({ $0.lowercased().hasPrefix(sectionIndex.lowercased()) }) if !sectionArr.isEmpty { typeArr.append(sectionArr) sectionIndexArr.append(sectionIndex) } } if !sectionIndexArr.isEmpty { mutipleSectionIndex.append(sectionIndexArr) } if !typeArr.isEmpty { mutipleSectionData.append(typeArr) } } if firTableView != nil { firTableView!.reloadData() } if secTableView != nil { secTableView!.reloadData() } } /// 重置类型表格之外的所有数据 /// /// - Parameter selindex: <#selindex description#> func resetOtherColoumnsData(_ selindex: Int) { secTableView!.reloadData() } /// 重置所有属性 func resetProperty() { selTypeIndex = 0 selSecValueRowIndex = 0 selSecValueSectionIndex = 0 } // MARK: - Action @objc func tapSinceButton(sender: UIButton) { for button in sinceButtons { button.isSelected = sender == button } if let since = sender.currentTitle?.enLocalized { filterDelegate?.didTapSinceTime(since: since) } } } extension CPFilterTableView:UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { if mutipleSectionData.isEmpty { return 1 } if tableView == firTableView { return 1 } else { if !mutipleSectionData.isBeyond(index: selTypeIndex) { let typeData = mutipleSectionData[selTypeIndex] return typeData.count } } return 1 } func sectionIndexTitles(for tableView: UITableView) -> [String]? { if mutipleSectionData.isEmpty { return nil } if tableView == firTableView { return nil } else { if !mutipleSectionIndex.isBeyond(index: selTypeIndex) { let indexData = mutipleSectionIndex[selTypeIndex] return indexData } } return nil } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if filterTypes.isEmpty { return 0 } if mutipleSectionData.isEmpty { return 0 } if tableView == firTableView { return filterTypes.count } else { if !mutipleSectionData.isBeyond(index: selTypeIndex) { let typeData = mutipleSectionData[selTypeIndex] let sectionData = typeData[section] return sectionData.count } return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cellText = "" let section = indexPath.section let row = indexPath.row if tableView == firTableView { cellText = filterTypes[row] } else { let typeData = mutipleSectionData[selTypeIndex] let sectionData = typeData[section] if !sectionData.isBeyond(index: row) { cellText = sectionData[row] } } let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) cell.textLabel?.textColor = UIColor.iOS11Black if tableView == firTableView { cell.backgroundColor = UIColor.bfViewBackgroundColor cell.textLabel!.font = UIFont.bfSystemFont(ofSize: 14.0) cell.textLabel!.adjustFontSizeToFitWidth(minScale: 0.5) cell.addBorderSingle(UIColor.bfLineBackgroundColor, width: 0.5, at: .bottom) cell.addBorderSingle(UIColor.bfLineBackgroundColor, width: 0.5, at: .right) if indexPath.row == selTypeIndex { cell.backgroundColor = UIColor.white cell.removeBorder(.right) cell.textLabel?.textColor = UIColor.black } } else { cell.textLabel!.font = UIFont.bfSystemFont(ofSize: 12.0) cell.textLabel!.adjustFontSizeToFitWidth(minScale: 0.5) cell.selectionStyle = .none let selValueIndex = selSecValueRowIndex if row == selValueIndex && section == selSecValueSectionIndex { cell.textLabel?.textColor = UIColor.bfRedColor } } //所有数据从Plist读取的时候,已经经过本地化了 cell.textLabel!.text = cellText return cell } } extension CPFilterTableView:UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if tableView == firTableView { return rowHeights[0] } return rowHeights[1] } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let section = indexPath.section let row = indexPath.row if tableView == firTableView { selTypeIndex = row } else { selSecValueSectionIndex = section selSecValueRowIndex = row } let indexOfTableviews = (tableView == firTableView) ? 0:1 /// 其中的数据在传进来时,已经本地化 let type = filterTypes[selTypeIndex].enLocalized //其中的数据从plist中读取已经本地化 let typeData = mutipleSectionData[selTypeIndex] let sectionData = typeData[section] if !sectionData.isBeyond(index: row) { let value = (sectionData[selSecValueRowIndex]).enLocalized resetAllColoumnsData() if filterDelegate != nil { if indexOfTableviews == 0 { filterDelegate?.didSelectTypeColoumn(indexPath.row, type: type) } else if indexOfTableviews == 1 { filterDelegate?.didSelectValueColoumn(indexPath.row, type: type, value: value) } } } } func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { return index } }
mit
1ae43c4219ec7b80aada5dd5552d8bc4
29.944828
199
0.581532
4.502007
false
false
false
false
taqun/HBR
HBR/Classes/ViewController/Base/BaseItemListTableViewController.swift
1
2934
// // BaseItemListTableViewController.swift // HBR // // Created by taqun on 2014/10/17. // Copyright (c) 2014年 envoixapp. All rights reserved. // import UIKit class BaseItemListTableViewController: SegmentedDisplayTableViewController { var feedTitle: String! /* * Initialize */ override func viewDidLoad() { super.viewDidLoad() // navigation bar let backBtn = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: self, action: nil) self.navigationItem.backBarButtonItem = backBtn // tableview self.clearsSelectionOnViewWillAppear = true self.tableView.separatorInset = UIEdgeInsetsZero self.tableView.registerNib(UINib(nibName: "HBRFeedTableViewCell", bundle: nil), forCellReuseIdentifier: "FeedCell") self.refreshControl = UIRefreshControl() self.refreshControl?.addTarget(self, action: Selector("didRefreshControlChanged"), forControlEvents: UIControlEvents.ValueChanged) } /* * Private Method */ @objc private func didRefreshControlChanged() { FeedController.sharedInstance.loadFeeds() let delay = 0.5 * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(time, dispatch_get_main_queue()) { () -> Void in refreshControl?.endRefreshing() } } @objc internal func feedLoaded(notification: NSNotification) { println("HBRBaseItemListTableViewController#feedLoaded is called. This method should be override.") } internal func updateTitle() { let unreadCount = ModelManager.sharedInstance.allUnreadItemCount if unreadCount == 0 { self.title = feedTitle } else { self.title = feedTitle + " (" + String(unreadCount) + ")" } } /* * UIViewController Method */ override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // navigationbar self.updateTitle() // toolbar self.navigationController?.toolbarHidden = true NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("feedLoaded:"), name: Notification.FEED_LOADED, object: nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } /* * UITableViewDataSoruce Protocol */ override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } /* * UITableViewDelegate Protocol */ override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 80 } }
mit
0991749391b6cc55042071e25859996b
28.029703
142
0.632674
5.389706
false
false
false
false
loretoparisi/ios-json-benchmark
JSONlibs/ObjectMapper/Core/BasicTypes.swift
1
8943
// // BasicTypes.swift // ObjectMapper // // Created by Tristan Himmelman on 2015-02-17. // // The MIT License (MIT) // // Copyright (c) 2014-2015 Hearst // // 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. class BasicTypes: Mappable { var bool: Bool = true var boolOptional: Bool? var boolImplicityUnwrapped: Bool! var int: Int = 0 var intOptional: Int? var intImplicityUnwrapped: Int! var double: Double = 1.1 var doubleOptional: Double? var doubleImplicityUnwrapped: Double! var float: Float = 1.11 var floatOptional: Float? var floatImplicityUnwrapped: Float! var string: String = "" var stringOptional: String? var stringImplicityUnwrapped: String! var anyObject: AnyObject = true var anyObjectOptional: AnyObject? var anyObjectImplicitlyUnwrapped: AnyObject! var arrayBool: Array<Bool> = [] var arrayBoolOptional: Array<Bool>? var arrayBoolImplicityUnwrapped: Array<Bool>! var arrayInt: Array<Int> = [] var arrayIntOptional: Array<Int>? var arrayIntImplicityUnwrapped: Array<Int>! var arrayDouble: Array<Double> = [] var arrayDoubleOptional: Array<Double>? var arrayDoubleImplicityUnwrapped: Array<Double>! var arrayFloat: Array<Float> = [] var arrayFloatOptional: Array<Float>? var arrayFloatImplicityUnwrapped: Array<Float>! var arrayString: Array<String> = [] var arrayStringOptional: Array<String>? var arrayStringImplicityUnwrapped: Array<String>! var arrayAnyObject: Array<AnyObject> = [] var arrayAnyObjectOptional: Array<AnyObject>? var arrayAnyObjectImplicitlyUnwrapped: Array<AnyObject>! var dictBool: Dictionary<String,Bool> = [:] var dictBoolOptional: Dictionary<String, Bool>? var dictBoolImplicityUnwrapped: Dictionary<String, Bool>! var dictInt: Dictionary<String,Int> = [:] var dictIntOptional: Dictionary<String,Int>? var dictIntImplicityUnwrapped: Dictionary<String,Int>! var dictDouble: Dictionary<String,Double> = [:] var dictDoubleOptional: Dictionary<String,Double>? var dictDoubleImplicityUnwrapped: Dictionary<String,Double>! var dictFloat: Dictionary<String,Float> = [:] var dictFloatOptional: Dictionary<String,Float>? var dictFloatImplicityUnwrapped: Dictionary<String,Float>! var dictString: Dictionary<String,String> = [:] var dictStringOptional: Dictionary<String,String>? var dictStringImplicityUnwrapped: Dictionary<String,String>! var dictAnyObject: Dictionary<String, AnyObject> = [:] var dictAnyObjectOptional: Dictionary<String, AnyObject>? var dictAnyObjectImplicitlyUnwrapped: Dictionary<String, AnyObject>! enum EnumInt: Int { case Default case Another } var enumInt: EnumInt = .Default var enumIntOptional: EnumInt? var enumIntImplicitlyUnwrapped: EnumInt! enum EnumDouble: Double { case Default case Another } var enumDouble: EnumDouble = .Default var enumDoubleOptional: EnumDouble? var enumDoubleImplicitlyUnwrapped: EnumDouble! enum EnumFloat: Float { case Default case Another } var enumFloat: EnumFloat = .Default var enumFloatOptional: EnumFloat? var enumFloatImplicitlyUnwrapped: EnumFloat! enum EnumString: String { case Default = "Default" case Another = "Another" } var enumString: EnumString = .Default var enumStringOptional: EnumString? var enumStringImplicitlyUnwrapped: EnumString! var arrayEnumInt: [EnumInt] = [] var arrayEnumIntOptional: [EnumInt]? var arrayEnumIntImplicitlyUnwrapped: [EnumInt]! var dictEnumInt: [String: EnumInt] = [:] var dictEnumIntOptional: [String: EnumInt]? var dictEnumIntImplicitlyUnwrapped: [String: EnumInt]! init(){ } required init?(_ map: Map){ } func mapping(map: Map) { bool <- map["bool"] boolOptional <- map["boolOpt"] boolImplicityUnwrapped <- map["boolImp"] int <- map["int"] intOptional <- map["intOpt"] intImplicityUnwrapped <- map["intImp"] double <- map["double"] doubleOptional <- map["doubleOpt"] doubleImplicityUnwrapped <- map["doubleImp"] float <- map["float"] floatOptional <- map["floatOpt"] floatImplicityUnwrapped <- map["floatImp"] string <- map["string"] stringOptional <- map["stringOpt"] stringImplicityUnwrapped <- map["stringImp"] anyObject <- map["anyObject"] anyObjectOptional <- map["anyObjectOpt"] anyObjectImplicitlyUnwrapped <- map["anyObjectImp"] arrayBool <- map["arrayBool"] arrayBoolOptional <- map["arrayBoolOpt"] arrayBoolImplicityUnwrapped <- map["arrayBoolImp"] arrayInt <- map["arrayInt"] arrayIntOptional <- map["arrayIntOpt"] arrayIntImplicityUnwrapped <- map["arrayIntImp"] arrayDouble <- map["arrayDouble"] arrayDoubleOptional <- map["arrayDoubleOpt"] arrayDoubleImplicityUnwrapped <- map["arrayDoubleImp"] arrayFloat <- map["arrayFloat"] arrayFloatOptional <- map["arrayFloatOpt"] arrayFloatImplicityUnwrapped <- map["arrayFloatImp"] arrayString <- map["arrayString"] arrayStringOptional <- map["arrayStringOpt"] arrayStringImplicityUnwrapped <- map["arrayStringImp"] arrayAnyObject <- map["arrayAnyObject"] arrayAnyObjectOptional <- map["arrayAnyObjectOpt"] arrayAnyObjectImplicitlyUnwrapped <- map["arratAnyObjectImp"] dictBool <- map["dictBool"] dictBoolOptional <- map["dictBoolOpt"] dictBoolImplicityUnwrapped <- map["dictBoolImp"] dictInt <- map["dictInt"] dictIntOptional <- map["dictIntOpt"] dictIntImplicityUnwrapped <- map["dictIntImp"] dictDouble <- map["dictDouble"] dictDoubleOptional <- map["dictDoubleOpt"] dictDoubleImplicityUnwrapped <- map["dictDoubleImp"] dictFloat <- map["dictFloat"] dictFloatOptional <- map["dictFloatOpt"] dictFloatImplicityUnwrapped <- map["dictFloatImp"] dictString <- map["dictString"] dictStringOptional <- map["dictStringOpt"] dictStringImplicityUnwrapped <- map["dictStringImp"] dictAnyObject <- map["dictAnyObject"] dictAnyObjectOptional <- map["dictAnyObjectOpt"] dictAnyObjectImplicitlyUnwrapped <- map["dictAnyObjectImp"] enumInt <- map["enumInt"] enumIntOptional <- map["enumIntOpt"] enumIntImplicitlyUnwrapped <- map["enumIntImp"] enumDouble <- map["enumDouble"] enumDoubleOptional <- map["enumDoubleOpt"] enumDoubleImplicitlyUnwrapped <- map["enumDoubleImp"] enumFloat <- map["enumFloat"] enumFloatOptional <- map["enumFloatOpt"] enumFloatImplicitlyUnwrapped <- map["enumFloatImp"] enumString <- map["enumString"] enumStringOptional <- map["enumStringOpt"] enumStringImplicitlyUnwrapped <- map["enumStringImp"] arrayEnumInt <- map["arrayEnumInt"] arrayEnumIntOptional <- map["arrayEnumIntOpt"] arrayEnumIntImplicitlyUnwrapped <- map["arrayEnumIntImp"] dictEnumInt <- map["dictEnumInt"] dictEnumIntOptional <- map["dictEnumIntOpt"] dictEnumIntImplicitlyUnwrapped <- map["dictEnumIntImp"] } } class TestCollectionOfPrimitives : Mappable { var dictStringString: [String: String] = [:] var dictStringInt: [String: Int] = [:] var dictStringBool: [String: Bool] = [:] var dictStringDouble: [String: Double] = [:] var dictStringFloat: [String: Float] = [:] var arrayString: [String] = [] var arrayInt: [Int] = [] var arrayBool: [Bool] = [] var arrayDouble: [Double] = [] var arrayFloat: [Float] = [] init(){ } required init?(_ map: Map){ } func mapping(map: Map) { dictStringString <- map["dictStringString"] dictStringBool <- map["dictStringBool"] dictStringInt <- map["dictStringInt"] dictStringDouble <- map["dictStringDouble"] dictStringFloat <- map["dictStringFloat"] arrayString <- map["arrayString"] arrayInt <- map["arrayInt"] arrayBool <- map["arrayBool"] arrayDouble <- map["arrayDouble"] arrayFloat <- map["arrayFloat"] } }
mit
e978c1324f310886dd77c8097b366eed
34.919679
81
0.713854
3.864736
false
false
false
false
modocache/FutureKit
FutureKit/SyncWaitHandler.swift
3
2507
// // SyncFuture.swift // FutureKit // // Created by Michael Gray on 4/12/15. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public func warnOperationOnMainThread() { NSLog("Warning: A long-running Future wait operation is being executed on the main thread. \n Break on FutureKit.warnOperationOnMainThread() to debug.") } class SyncWaitHandler<T> { private var condition : NSCondition = NSCondition() private var completion : Completion<T>? init (waitingOnFuture f: Future<T>) { f.onComplete { (c) -> Void in self.condition.lock() self.completion = c self.condition.broadcast() self.condition.unlock() } } final func waitUntilCompleted(doMainQWarning : Bool = true) -> Completion<T> { self.condition.lock() if (doMainQWarning && NSThread.isMainThread()) { if (self.completion == nil) { warnOperationOnMainThread() } } while (self.completion == nil) { self.condition.wait() } self.condition.unlock() return self.completion! } } /* extension Future { public func waitUntilCompleted() -> Completion<T> { let s = FutureWaitHandler<T>(waitingOnFuture: self) return s.waitUntilCompleted() } public func waitForResult() -> T? { return self.waitUntilCompleted().result } } */
mit
64c24343be1139cd39caee4c66095af7
32.878378
156
0.66773
4.533454
false
false
false
false
montlebalm/Async
AsyncTests/FilterSeriesTests.swift
1
672
import XCTest class FilterSeriesTests: XCTestCase { func testPreservesOrder() { func isEven(num: Int, callback: (Bool) -> ()) { callback(num % 2 == 0) } Async.filterSeries([1, 2, 3, 4], iterator: isEven) { results in XCTAssertEqual(results, [2, 4]) } } func testRunsInSeries() { var completedOrder: [String] = [] func throttle(text: String, callback: (Bool) -> ()) { if text == "slow" { delay(100) } completedOrder.append(text) callback(true) } Async.filterSeries(["slow", "fast"], iterator: throttle) { results in XCTAssertEqual(completedOrder, ["slow", "fast"]) } } }
mit
2ac97c88aa26d418ab410661c63be57c
20
73
0.581845
3.692308
false
true
false
false
AlexeyTyurenkov/NBUStats
NBUStatProject/NBUStat/Modules/PrivatModule/PrivateCurrencyViewController.swift
1
2376
// // PrivateCurrencyViewController.swift // FinStat Ukraine // // Created by Aleksey Tyurenkov on 3/11/18. // Copyright © 2018 Oleksii Tiurenkov. All rights reserved. // import UIKit protocol PrivateCurrencyRatesViewInput: class { } class PrivateCurrencyViewController: BaseViewController,PrivateCurrencyRatesViewInput, PresenterViewDelegate { private var privateController: PrivateInternalTableViewController? func presenter(_ presenter: PresenterProtocol, updateAsProfessional: Bool) { if let privateController = privateController { configure(privateController: privateController) } view.sendSubview(toBack: activityView) activityView.isHidden = true } func presenter(_: PresenterProtocol, getError: Error) { } func presenterCancelSearch(_: PresenterProtocol) { } func presenterWillLoad(_: PresenterProtocol) { activityView.isHidden = false refreshController?.animation{ return !self.activityView.isHidden } } func presenterDidLoad(_: PresenterProtocol) { } @IBOutlet weak var activityView: UIView! @IBOutlet weak var containerView: UIView! weak var output: PrivateCurrencyRatesViewOutput? var presenter: PrivateCurrencyRatesPresenter! @IBOutlet weak var segmentController: UISegmentedControl! weak var refreshController:RefreshController? override func viewDidLoad() { super.viewDidLoad() let refresh = RefreshController.defaultRefresh(frame: activityView.bounds) refreshController = refresh activityView.addSubview(refresh) presenter.viewLoaded() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func dataproviderTapped(_ sender: Any) { presenter.showDataProviderInfo() } @IBAction func indexChanged(_ sender: UISegmentedControl) { presenter.load(index: sender.selectedSegmentIndex) } override func configure(privateController: PrivateInternalTableViewController) { self.privateController = privateController self.privateController?.configure(with: presenter) self.privateController?.tableView.reloadData() } }
mit
cbfcaf1fb61e215492ec3cfb4ad9a947
27.963415
110
0.697684
5.361174
false
false
false
false
andersio/ReactiveCocoa
ReactiveCocoaTests/Swift/FlattenSpec.swift
1
23807
// // FlattenSpec.swift // ReactiveCocoa // // Created by Oleg Shnitko on 1/22/16. // Copyright © 2016 GitHub. All rights reserved. // import Result import Nimble import Quick import ReactiveCocoa private extension SignalType { typealias Pipe = (signal: Signal<Value, Error>, observer: Observer<Value, Error>) } private typealias Pipe = Signal<SignalProducer<Int, TestError>, TestError>.Pipe class FlattenSpec: QuickSpec { override func spec() { func describeSignalFlattenDisposal(flattenStrategy: FlattenStrategy, name: String) { describe(name) { var pipe: Pipe! var disposable: Disposable? beforeEach { pipe = Signal.pipe() disposable = pipe.signal .flatten(flattenStrategy) .observe { _ in } } afterEach { disposable?.dispose() } context("disposal") { var disposed = false beforeEach { disposed = false pipe.observer.sendNext(SignalProducer<Int, TestError> { _, disposable in disposable += ActionDisposable { disposed = true } }) } it("should dispose inner signals when outer signal interrupted") { pipe.observer.sendInterrupted() expect(disposed) == true } it("should dispose inner signals when outer signal failed") { pipe.observer.sendFailed(.Default) expect(disposed) == true } it("should not dispose inner signals when outer signal completed") { pipe.observer.sendCompleted() expect(disposed) == false } } } } context("Signal") { describeSignalFlattenDisposal(.Latest, name: "switchToLatest") describeSignalFlattenDisposal(.Merge, name: "merge") describeSignalFlattenDisposal(.Concat, name: "concat") } func describeSignalProducerFlattenDisposal(flattenStrategy: FlattenStrategy, name: String) { describe(name) { it("disposes original signal when result signal interrupted") { var disposed = false let disposable = SignalProducer<SignalProducer<(), NoError>, NoError> { _, disposable in disposable += ActionDisposable { disposed = true } } .flatten(flattenStrategy) .start() disposable.dispose() expect(disposed) == true } } } context("SignalProducer") { describeSignalProducerFlattenDisposal(.Latest, name: "switchToLatest") describeSignalProducerFlattenDisposal(.Merge, name: "merge") describeSignalProducerFlattenDisposal(.Concat, name: "concat") } describe("Signal.flatten()") { it("works with TestError and a TestError Signal") { typealias Inner = Signal<Int, TestError> typealias Outer = Signal<Inner, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .observeNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a TestError Signal") { typealias Inner = Signal<Int, TestError> typealias Outer = Signal<Inner, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .observeNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a NoError Signal") { typealias Inner = Signal<Int, NoError> typealias Outer = Signal<Inner, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .observeNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a NoError Signal") { typealias Inner = Signal<Int, NoError> typealias Outer = Signal<Inner, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .observeNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a TestError SignalProducer") { typealias Inner = SignalProducer<Int, TestError> typealias Outer = Signal<Inner, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .observeNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a TestError SignalProducer") { typealias Inner = SignalProducer<Int, TestError> typealias Outer = Signal<Inner, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .observeNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a NoError SignalProducer") { typealias Inner = SignalProducer<Int, NoError> typealias Outer = Signal<Inner, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .observeNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a NoError SignalProducer") { typealias Inner = SignalProducer<Int, NoError> typealias Outer = Signal<Inner, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .observeNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with SequenceType as a value") { let (signal, innerObserver) = Signal<[Int], NoError>.pipe() let sequence = [1, 2, 3] var observedValues = [Int]() signal .flatten(.Concat) .observeNext { value in observedValues.append(value) } innerObserver.sendNext(sequence) expect(observedValues) == sequence } } describe("SignalProducer.flatten()") { it("works with TestError and a TestError Signal") { typealias Inner = Signal<Int, TestError> typealias Outer = SignalProducer<Inner, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .startWithNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a TestError Signal") { typealias Inner = Signal<Int, TestError> typealias Outer = SignalProducer<Inner, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .startWithNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a NoError Signal") { typealias Inner = Signal<Int, NoError> typealias Outer = SignalProducer<Inner, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .startWithNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a NoError Signal") { typealias Inner = Signal<Int, NoError> typealias Outer = SignalProducer<Inner, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .startWithNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a TestError SignalProducer") { typealias Inner = SignalProducer<Int, TestError> typealias Outer = SignalProducer<Inner, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .startWithNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a TestError SignalProducer") { typealias Inner = SignalProducer<Int, TestError> typealias Outer = SignalProducer<Inner, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .startWithNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a NoError SignalProducer") { typealias Inner = SignalProducer<Int, NoError> typealias Outer = SignalProducer<Inner, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .startWithNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a NoError SignalProducer") { typealias Inner = SignalProducer<Int, NoError> typealias Outer = SignalProducer<Inner, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatten(.Latest) .startWithNext { value in observed = value } outerObserver.sendNext(inner) innerObserver.sendNext(4) expect(observed) == 4 } it("works with SequenceType as a value") { let sequence = [1, 2, 3] var observedValues = [Int]() let producer = SignalProducer<[Int], NoError>(value: sequence) producer .flatten(.Latest) .startWithNext { value in observedValues.append(value) } expect(observedValues) == sequence } } describe("Signal.flatMap()") { it("works with TestError and a TestError Signal") { typealias Inner = Signal<Int, TestError> typealias Outer = Signal<Int, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .observeNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a TestError Signal") { typealias Inner = Signal<Int, TestError> typealias Outer = Signal<Int, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .observeNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a NoError Signal") { typealias Inner = Signal<Int, NoError> typealias Outer = Signal<Int, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .observeNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a NoError Signal") { typealias Inner = Signal<Int, NoError> typealias Outer = Signal<Int, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .observeNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a TestError SignalProducer") { typealias Inner = SignalProducer<Int, TestError> typealias Outer = Signal<Int, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .observeNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a TestError SignalProducer") { typealias Inner = SignalProducer<Int, TestError> typealias Outer = Signal<Int, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .observeNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a NoError SignalProducer") { typealias Inner = SignalProducer<Int, NoError> typealias Outer = Signal<Int, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .observeNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a NoError SignalProducer") { typealias Inner = SignalProducer<Int, NoError> typealias Outer = Signal<Int, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .observeNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } } describe("SignalProducer.flatMap()") { it("works with TestError and a TestError Signal") { typealias Inner = Signal<Int, TestError> typealias Outer = SignalProducer<Int, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .startWithNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a TestError Signal") { typealias Inner = Signal<Int, TestError> typealias Outer = SignalProducer<Int, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .startWithNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a NoError Signal") { typealias Inner = Signal<Int, NoError> typealias Outer = SignalProducer<Int, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .startWithNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a NoError Signal") { typealias Inner = Signal<Int, NoError> typealias Outer = SignalProducer<Int, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .startWithNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a TestError SignalProducer") { typealias Inner = SignalProducer<Int, TestError> typealias Outer = SignalProducer<Int, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .startWithNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a TestError SignalProducer") { typealias Inner = SignalProducer<Int, TestError> typealias Outer = SignalProducer<Int, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .startWithNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with NoError and a NoError SignalProducer") { typealias Inner = SignalProducer<Int, NoError> typealias Outer = SignalProducer<Int, NoError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .startWithNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } it("works with TestError and a NoError SignalProducer") { typealias Inner = SignalProducer<Int, NoError> typealias Outer = SignalProducer<Int, TestError> let (inner, innerObserver) = Inner.pipe() let (outer, outerObserver) = Outer.pipe() var observed: Int? = nil outer .flatMap(.Latest) { _ in inner } .startWithNext { value in observed = value } outerObserver.sendNext(4) innerObserver.sendNext(4) expect(observed) == 4 } } describe("Signal.merge()") { it("should emit values from all signals") { let (signal1, observer1) = Signal<Int, NoError>.pipe() let (signal2, observer2) = Signal<Int, NoError>.pipe() let mergedSignals = Signal.merge([signal1, signal2]) var lastValue: Int? mergedSignals.observeNext { lastValue = $0 } expect(lastValue).to(beNil()) observer1.sendNext(1) expect(lastValue) == 1 observer2.sendNext(2) expect(lastValue) == 2 observer1.sendNext(3) expect(lastValue) == 3 } it("should not stop when one signal completes") { let (signal1, observer1) = Signal<Int, NoError>.pipe() let (signal2, observer2) = Signal<Int, NoError>.pipe() let mergedSignals = Signal.merge([signal1, signal2]) var lastValue: Int? mergedSignals.observeNext { lastValue = $0 } expect(lastValue).to(beNil()) observer1.sendNext(1) expect(lastValue) == 1 observer1.sendCompleted() expect(lastValue) == 1 observer2.sendNext(2) expect(lastValue) == 2 } it("should complete when all signals complete") { let (signal1, observer1) = Signal<Int, NoError>.pipe() let (signal2, observer2) = Signal<Int, NoError>.pipe() let mergedSignals = Signal.merge([signal1, signal2]) var completed = false mergedSignals.observeCompleted { completed = true } expect(completed) == false observer1.sendNext(1) expect(completed) == false observer1.sendCompleted() expect(completed) == false observer2.sendCompleted() expect(completed) == true } } describe("SignalProducer.merge()") { it("should emit values from all producers") { let (signal1, observer1) = SignalProducer<Int, NoError>.pipe() let (signal2, observer2) = SignalProducer<Int, NoError>.pipe() let mergedSignals = SignalProducer.merge([signal1, signal2]) var lastValue: Int? mergedSignals.startWithNext { lastValue = $0 } expect(lastValue).to(beNil()) observer1.sendNext(1) expect(lastValue) == 1 observer2.sendNext(2) expect(lastValue) == 2 observer1.sendNext(3) expect(lastValue) == 3 } it("should not stop when one producer completes") { let (signal1, observer1) = SignalProducer<Int, NoError>.pipe() let (signal2, observer2) = SignalProducer<Int, NoError>.pipe() let mergedSignals = SignalProducer.merge([signal1, signal2]) var lastValue: Int? mergedSignals.startWithNext { lastValue = $0 } expect(lastValue).to(beNil()) observer1.sendNext(1) expect(lastValue) == 1 observer1.sendCompleted() expect(lastValue) == 1 observer2.sendNext(2) expect(lastValue) == 2 } it("should complete when all producers complete") { let (signal1, observer1) = SignalProducer<Int, NoError>.pipe() let (signal2, observer2) = SignalProducer<Int, NoError>.pipe() let mergedSignals = SignalProducer.merge([signal1, signal2]) var completed = false mergedSignals.startWithCompleted { completed = true } expect(completed) == false observer1.sendNext(1) expect(completed) == false observer1.sendCompleted() expect(completed) == false observer2.sendCompleted() expect(completed) == true } } describe("SignalProducer.prefix()") { it("should emit initial value") { let (signal, observer) = SignalProducer<Int, NoError>.pipe() let mergedSignals = signal.prefix(value: 0) var lastValue: Int? mergedSignals.startWithNext { lastValue = $0 } expect(lastValue) == 0 observer.sendNext(1) expect(lastValue) == 1 observer.sendNext(2) expect(lastValue) == 2 observer.sendNext(3) expect(lastValue) == 3 } it("should emit initial value") { let (signal, observer) = SignalProducer<Int, NoError>.pipe() let mergedSignals = signal.prefix(SignalProducer(value: 0)) var lastValue: Int? mergedSignals.startWithNext { lastValue = $0 } expect(lastValue) == 0 observer.sendNext(1) expect(lastValue) == 1 observer.sendNext(2) expect(lastValue) == 2 observer.sendNext(3) expect(lastValue) == 3 } } describe("SignalProducer.concat(value:)") { it("should emit final value") { let (signal, observer) = SignalProducer<Int, NoError>.pipe() let mergedSignals = signal.concat(value: 4) var lastValue: Int? mergedSignals.startWithNext { lastValue = $0 } observer.sendNext(1) expect(lastValue) == 1 observer.sendNext(2) expect(lastValue) == 2 observer.sendNext(3) expect(lastValue) == 3 observer.sendCompleted() expect(lastValue) == 4 } } } }
mit
d8edc8069e3d3d020cbeb001b193d33c
24.352503
94
0.628875
3.868378
false
true
false
false
Chaosspeeder/YourGoals
YourGoals/Business/WatchConnectivity/PieProgressPainter.swift
1
3718
// // PieProgressPainter.swift // YourGoals // // Created by André Claaßen on 03.04.18. // Copyright © 2018 André Claaßen. All rights reserved. // import Foundation import WatchKit class PieProgressPainter { let chartSize = CGSize(width: 312, height: 200) let bounds:CGRect! init() { self.bounds = CGRect(x: 0, y: 0, width: chartSize.width, height: chartSize.height) } // This needs to have a setter/getter for it to work with CoreAnimation, therefore NSManaged var thicknessRatio: CGFloat = 0.1 var progressTintColor = UIColor.blue var trackTintColor = UIColor.blue var fillColor = UIColor.blue.withAlphaComponent(0.3) var clockwise = true func fillProgressIfNecessary(ctx: CGContext, progress:CGFloat, centerPoint:CGPoint, radius:CGFloat, radians:CGFloat) { guard progress >= 0.0 else { return } ctx.setFillColor(progressTintColor.cgColor) let progressPath = CGMutablePath() progressPath.move(to: centerPoint) let topAngle = CGFloat(3 * (Double.pi / 2)) if clockwise { progressPath.addArc(center: centerPoint, radius: radius, startAngle: topAngle, endAngle: radians, clockwise: false ) } else { progressPath.addArc(center: centerPoint, radius: radius, startAngle: radians, endAngle: topAngle, clockwise: true) } progressPath.closeSubpath() ctx.addPath(progressPath) ctx.fillPath() } func fillBackgroundCircle(ctx:CGContext, centerPoint:CGPoint, radius:CGFloat) { let rect = CGRect(x: centerPoint.x - radius, y: centerPoint.y - radius, width: radius * 2, height: radius * 2) ctx.setFillColor(self.fillColor.cgColor) ctx.fillEllipse(in: rect) } func fillOuterCircle(ctx:CGContext, centerPoint:CGPoint, radius:CGFloat) { let lineWidth = thicknessRatio * radius let rect = CGRect(x: centerPoint.x - radius, y: centerPoint.y - radius, width: radius * 2, height: radius * 2).insetBy(dx: lineWidth / 2.0, dy: lineWidth / 2.0 ) ctx.setStrokeColor(trackTintColor.cgColor) ctx.setLineWidth(lineWidth) ctx.strokeEllipse(in: rect) } func draw(in ctx: CGContext, percentage:CGFloat) { let rect = self.bounds! let centerPoint = CGPoint(x: rect.size.width / 2, y: rect.size.height / 2) let radius = min(rect.size.height, rect.size.width) / 2 let progressRadius = radius * (1 - thicknessRatio * 2.0) let progress: CGFloat = min(percentage, CGFloat(1 - Float.ulpOfOne)) // clockwise progress let radians = clockwise ? CGFloat((Double(progress) * 2.0 * Double.pi) - (Double.pi / 2)) : CGFloat( 2.0 * Double.pi - (Double(progress) * 2.0 * Double.pi) - (Double.pi / 2.0)) fillProgressIfNecessary(ctx: ctx, progress: progress, centerPoint: centerPoint, radius: progressRadius, radians: radians) fillBackgroundCircle(ctx: ctx, centerPoint: centerPoint, radius: radius) fillOuterCircle(ctx: ctx, centerPoint: centerPoint, radius: radius) } func draw(percentage: CGFloat, tintColor: UIColor) -> UIImage? { self.progressTintColor = tintColor self.trackTintColor = tintColor self.fillColor = tintColor.withAlphaComponent(0.3) UIGraphicsBeginImageContext(chartSize) let context = UIGraphicsGetCurrentContext()! draw(in: context, percentage: percentage) let finalImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return finalImage } }
lgpl-3.0
2fd36f5d52845ecbc27d28990945be74
38.5
169
0.64934
4.409739
false
false
false
false
DevaLee/LYCSwiftDemo
LYCSwiftDemo/Classes/Component/HYPageView/HYPageCollectionFlowLayout.swift
1
2721
// // HYPageCollectionFlowLayout.swift // pageView扩展 // // Created by 李玉臣 on 2017/6/11. // Copyright © 2017年 yuchen.li. All rights reserved. // import UIKit class HYPageCollectionFlowLayout: UICollectionViewFlowLayout { var cols : Int = 1 var rows : Int = 1 fileprivate lazy var cellAttrs : [UICollectionViewLayoutAttributes] = [] fileprivate lazy var maxWidth : CGFloat = 0 } extension HYPageCollectionFlowLayout{ override func prepare() { let itemW = (collectionView!.bounds.size.width - sectionInset.left - sectionInset.right - minimumLineSpacing * CGFloat(cols - 1)) / CGFloat(cols) let itemH = (collectionView!.bounds.size.height - sectionInset.top - sectionInset.bottom - minimumInteritemSpacing * CGFloat(rows - 1)) / CGFloat(rows) // 一共有多少组 let sectionNum = collectionView!.numberOfSections // 前面一共有多少页 var prePageCount : Int = 0 for i in 0 ..< sectionNum { let itemCount = collectionView?.numberOfItems(inSection: i) for j in 0 ..< collectionView!.numberOfItems(inSection: i) { // 取出对应的indexPath let indexPath = IndexPath(item: j, section: i) // 根据IndexPath 创建 Attribute let layoutAttribute = UICollectionViewLayoutAttributes(forCellWith: indexPath) // 设置 layoutAttribute 的frame //计算 j 在该section 中第几页 在该页中的index let page = Int(j / (cols * rows) ) let index = Int( j % Int (cols * rows)) var itemY : CGFloat = 0 var itemX : CGFloat = 0 itemY = sectionInset.top + (itemH + minimumLineSpacing) * CGFloat((index / cols)) itemX = CGFloat(prePageCount + page) * collectionView!.bounds.width + sectionInset.left + (itemW + minimumInteritemSpacing) * CGFloat (index % cols) layoutAttribute.frame = CGRect(x: itemX, y: itemY, width: itemW, height: itemH) cellAttrs.append(layoutAttribute) } prePageCount += (itemCount! - 1) / (rows * cols) + 1 } self.maxWidth = CGFloat(prePageCount) * (collectionView?.bounds.width)! } } extension HYPageCollectionFlowLayout{ override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return cellAttrs } } extension HYPageCollectionFlowLayout{ override var collectionViewContentSize: CGSize{ return CGSize(width: self.maxWidth, height: 0) } }
mit
62b30be10feffd8f2a432022da45096c
35.027397
164
0.611787
4.790528
false
false
false
false
rsaenzi/MyMoviesListApp
MyMoviesListApp/MyMoviesListApp/AuthWireframe.swift
1
1237
// // AuthWireframe.swift // MyMoviesListApp // // Created by Rigoberto Sáenz Imbacuán on 5/29/17. // Copyright © 2017 Rigoberto Sáenz Imbacuán. All rights reserved. // import Foundation import SwiftKeychainWrapper class AuthWireframe { func goToLogin(_ window: UIWindow?, using presenter: AuthPresenter) { let view = UILoader.loadScene(from: AuthView.self) view.presenter = presenter window?.rootViewController = view window?.makeKeyAndVisible() } func goToMovies(_ window: UIWindow? = nil) { if let validWindow = window { showMovies(validWindow) return } if let validWindow = UIApplication.shared.windows.first { showMovies(validWindow) return } } fileprivate func showMovies(_ window: UIWindow) { let popularModule = PopularModule() let searchModule = SearchModule() let tabBar: MainTabBar = UILoader.loadScene(from: MainTabBar.self) tabBar.viewControllers = [popularModule.view, searchModule.view] window.rootViewController = tabBar window.makeKeyAndVisible() } }
mit
7739c77dcb222ec98df6d72c648bded0
25.212766
74
0.616883
4.987854
false
false
false
false
skedgo/tripkit-ios
Sources/TripKitUI/helper/RxTripKit/Rx+Concurrency.swift
1
3087
// // Rx+Concurrency.swift // TripKitUI-iOS // // Created by Adrian Schönig on 16/3/2022. // Copyright © 2022 SkedGo Pty Ltd. All rights reserved. // import RxSwift import RxCocoa extension ObservableType { public func asyncMap<T>( _ transform: @escaping (Element) async -> T ) -> Observable<T> { return flatMapLatest { (value: Element) -> Observable<T> in Single.create { subscriber in Task { let output = await transform(value) subscriber(.success(output)) } return Disposables.create() } .asObservable() } } public func asyncMap<T>( _ transform: @escaping (Element) async throws -> T ) -> Observable<T> { return flatMapLatest { (value: Element) -> Observable<T> in Single.create { subscriber in Task { do { let output = try await transform(value) subscriber(.success(output)) } catch { subscriber(.failure(error)) } } return Disposables.create() } .asObservable() } } } extension SharedSequenceConvertibleType { public func safeMap<T>( catchError: @escaping (Error) -> Void, _ transform: @escaping (Element) async throws -> T? ) -> SharedSequence<SharingStrategy, T> { return flatMapLatest { value -> SharedSequence<SharingStrategy, T?> in Observable.create { subscriber in Task { do { let output = try await transform(value) await MainActor.run { subscriber.onNext(output) subscriber.onCompleted() } } catch { await MainActor.run { catchError(error) subscriber.onCompleted() } } } return Disposables.create() } .subscribe(on: SharingStrategy.scheduler) .observe(on: SharingStrategy.scheduler) .asSharedSequence(sharingStrategy: SharingStrategy.self, onErrorRecover: { _ in return .empty() }) } .compactMap { $0 } } public func safeMap<T>( catchError: @escaping (Error) -> Void, _ transform: @escaping (Element) throws -> T? ) -> SharedSequence<SharingStrategy, T> { return compactMap { value in do { return try transform(value) } catch { catchError(error) return nil } } } } extension PrimitiveSequenceType where Trait == SingleTrait { public static func create(_ handler: @escaping () async -> Element) -> Single<Element> { create { subscriber in Task { subscriber(.success(await handler())) } return Disposables.create() } } public static func create(_ handler: @escaping () async throws -> Element) -> Single<Element> { create { subscriber in Task { do { subscriber(.success(try await handler())) } catch { subscriber(.failure(error)) } } return Disposables.create() } } }
apache-2.0
1c5d2aa7942353d7338ea9ff9bb545d3
24.708333
97
0.563047
4.709924
false
false
false
false
steve-holmes/music-app-2
MusicApp/Modules/Search/SearchStore.swift
1
776
// // SearchStore.swift // MusicApp // // Created by Hưng Đỗ on 7/11/17. // Copyright © 2017 HungDo. All rights reserved. // import RxSwift protocol SearchStore { var histories: Variable<[String]> { get } var info: Variable<SearchInfo> { get } var songs: Variable<[Song]> { get } var playlists: Variable<[Playlist]> { get } var videos: Variable<[Video]> { get } var state: Variable<SearchState> { get } } class MASearchStore: SearchStore { let histories = Variable<[String]>([]) let info = Variable<SearchInfo>(SearchInfo()) let songs = Variable<[Song]>([]) let playlists = Variable<[Playlist]>([]) let videos = Variable<[Video]>([]) let state = Variable<SearchState>(.all) }
mit
abcbb24c43083b018b45a5569f50d39b
21.028571
49
0.609598
3.974227
false
false
false
false
onekiloparsec/siesta
Source/Error.swift
2
7900
// // Error.swift // Siesta // // Created by Paul on 2015/6/26. // Copyright © 2016 Bust Out Solutions. All rights reserved. // import Foundation /** Information about a failed resource request. Siesta can encounter errors from many possible sources, including: - client-side encoding / request creation issues, - network connectivity problems, - protocol issues (e.g. certificate problems), - server errors (404, 500, etc.), and - client-side parsing and entity validation failures. `Error` presents all these errors in a uniform structure. Several properties preserve diagnostic information, which you can use to intercept specific known errors, but these diagnostic properties are all optional. They are not even mutually exclusive: Siesta errors do not break cleanly into HTTP-based vs. exception/NSError-based, for example, because network implementations may sometimes provide _both_ an underlying NSError _and_ an HTTP diagnostic. The one ironclad guarantee that `Error` makes is the presence of a `userMessage`. */ public struct Error: ErrorType { /** A description of this error suitable for showing to the user. Typically messages are brief and in plain language, e.g. “Not found,” “Invalid username or password,” or “The internet connection is offline.” */ public var userMessage: String /// The HTTP status code (e.g. 404) if this error came from an HTTP response. public var httpStatusCode: Int? /// The response body if this error came from an HTTP response. Its meaning is API-specific. public var entity: Entity? /// Details about the underlying error. Errors originating from Siesta will have a cause from `Error.Cause`. /// Errors originating from the `NetworkingProvider` or custom `ResponseTransformer`s have domain-specific causes. public var cause: ErrorType? /// The time at which the error occurred. public let timestamp: NSTimeInterval = now() /** Initializes the error using a network response. If the `userMessage` parameter is nil, this initializer uses `error` or the response’s status code to generate a user message. That failing, it gives a generic failure message. */ public init( response: NSHTTPURLResponse?, content: AnyObject?, cause: ErrorType?, userMessage: String? = nil) { self.httpStatusCode = response?.statusCode self.cause = cause if let content = content { self.entity = Entity(response: response, content: content) } if let message = userMessage { self.userMessage = message } else if let message = (cause as? NSError)?.localizedDescription { self.userMessage = message } else if let code = self.httpStatusCode { self.userMessage = NSHTTPURLResponse.localizedStringForStatusCode(code).capitalizedFirstCharacter } else { self.userMessage = NSLocalizedString("Request failed", comment: "userMessage") } // Is this reachable? } /** Initializes the error using an underlying error. */ public init( userMessage: String, cause: ErrorType, entity: Entity? = nil) { self.userMessage = userMessage self.cause = cause self.entity = entity } } public extension Error { /** Underlying causes of errors reported by Siesta. You will find these on the `Error.cause` property. (Note that `cause` may also contain errors from the underlying network library that do not appear here.) The primary purpose of these error causes is to aid debugging. Client code rarely needs to work with them, but they can be useful if you want to add special handling for specific errors. For example, if you’re working with an API that sometimes returns garbled text data that isn’t decodable, and you want to show users a placeholder message instead of an error, then (1) gee, that’s weird, and (2) you can turn that one specific error into a success by adding a transformer: configure { $0.config.responseTransformers.add(GarbledResponseHandler()) } ... struct GarbledResponseHandler: ResponseTransformer { func process(response: Response) -> Response { switch response { case .Success: return response case .Failure(let error): if error.cause is Siesta.Error.Cause.InvalidTextEncoding { return .Success(Entity( content: "Nothingness. Tumbleweeds. The Void.", contentType: "text/string")) } else { return response } } } } */ public struct Cause { private init() { fatalError("Siesta.Error.Cause is only a namespace") } // MARK: Request Errors /// Unable to create a text request with the requested character encoding. public struct UnencodableText: ErrorType { public let encodingName: String public let text: String } /// Unable to create a JSON request using an object that is not JSON-encodable. public struct InvalidJSONObject: ErrorType { } /// Unable to create a URL-encoded request, probably due to unpaired Unicode surrogate chars. public struct NotURLEncodable: ErrorType { public let offendingString: String } // MARK: Network Errors /// Underlying network request was cancelled before response arrived. public struct RequestCancelled: ErrorType { public let networkError: ErrorType? } // TODO: Consider explicitly detecting offline connection // MARK: Response Errors /// Server sent 304 (“not changed”), but we have no local data for the resource. public struct NoLocalDataFor304: ErrorType { } /// The server sent a text encoding name that the OS does not recognize. public struct InvalidTextEncoding: ErrorType { public let encodingName: String } /// The server’s response could not be decoded using the text encoding it specified. public struct UndecodableText: ErrorType { public let encodingName: String } /// Siesta’s default JSON parser accepts only dictionaries and arrays, but the server /// sent a response containing a bare JSON primitive. public struct JSONResponseIsNotDictionaryOrArray: ErrorType { public let actualType: String } /// The server’s response could not be parsed using any known image format. public struct UnparsableImage: ErrorType { } /// A response transformer received entity content of a type it doesn’t know how to process. This error means /// that the upstream transformations may have succeeded, but did not return a value of the type the next /// transformer expected. public struct WrongTypeInTranformerPipeline: ErrorType { public let expectedType, actualType: String // TODO: Does Swift allow something more inspectable than String? Any.Type & similar don't seem to work. public let transformer: ResponseTransformer } /// A `ResponseContentTransformer` or a closure passed to `Service.configureTransformer(...)` returned nil. public struct TransformerReturnedNil: ErrorType { public let transformer: ResponseTransformer } } }
mit
8ecb0f84d02b0bd6d4a4094a2ecfcf9e
37.748768
161
0.644292
5.29697
false
false
false
false
GitTennis/SuccessFramework
Templates/_BusinessAppSwift_/_BusinessAppSwift_/PartialViews/Buttons/ConnectionStatusButton.swift
2
4071
// // ConnectionStatusButton.swift // _BusinessAppSwift_ // // Created by Gytenis Mikulenas on 23/10/16. // Copyright © 2016 Gytenis Mikulėnas // https://github.com/GitTennis/SuccessFramework // // 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. All rights reserved. // import UIKit let kConnectionStatusLabelTag = 20141206 // Border let kConnectionStatusLabelBorderCornerRadius = 4.0 let kConnectionStatusLabelBorderWidth = 1.0 let kConnectionStatusLabelBorderColor = kColorGrayDark.cgColor // Text let kConnectionStatusLabelTextColor = kColorWhite let kConnectionStatusLabelBackgroundColor = kColorGrayDark let kConnectionStatusLabelTextFont = kFontNormal let kConnectionStatusLabelTextSize = 15.0 let kConnnectionStatusLabelMessageKey = "NoIternetMessage" let kConnectionStatusLabelPhoneNumber = "123456789" class ConnectionStatusButton: UIButton { override init (frame : CGRect) { super.init(frame : frame) self.commonInit() } convenience init () { self.init(frame:CGRect.zero) self.commonInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.commonInit() } func didPressed() { var error: ErrorEntity = ErrorEntity.init(code: nil, message: nil) let canExecute: Bool = (_phoneCallCommand?.canExecute(error: &error))! if (canExecute) { _phoneCallCommand?.executeWithCallback(callback: nil) } } // MARK: // MARK: Internal // MARK: internal var _phoneCallCommand: PhoneCallCommand? internal func commonInit() { // Add corner radius if defined if (kConnectionStatusLabelBorderCornerRadius > 0) { self.layer.cornerRadius = CGFloat(kConnectionStatusLabelBorderCornerRadius) self.layer.masksToBounds = true } // Add border if defined if (kConnectionStatusLabelBorderWidth > 0) { self.layer.borderColor = kConnectionStatusLabelBorderColor self.layer.borderWidth = CGFloat(kConnectionStatusLabelBorderWidth) } self.backgroundColor = kConnectionStatusLabelBackgroundColor; self.setTitle(localizedString(key: kConnnectionStatusLabelMessageKey), for:UIControlState.normal) self.titleLabel?.textColor = kConnectionStatusLabelTextColor; self.titleLabel?.font = UIFont(name: kConnectionStatusLabelTextFont, size: CGFloat(kConnectionStatusLabelTextSize)) self.titleLabel?.textAlignment = NSTextAlignment.center self.titleLabel?.numberOfLines = 0; self.tag = kConnectionStatusLabelTag; self.addTarget(self, action: #selector(ConnectionStatusButton.didPressed), for: UIControlEvents.touchUpInside) _phoneCallCommand = PhoneCallCommand.init(phoneNumber: kConnectionStatusLabelPhoneNumber) } }
mit
36ff392a01354b46695f028bd0e9bec0
33.777778
123
0.697223
4.873054
false
false
false
false
lucdion/aide-devoir
sources/AideDevoir/Classes/UI/EditDictation/Subviews/EditDictationTableCell.swift
1
3173
// // EditDictationTableCell.swift // AideDevoir // // Created by DION, Luc (MTL) on 2016-12-04. // Copyright © 2016 Mirego. All rights reserved. // import MGSwipeTableCell protocol EditDictationTableCellDelegate: class { func didSelectDelete(forCell cell: EditDictationTableCell) // func didTapEdit(forCell cell: EditDictationTableCell) } class EditDictationTableCell: MGSwipeTableCell { weak var cellDelegate: EditDictationTableCellDelegate? static let reuseIdentifier = "EditDictationTableCell" static let preferedHeight: CGFloat = 44 // private let checkmarkImageView = UIImageView(image: UIImage(namedRetina: "filter-box-check", tintColor: .blue)) // private let titleLabel = UILabel() // private let editButton = UIButton() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) // selectionStyle = .none // titleLabel.setProperties(text: "Test", font: UIFont.systemFont(ofSize: 15), textColor: .black, fit: true) // contentView.addSubview(titleLabel) // contentView.addSubview(checkmarkImageView) // editButton.setImageAndFit(UIImage(namedRetina: "<#T##String#>"<#, tintColor: UIColor#>), forState: .Normal) // editButton.setProperties(text: "Edit", font: UIFont.systemFont(ofSize: 12), normalTextColor: .black, highlightedTextColor: .darkGray, fit: true) // editButton.addTarget(self, action: #selector(didTapEdit), for: .touchUpInside) // contentView.addSubview(editButton) let deleteButton = MGSwipeButton(title: "Effacer", backgroundColor: .red, callback: { [weak self] (_) -> Bool in guard let strongSelf = self else { return true } strongSelf.cellDelegate?.didSelectDelete(forCell: strongSelf) // don't autohide return false }) rightButtons = [deleteButton] rightSwipeSettings.transition = .border // rightExpansion.fillOnTrigger = true // rightExpansion.fillOnTrigger = true//; rightExpansion.threshold = 1.1 rightExpansion.buttonIndex = 0 rightExpansion.fillOnTrigger = true } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() // let hPadding: CGFloat = 10 // checkmarkImageView.setPosition(.positionVCenterLeft, margins: .left(hPadding)) // titleLabel.setRelativePosition(.relativePositionToTheRightCentered, toView: checkmarkImageView, margins: .left(hPadding)) // editButton.setPosition(.positionVCenterRight, margins: .right(hPadding)) } override func setHighlighted(_ highlighted: Bool, animated: Bool) { super.setHighlighted(highlighted, animated: animated) backgroundColor = highlighted ? .lightGray : .white } func configure(entry: WordEntry) { textLabel?.text = entry.word detailTextLabel?.text = entry.sentence } }
apache-2.0
c7b482af5bd5bf302155594e774f563e
38.65
154
0.67087
4.644217
false
false
false
false
VirgilSecurity/virgil-sdk-keys-ios
Source/Utils/Operation/AsyncOperation.swift
1
3317
// // Copyright (C) 2015-2020 Virgil Security 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 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 AUTHOR ''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 AUTHOR 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. // // Lead Maintainer: Virgil Security Inc. <[email protected]> // import Foundation /// Class for AsyncOperations open class AsyncOperation: Operation { /// Operation error open var error: Error? /// Overrides Operation variable override open var isAsynchronous: Bool { return true } /// Overrides Operation variable override open var isExecuting: Bool { return self.state == .executing } /// Overrides Operation variable override open var isFinished: Bool { return self.state == .finished } /// Operation state private var state = State.ready { willSet { self.willChangeValue(forKey: self.state.keyPath) self.willChangeValue(forKey: newValue.keyPath) } didSet { self.didChangeValue(forKey: self.state.keyPath) self.didChangeValue(forKey: oldValue.keyPath) } } /// Describes Operation state public enum State: String { case ready = "Ready" case executing = "Executing" case finished = "Finished" fileprivate var keyPath: String { return "is" + self.rawValue } } /// Overrides Operation function /// WARNING: You do not need override this function. Override main() func instead override open func start() { guard !self.isCancelled else { self.state = .finished return } self.state = .executing self.main() } /// Call this function when you task is finished /// WARNING: You do not need override this function. Override main() func instead open func finish() { self.state = .finished } /// Implement your task here override open func main() { } }
bsd-3-clause
65fe0f1c24849f9e26c4b3f2599ed301
35.450549
85
0.684353
4.779539
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/RowAdapterTests.swift
1
41629
import XCTest import GRDB private enum CustomValue : Int, DatabaseValueConvertible, Equatable { case a = 0 case b = 1 case c = 2 } class AdapterRowTests : RowTestCase { func testRowAsSequence() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"]) let row = try Row.fetchOne(db, sql: "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 2 as basec", adapter: adapter)! var columnNames = [String]() var ints = [Int]() var bools = [Bool]() for (columnName, dbValue) in row { columnNames.append(columnName) ints.append(Int.fromDatabaseValue(dbValue)!) bools.append(Bool.fromDatabaseValue(dbValue)!) } XCTAssertEqual(columnNames, ["a", "b", "c"]) XCTAssertEqual(ints, [0, 1, 2]) XCTAssertEqual(bools, [false, true, true]) } } func testRowValueAtIndex() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"]) let row = try Row.fetchOne(db, sql: "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 2 as basec", adapter: adapter)! // Raw extraction assertRowRawValueEqual(row, index: 0, value: 0 as Int64) assertRowRawValueEqual(row, index: 1, value: 1 as Int64) assertRowRawValueEqual(row, index: 2, value: 2 as Int64) // DatabaseValueConvertible & StatementColumnConvertible assertRowConvertedValueEqual(row, index: 0, value: 0 as Int) assertRowConvertedValueEqual(row, index: 1, value: 1 as Int) assertRowConvertedValueEqual(row, index: 2, value: 2 as Int) // DatabaseValueConvertible assertRowConvertedValueEqual(row, index: 0, value: CustomValue.a) assertRowConvertedValueEqual(row, index: 1, value: CustomValue.b) assertRowConvertedValueEqual(row, index: 2, value: CustomValue.c) // Expect fatal error: // // row[-1] // row[3] } } func testRowValueNamed() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"]) let row = try Row.fetchOne(db, sql: "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 2 as basec", adapter: adapter)! // Raw extraction assertRowRawValueEqual(row, name: "a", value: 0 as Int64) assertRowRawValueEqual(row, name: "b", value: 1 as Int64) assertRowRawValueEqual(row, name: "c", value: 2 as Int64) // DatabaseValueConvertible & StatementColumnConvertible assertRowConvertedValueEqual(row, name: "a", value: 0 as Int) assertRowConvertedValueEqual(row, name: "b", value: 1 as Int) assertRowConvertedValueEqual(row, name: "c", value: 2 as Int) // DatabaseValueConvertible assertRowConvertedValueEqual(row, name: "a", value: CustomValue.a) assertRowConvertedValueEqual(row, name: "b", value: CustomValue.b) assertRowConvertedValueEqual(row, name: "c", value: CustomValue.c) } } func testRowValueFromColumn() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"]) let row = try Row.fetchOne(db, sql: "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 2 as basec", adapter: adapter)! // Raw extraction assertRowRawValueEqual(row, column: Column("a"), value: 0 as Int64) assertRowRawValueEqual(row, column: Column("b"), value: 1 as Int64) assertRowRawValueEqual(row, column: Column("c"), value: 2 as Int64) // DatabaseValueConvertible & StatementColumnConvertible assertRowConvertedValueEqual(row, column: Column("a"), value: 0 as Int) assertRowConvertedValueEqual(row, column: Column("b"), value: 1 as Int) assertRowConvertedValueEqual(row, column: Column("c"), value: 2 as Int) // DatabaseValueConvertible assertRowConvertedValueEqual(row, column: Column("a"), value: CustomValue.a) assertRowConvertedValueEqual(row, column: Column("b"), value: CustomValue.b) assertRowConvertedValueEqual(row, column: Column("c"), value: CustomValue.c) } } func testWithUnsafeData() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let data = "foo".data(using: .utf8)! let emptyData = Data() let adapter = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"]) let row = try Row.fetchOne(db, sql: "SELECT ? AS basea, ? AS baseb, ? AS basec", arguments: [data, emptyData, nil], adapter: adapter)! try row.withUnsafeData(atIndex: 0) { XCTAssertEqual($0, data) } try row.withUnsafeData(named: "a") { XCTAssertEqual($0, data) } try row.withUnsafeData(at: Column("a")) { XCTAssertEqual($0, data) } try row.withUnsafeData(atIndex: 1) { XCTAssertEqual($0, emptyData) } try row.withUnsafeData(named: "b") { XCTAssertEqual($0, emptyData) } try row.withUnsafeData(at: Column("b")) { XCTAssertEqual($0, emptyData) } try row.withUnsafeData(atIndex: 2) { XCTAssertNil($0) } try row.withUnsafeData(named: "c") { XCTAssertNil($0) } try row.withUnsafeData(at: Column("c")) { XCTAssertNil($0) } try row.withUnsafeData(named: "missing") { XCTAssertNil($0) } try row.withUnsafeData(at: Column("missing")) { XCTAssertNil($0) } } } func testRowDatabaseValueAtIndex() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["null": "basenull", "int64": "baseint64", "double": "basedouble", "string": "basestring", "blob": "baseblob"]) let row = try Row.fetchOne(db, sql: "SELECT NULL AS basenull, 'XXX' AS extra, 1 AS baseint64, 1.1 AS basedouble, 'foo' AS basestring, x'53514C697465' AS baseblob", adapter: adapter)! guard case .null = (row[0] as DatabaseValue).storage else { XCTFail(); return } guard case .int64(let int64) = (row[1] as DatabaseValue).storage, int64 == 1 else { XCTFail(); return } guard case .double(let double) = (row[2] as DatabaseValue).storage, double == 1.1 else { XCTFail(); return } guard case .string(let string) = (row[3] as DatabaseValue).storage, string == "foo" else { XCTFail(); return } guard case .blob(let data) = (row[4] as DatabaseValue).storage, data == "SQLite".data(using: .utf8) else { XCTFail(); return } } } func testRowDatabaseValueNamed() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["null": "basenull", "int64": "baseint64", "double": "basedouble", "string": "basestring", "blob": "baseblob"]) let row = try Row.fetchOne(db, sql: "SELECT NULL AS basenull, 'XXX' AS extra, 1 AS baseint64, 1.1 AS basedouble, 'foo' AS basestring, x'53514C697465' AS baseblob", adapter: adapter)! guard case .null = (row["null"] as DatabaseValue).storage else { XCTFail(); return } guard case .int64(let int64) = (row["int64"] as DatabaseValue).storage, int64 == 1 else { XCTFail(); return } guard case .double(let double) = (row["double"] as DatabaseValue).storage, double == 1.1 else { XCTFail(); return } guard case .string(let string) = (row["string"] as DatabaseValue).storage, string == "foo" else { XCTFail(); return } guard case .blob(let data) = (row["blob"] as DatabaseValue).storage, data == "SQLite".data(using: .utf8) else { XCTFail(); return } } } func testRowCount() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"]) let row = try Row.fetchOne(db, sql: "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 2 as basec", adapter: adapter)! XCTAssertEqual(row.count, 3) } } func testRowColumnNames() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"]) let row = try Row.fetchOne(db, sql: "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 2 as basec", adapter: adapter)! XCTAssertEqual(Array(row.columnNames), ["a", "b", "c"]) } } func testRowDatabaseValues() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"]) let row = try Row.fetchOne(db, sql: "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 2 as basec", adapter: adapter)! XCTAssertEqual(Array(row.databaseValues), [0.databaseValue, 1.databaseValue, 2.databaseValue]) } } func testRowIsCaseInsensitive() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["nAmE": "basenAmE"]) let row = try Row.fetchOne(db, sql: "SELECT 'foo' AS basenAmE, 'XXX' AS extra", adapter: adapter)! XCTAssertEqual(row["name"] as DatabaseValue, "foo".databaseValue) XCTAssertEqual(row["NAME"] as DatabaseValue, "foo".databaseValue) XCTAssertEqual(row["NaMe"] as DatabaseValue, "foo".databaseValue) XCTAssertEqual(row["name"] as String, "foo") XCTAssertEqual(row["NAME"] as String, "foo") XCTAssertEqual(row["NaMe"] as String, "foo") } } func testRowIsCaseInsensitiveAndReturnsLeftmostMatchingColumn() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["name": "basename", "NAME": "baseNAME"]) let row = try Row.fetchOne(db, sql: "SELECT 1 AS basename, 'XXX' AS extra, 2 AS baseNAME", adapter: adapter)! XCTAssertEqual(row["name"] as DatabaseValue, 1.databaseValue) XCTAssertEqual(row["NAME"] as DatabaseValue, 1.databaseValue) XCTAssertEqual(row["NaMe"] as DatabaseValue, 1.databaseValue) XCTAssertEqual(row["name"] as Int, 1) XCTAssertEqual(row["NAME"] as Int, 1) XCTAssertEqual(row["NaMe"] as Int, 1) } } func testRowAdapterIsCaseInsensitiveAndPicksLeftmostBaseColumn() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["name": "baseNaMe"]) let row = try Row.fetchOne(db, sql: "SELECT 1 AS basename, 2 AS baseNaMe, 3 AS BASENAME", adapter: adapter)! XCTAssertEqual(row["name"] as DatabaseValue, 1.databaseValue) } } func testMissingColumn() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["name": "name"]) let row = try Row.fetchOne(db, sql: "SELECT 1 AS name, 'foo' AS missing", adapter: adapter)! XCTAssertFalse(row.hasColumn("missing")) XCTAssertFalse(row.hasColumn("missingInBaseRow")) XCTAssertTrue(row["missing"] as DatabaseValue? == nil) XCTAssertTrue(row["missingInBaseRow"] as DatabaseValue? == nil) XCTAssertTrue(row["missing"] == nil) XCTAssertTrue(row["missingInBaseRow"] == nil) } } func testRowHasColumnIsCaseInsensitive() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["nAmE": "basenAmE", "foo": "basefoo"]) let row = try Row.fetchOne(db, sql: "SELECT 'foo' AS basenAmE, 'XXX' AS extra, 1 AS basefoo", adapter: adapter)! XCTAssertTrue(row.hasColumn("name")) XCTAssertTrue(row.hasColumn("NAME")) XCTAssertTrue(row.hasColumn("Name")) XCTAssertTrue(row.hasColumn("NaMe")) XCTAssertTrue(row.hasColumn("foo")) XCTAssertTrue(row.hasColumn("Foo")) XCTAssertTrue(row.hasColumn("FOO")) } } func testScopes() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ScopeAdapter([ "sub1": ColumnMapping(["id": "id1", "val": "val1"]), "sub2": ColumnMapping(["id": "id2", "val": "val2"])]) let row = try Row.fetchOne(db, sql: "SELECT 1 AS id1, 'foo1' AS val1, 2 as id2, 'foo2' AS val2", adapter: adapter)! XCTAssertEqual(row.count, 4) XCTAssertEqual(row["id1"] as Int, 1) XCTAssertEqual(row["val1"] as String, "foo1") XCTAssertEqual(row["id2"] as Int, 2) XCTAssertEqual(row["val2"] as String, "foo2") XCTAssertEqual(Set(row.scopes.names), ["sub1", "sub2"]) XCTAssertEqual(row.scopes.count, 2) for (name, scopedRow) in row.scopes { if name == "sub1" { XCTAssertEqual(scopedRow, ["id": 1, "val": "foo1"]) } else if name == "sub2" { XCTAssertEqual(scopedRow, ["id": 2, "val": "foo2"]) } else { XCTFail() } } XCTAssertEqual(row.scopesTree.names, ["sub1", "sub2"]) XCTAssertEqual(row.scopes["sub1"]!, ["id": 1, "val": "foo1"]) XCTAssertTrue(row.scopes["sub1"]!.scopes.isEmpty) XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) XCTAssertEqual(row.scopes["sub2"]!, ["id": 2, "val": "foo2"]) XCTAssertTrue(row.scopes["sub2"]!.scopes.isEmpty) XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub2"]) XCTAssertTrue(row.scopes["SUB1"] == nil) XCTAssertTrue(row.scopesTree["SUB1"] == nil) XCTAssertTrue(row.scopes["missing"] == nil) XCTAssertTrue(row.scopesTree["missing"] == nil) } } func testScopesWithMainMapping() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["id": "id0", "val": "val0"]) .addingScopes([ "sub1": ColumnMapping(["id": "id1", "val": "val1"]), "sub2": ColumnMapping(["id": "id2", "val": "val2"])]) let row = try Row.fetchOne(db, sql: "SELECT 0 AS id0, 'foo0' AS val0, 1 AS id1, 'foo1' AS val1, 2 as id2, 'foo2' AS val2", adapter: adapter)! XCTAssertEqual(row.count, 2) XCTAssertEqual(row["id"] as Int, 0) XCTAssertEqual(row["val"] as String, "foo0") XCTAssertEqual(Set(row.scopes.names), ["sub1", "sub2"]) XCTAssertEqual(row.scopes.count, 2) for (name, scopedRow) in row.scopes { if name == "sub1" { XCTAssertEqual(scopedRow, ["id": 1, "val": "foo1"]) } else if name == "sub2" { XCTAssertEqual(scopedRow, ["id": 2, "val": "foo2"]) } else { XCTFail() } } XCTAssertEqual(row.scopesTree.names, ["sub1", "sub2"]) XCTAssertEqual(row.scopes["sub1"]!, ["id": 1, "val": "foo1"]) XCTAssertTrue(row.scopes["sub1"]!.scopes.isEmpty) XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) XCTAssertEqual(row.scopes["sub2"], ["id": 2, "val": "foo2"]) XCTAssertTrue(row.scopes["sub2"]!.scopes.isEmpty) XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub2"]) XCTAssertTrue(row.scopes["SUB1"] == nil) XCTAssertTrue(row.scopesTree["SUB1"] == nil) XCTAssertTrue(row.scopes["missing"] == nil) XCTAssertTrue(row.scopesTree["missing"] == nil) } } func testMergeScopes() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter0 = ColumnMapping(["id": "id0", "val": "val0"]) let adapter1 = ColumnMapping(["id": "id1", "val": "val1"]) let adapter2 = ColumnMapping(["id": "id2", "val": "val2"]) // - sub0 is defined in the the first scoped adapter // - sub1 is defined in the the first scoped adapter, and then // redefined in the second // - sub2 is defined in the the second scoped adapter let mainAdapter = ScopeAdapter(["sub0": adapter0, "sub1": adapter2]) let adapter = mainAdapter.addingScopes(["sub1": adapter1, "sub2": adapter2]) let row = try Row.fetchOne(db, sql: "SELECT 0 AS id0, 'foo0' AS val0, 1 AS id1, 'foo1' AS val1, 2 as id2, 'foo2' AS val2", adapter: adapter)! XCTAssertEqual(Set(row.scopes.names), ["sub0", "sub1", "sub2"]) XCTAssertEqual(row.scopes.count, 3) for (name, scopedRow) in row.scopes { if name == "sub0" { XCTAssertEqual(scopedRow, ["id": 0, "val": "foo0"]) } else if name == "sub1" { XCTAssertEqual(scopedRow, ["id": 1, "val": "foo1"]) } else if name == "sub2" { XCTAssertEqual(scopedRow, ["id": 2, "val": "foo2"]) } else { XCTFail() } } XCTAssertEqual(row.scopesTree.names, ["sub0", "sub1", "sub2"]) XCTAssertEqual(row.scopes["sub0"], ["id": 0, "val": "foo0"]) XCTAssertTrue(row.scopes["sub0"]!.scopes.isEmpty) XCTAssertEqual(row.scopesTree["sub0"], row.scopes["sub0"]) XCTAssertEqual(row.scopes["sub1"], ["id": 1, "val": "foo1"]) XCTAssertTrue(row.scopes["sub1"]!.scopes.isEmpty) XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) XCTAssertEqual(row.scopes["sub2"], ["id": 2, "val": "foo2"]) XCTAssertTrue(row.scopes["sub2"]!.scopes.isEmpty) XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub2"]) } } func testThreeLevelScopes() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["id": "id0", "val": "val0"]) .addingScopes([ "sub1": ColumnMapping(["id": "id1", "val": "val1"]) .addingScopes([ "sub2": ColumnMapping(["id": "id2", "val": "val2"])])]) let row = try Row.fetchOne(db, sql: "SELECT 0 AS id0, 'foo0' AS val0, 1 AS id1, 'foo1' AS val1, 2 as id2, 'foo2' AS val2", adapter: adapter)! XCTAssertEqual(row.count, 2) XCTAssertEqual(row["id"] as Int, 0) XCTAssertEqual(row["val"] as String, "foo0") XCTAssertEqual(Set(row.scopes.names), ["sub1"]) XCTAssertEqual(row.scopes.count, 1) for (name, scopedRow) in row.scopes { if name == "sub1" { XCTAssertEqual(scopedRow.unscoped, ["id": 1, "val": "foo1"]) } else { XCTFail() } } let scopedRow = row.scopes["sub1"]! XCTAssertEqual(scopedRow.unscoped, ["id": 1, "val": "foo1"]) XCTAssertEqual(Set(scopedRow.scopes.names), ["sub2"]) XCTAssertEqual(scopedRow.scopes.count, 1) for (name, subScopedRow) in scopedRow.scopes { if name == "sub2" { XCTAssertEqual(subScopedRow, ["id": 2, "val": "foo2"]) } else { XCTFail() } } XCTAssertEqual(scopedRow.scopes["sub2"]!, ["id": 2, "val": "foo2"]) XCTAssertTrue(scopedRow.scopes["sub2"]!.scopes.isEmpty) // sub2 is only defined in sub1 XCTAssertTrue(row.scopes["sub2"] == nil) XCTAssertEqual(row.scopesTree.names, ["sub1", "sub2"]) XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub1"]!.scopes["sub2"]) } } func testSuffixAdapter() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let sql = "SELECT 0 AS a0, 1 AS a1, 2 AS a2, 3 AS a3" do { let row = try Row.fetchOne(db, sql: sql, adapter: SuffixRowAdapter(fromIndex:0))! XCTAssertEqual(Array(row.columnNames), ["a0", "a1", "a2", "a3"]) XCTAssertEqual(Array(row.databaseValues), [0.databaseValue, 1.databaseValue, 2.databaseValue, 3.databaseValue]) } do { let row = try Row.fetchOne(db, sql: sql, adapter: SuffixRowAdapter(fromIndex:1))! XCTAssertEqual(Array(row.columnNames), ["a1", "a2", "a3"]) XCTAssertEqual(Array(row.databaseValues), [1.databaseValue, 2.databaseValue, 3.databaseValue]) } do { let row = try Row.fetchOne(db, sql: sql, adapter: SuffixRowAdapter(fromIndex:3))! XCTAssertEqual(Array(row.columnNames), ["a3"]) XCTAssertEqual(Array(row.databaseValues), [3.databaseValue]) } do { let row = try Row.fetchOne(db, sql: sql, adapter: SuffixRowAdapter(fromIndex:4))! XCTAssertEqual(Array(row.columnNames), []) XCTAssertEqual(Array(row.databaseValues), []) } } } func testSuffixAdapterIndexesAreIndependentFromScopes() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ScopeAdapter([ "sub1": SuffixRowAdapter(fromIndex: 1) .addingScopes([ "sub2": SuffixRowAdapter(fromIndex: 1)])]) let row = try Row.fetchOne(db, sql: "SELECT 0 AS a0, 1 AS a1, 2 AS a2, 3 AS a3", adapter: adapter)! XCTAssertEqual(Set(row.scopes.names), ["sub1"]) XCTAssertEqual(row.scopes.count, 1) for (name, scopedRow) in row.scopes { if name == "sub1" { XCTAssertEqual(scopedRow.unscoped, ["a1": 1, "a2": 2, "a3": 3]) } else { XCTFail() } } let scopedRow = row.scopes["sub1"]! XCTAssertEqual(scopedRow.unscoped, ["a1": 1, "a2": 2, "a3": 3]) XCTAssertEqual(Set(scopedRow.scopes.names), ["sub2"]) XCTAssertEqual(scopedRow.scopes.count, 1) for (name, subScopedRow) in scopedRow.scopes { if name == "sub2" { XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2, "a3": 3]) } else { XCTFail() } } let subScopedRow = scopedRow.scopes["sub2"]! XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2, "a3": 3]) XCTAssertTrue(subScopedRow.scopes.isEmpty) // sub2 is only defined in sub1 XCTAssertTrue(row.scopes["sub2"] == nil) XCTAssertEqual(row.scopesTree.names, ["sub1", "sub2"]) XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub1"]!.scopes["sub2"]) } } func testRangeAdapterWithCountableRange() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let sql = "SELECT 0 AS a0, 1 AS a1, 2 AS a2, 3 AS a3" do { let row = try Row.fetchOne(db, sql: sql, adapter: RangeRowAdapter(0..<0))! XCTAssertEqual(Array(row.columnNames), []) XCTAssertEqual(Array(row.databaseValues), []) } do { let row = try Row.fetchOne(db, sql: sql, adapter: RangeRowAdapter(0..<1))! XCTAssertEqual(Array(row.columnNames), ["a0"]) XCTAssertEqual(Array(row.databaseValues), [0.databaseValue]) } do { let row = try Row.fetchOne(db, sql: sql, adapter: RangeRowAdapter(1..<3))! XCTAssertEqual(Array(row.columnNames), ["a1", "a2"]) XCTAssertEqual(Array(row.databaseValues), [1.databaseValue, 2.databaseValue]) } do { let row = try Row.fetchOne(db, sql: sql, adapter: RangeRowAdapter(0..<4))! XCTAssertEqual(Array(row.columnNames), ["a0", "a1", "a2", "a3"]) XCTAssertEqual(Array(row.databaseValues), [0.databaseValue, 1.databaseValue, 2.databaseValue, 3.databaseValue]) } do { let row = try Row.fetchOne(db, sql: sql, adapter: RangeRowAdapter(4..<4))! XCTAssertEqual(Array(row.columnNames), []) XCTAssertEqual(Array(row.databaseValues), []) } } } func testRangeAdapterWithCountableClosedRange() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let sql = "SELECT 0 AS a0, 1 AS a1, 2 AS a2, 3 AS a3" do { let row = try Row.fetchOne(db, sql: sql, adapter: RangeRowAdapter(0...0))! XCTAssertEqual(Array(row.columnNames), ["a0"]) XCTAssertEqual(Array(row.databaseValues), [0.databaseValue]) } do { let row = try Row.fetchOne(db, sql: sql, adapter: RangeRowAdapter(0...1))! XCTAssertEqual(Array(row.columnNames), ["a0", "a1"]) XCTAssertEqual(Array(row.databaseValues), [0.databaseValue, 1.databaseValue]) } do { let row = try Row.fetchOne(db, sql: sql, adapter: RangeRowAdapter(1...2))! XCTAssertEqual(Array(row.columnNames), ["a1", "a2"]) XCTAssertEqual(Array(row.databaseValues), [1.databaseValue, 2.databaseValue]) } do { let row = try Row.fetchOne(db, sql: sql, adapter: RangeRowAdapter(0...3))! XCTAssertEqual(Array(row.columnNames), ["a0", "a1", "a2", "a3"]) XCTAssertEqual(Array(row.databaseValues), [0.databaseValue, 1.databaseValue, 2.databaseValue, 3.databaseValue]) } do { let row = try Row.fetchOne(db, sql: sql, adapter: RangeRowAdapter(3...3))! XCTAssertEqual(Array(row.columnNames), ["a3"]) XCTAssertEqual(Array(row.databaseValues), [3.databaseValue]) } } } func testRangeAdapterIndexesAreIndependentFromScopes() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ScopeAdapter([ "sub1": RangeRowAdapter(1..<3) .addingScopes([ "sub2": RangeRowAdapter(1..<3)])]) let row = try Row.fetchOne(db, sql: "SELECT 0 AS a0, 1 AS a1, 2 AS a2, 3 AS a3", adapter: adapter)! XCTAssertEqual(Set(row.scopes.names), ["sub1"]) XCTAssertEqual(row.scopes.count, 1) for (name, scopedRow) in row.scopes { if name == "sub1" { XCTAssertEqual(scopedRow.unscoped, ["a1": 1, "a2": 2]) } else { XCTFail() } } let scopedRow = row.scopes["sub1"]! XCTAssertEqual(scopedRow.unscoped, ["a1": 1, "a2": 2]) XCTAssertEqual(Set(scopedRow.scopes.names), ["sub2"]) XCTAssertEqual(scopedRow.scopes.count, 1) for (name, subScopedRow) in scopedRow.scopes { if name == "sub2" { XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2]) } else { XCTFail() } } let subScopedRow = scopedRow.scopes["sub2"]! XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2]) XCTAssertTrue(subScopedRow.scopes.isEmpty) // sub2 is only defined in sub1 XCTAssertTrue(row.scopes["sub2"] == nil) XCTAssertEqual(row.scopesTree.names, ["sub1", "sub2"]) XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub1"]!.scopes["sub2"]) } } func testCopy() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"]) .addingScopes(["sub": ColumnMapping(["a": "baseb"])]) var copiedRow: Row? = nil let baseRows = try Row.fetchCursor(db, sql: "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 2 as basec", adapter: adapter) while let baseRow = try baseRows.next() { copiedRow = baseRow.copy() } if let copiedRow = copiedRow { XCTAssertEqual(copiedRow.count, 3) XCTAssertEqual(copiedRow["a"] as Int, 0) XCTAssertEqual(copiedRow["b"] as Int, 1) XCTAssertEqual(copiedRow["c"] as Int, 2) XCTAssertEqual(Set(copiedRow.scopes.names), ["sub"]) XCTAssertEqual(copiedRow.scopes.count, 1) for (name, scopedRow) in copiedRow.scopes { if name == "sub" { XCTAssertEqual(scopedRow, ["a": 1]) } else { XCTFail() } } XCTAssertEqual(Set(copiedRow.scopes.names), ["sub"]) XCTAssertEqual(copiedRow.scopes["sub"]!, ["a": 1]) XCTAssertTrue(copiedRow.scopes["sub"]!.scopes.isEmpty) XCTAssertEqual(copiedRow.scopesTree.names, ["sub"]) XCTAssertEqual(copiedRow.scopesTree["sub"]!, ["a": 1]) } else { XCTFail() } } } func testEqualityWithCopy() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"]) var row: Row? = nil let baseRows = try Row.fetchCursor(db, sql: "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 2 as basec", adapter: adapter) while let baseRow = try baseRows.next() { row = baseRow.copy() XCTAssertEqual(row, baseRow) } if let row = row { let copiedRow = row.copy() XCTAssertEqual(row, copiedRow) } else { XCTFail() } } } func testEqualityComparesScopes() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter1 = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"]) .addingScopes(["sub": ColumnMapping(["b": "baseb"])]) let adapter2 = ColumnMapping(["a": "basea", "b": "baseb2", "c": "basec"]) let adapter3 = ColumnMapping(["a": "basea", "b": "baseb2", "c": "basec"]) .addingScopes(["sub": ColumnMapping(["b": "baseb2"])]) let adapter4 = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"]) .addingScopes(["sub": ColumnMapping(["b": "baseb"]), "altSub": ColumnMapping(["a": "baseb2"])]) let adapter5 = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"]) .addingScopes(["sub": ColumnMapping(["b": "baseb", "c": "basec"])]) let row1 = try Row.fetchOne(db, sql: "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 1 AS baseb2, 2 as basec", adapter: adapter1)! let row2 = try Row.fetchOne(db, sql: "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 1 AS baseb2, 2 as basec", adapter: adapter2)! let row3 = try Row.fetchOne(db, sql: "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 1 AS baseb2, 2 as basec", adapter: adapter3)! let row4 = try Row.fetchOne(db, sql: "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 1 AS baseb2, 2 as basec", adapter: adapter4)! let row5 = try Row.fetchOne(db, sql: "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 1 AS baseb2, 2 as basec", adapter: adapter5)! let tests = [ (row1, row2, false), (row1, row3, true), (row1, row4, false), (row1, row5, false), (row1.scopes["sub"], row3.scopes["sub"], true), (row1.scopes["sub"], row4.scopes["sub"], true), (row1.scopes["sub"], row5.scopes["sub"], false)] for (lrow, rrow, equal) in tests { if equal { XCTAssertEqual(lrow, rrow) } else { XCTAssertNotEqual(lrow, rrow) } } } } func testEqualityWithNonMappedRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["id": "baseid", "val": "baseval"]) let mappedRow1 = try Row.fetchOne(db, sql: "SELECT 1 AS baseid, 'XXX' AS extra, 'foo' AS baseval", adapter: adapter)! let mappedRow2 = try Row.fetchOne(db, sql: "SELECT 'foo' AS baseval, 'XXX' AS extra, 1 AS baseid", adapter: adapter)! let nonMappedRow1 = try Row.fetchOne(db, sql: "SELECT 1 AS id, 'foo' AS val")! let nonMappedRow2 = try Row.fetchOne(db, sql: "SELECT 'foo' AS val, 1 AS id")! // All rows contain the same values. But they differ by column ordering. XCTAssertEqual(Array(mappedRow1.columnNames), ["id", "val"]) XCTAssertEqual(Array(mappedRow2.columnNames), ["val", "id"]) XCTAssertEqual(Array(nonMappedRow1.columnNames), ["id", "val"]) XCTAssertEqual(Array(nonMappedRow2.columnNames), ["val", "id"]) // Row equality takes ordering in account: XCTAssertNotEqual(mappedRow1, mappedRow2) XCTAssertEqual(mappedRow1, nonMappedRow1) XCTAssertNotEqual(mappedRow1, nonMappedRow2) XCTAssertNotEqual(mappedRow2, nonMappedRow1) XCTAssertEqual(mappedRow2, nonMappedRow2) } } func testEmptyMapping() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping([:]) let row = try Row.fetchOne(db, sql: "SELECT 'foo' AS foo", adapter: adapter)! XCTAssertTrue(row.isEmpty) XCTAssertEqual(row.count, 0) XCTAssertEqual(Array(row.columnNames), []) XCTAssertEqual(Array(row.databaseValues), []) XCTAssertFalse(row.hasColumn("foo")) } } func testRequestAdapter() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { let row = try SQLRequest<Row>(sql: "SELECT 0 AS a0, 1 AS a1, 2 AS a2", adapter: SuffixRowAdapter(fromIndex: 1)) .fetchOne(db)! XCTAssertEqual(Array(row.columnNames), ["a1", "a2"]) XCTAssertEqual(Array(row.databaseValues), [1.databaseValue, 2.databaseValue]) } do { let row = try SQLRequest<Row>(sql: "SELECT 0 AS a0, 1 AS a1, 2 AS a2") .adapted { _ in SuffixRowAdapter(fromIndex: 1) } .fetchOne(db)! XCTAssertEqual(Array(row.columnNames), ["a1", "a2"]) XCTAssertEqual(Array(row.databaseValues), [1.databaseValue, 2.databaseValue]) } do { let row = try SQLRequest<Row>(sql: "SELECT 0 AS a0, 1 AS a1, 2 AS a2", adapter: SuffixRowAdapter(fromIndex: 1)) .adapted { _ in SuffixRowAdapter(fromIndex: 1) } .fetchOne(db)! XCTAssertEqual(Array(row.columnNames), ["a2"]) XCTAssertEqual(Array(row.databaseValues), [2.databaseValue]) } do { let row = try SQLRequest<Row>(sql: "SELECT 0 AS a0", adapter: ColumnMapping(["a1": "a0"])) .adapted { _ in ColumnMapping(["a2": "a1"]) } .fetchOne(db)! XCTAssertEqual(Array(row.columnNames), ["a2"]) XCTAssertEqual(Array(row.databaseValues), [0.databaseValue]) } do { let row = try SQLRequest<Row>(sql: "SELECT 0 AS a0", adapter: ColumnMapping(["a1": "a0"])) .adapted { _ in ColumnMapping(["a2": "a1"]) } .adapted { _ in ColumnMapping(["a3": "a2"]) } .fetchOne(db)! XCTAssertEqual(Array(row.columnNames), ["a3"]) XCTAssertEqual(Array(row.databaseValues), [0.databaseValue]) } } } func testDescription() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let adapter = ColumnMapping(["id": "id0", "val": "val0"]) .addingScopes([ "a": ColumnMapping(["id": "id1", "val": "val1"]) .addingScopes([ "b": ColumnMapping(["id": "id2", "val": "val2"]) .addingScopes([ "c": SuffixRowAdapter(fromIndex:4)]), "a": SuffixRowAdapter(fromIndex:0)]), "b": ColumnMapping(["id": "id1", "val": "val1"]) .addingScopes([ "ba": ColumnMapping(["id": "id2", "val": "val2"])])]) let row = try Row.fetchOne(db, sql: "SELECT 0 AS id0, 'foo0' AS val0, 1 AS id1, 'foo1' AS val1, 2 as id2, 'foo2' AS val2", adapter: adapter)! XCTAssertEqual(row.description, "[id:0 val:\"foo0\"]") XCTAssertEqual(row.debugDescription, """ ▿ [id:0 val:"foo0"] unadapted: [id0:0 val0:"foo0" id1:1 val1:"foo1" id2:2 val2:"foo2"] - a: [id:1 val:"foo1"] - a: [id0:0 val0:"foo0" id1:1 val1:"foo1" id2:2 val2:"foo2"] - b: [id:2 val:"foo2"] - c: [id2:2 val2:"foo2"] - b: [id:1 val:"foo1"] - ba: [id:2 val:"foo2"] """) XCTAssertEqual(row.scopes["a"]!.description, "[id:1 val:\"foo1\"]") XCTAssertEqual(row.scopes["a"]!.debugDescription, """ ▿ [id:1 val:"foo1"] unadapted: [id0:0 val0:"foo0" id1:1 val1:"foo1" id2:2 val2:"foo2"] - a: [id0:0 val0:"foo0" id1:1 val1:"foo1" id2:2 val2:"foo2"] - b: [id:2 val:"foo2"] - c: [id2:2 val2:"foo2"] """) } } func testRenameColumnAdapter() throws { // Test RenameColumn with the use case it was introduced for: // columns that have a `:NNN` suffix. // See https://github.com/groue/GRDB.swift/issues/810 let request: SQLRequest<Row> = #"SELECT 1 AS "id:1", 'foo' AS name, 2 AS "id:2""# let adaptedRequest = request .adapted { _ in RenameColumnAdapter { String($0.prefix(while: { $0 != ":" })) } } .adapted { _ in let adapters = splittingRowAdapters(columnCounts: [2, 1]) return ScopeAdapter([ "a": adapters[0], "b": adapters[1], ]) } let row = try makeDatabaseQueue().read(adaptedRequest.fetchOne)! XCTAssertEqual(row.unscoped, ["id": 1, "name": "foo", "id": 2]) XCTAssertEqual(row.unadapted, ["id:1": 1, "name": "foo", "id:2": 2]) XCTAssertEqual(row.scopes["a"], ["id": 1, "name": "foo"]) XCTAssertEqual(row.scopes["b"], ["id": 2]) } }
mit
de624a0ccae5f65d38bbb8b376da8744
47.741218
194
0.535375
4.238798
false
false
false
false
goin18/test-ios
Toshl iOS/CostsRevenuesVC.swift
1
12443
// // CostsRevenuesVC.swift // Toshl iOS // // Created by Marko Budal on 25/03/15. // Copyright (c) 2015 Marko Budal. All rights reserved. // import UIKit import CoreData class CostsRevenuesVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate { @IBOutlet weak var tableView: UITableView! var myPathView:PathView! var plusButton: UIButton! var titleLabel: UILabel! let appDelegete = (UIApplication.sharedApplication().delegate as! AppDelegate) let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext var tableDays:[(DateDay, Bool)] = [] var tableCostDay:[[Cost]] = [] override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self navigationController?.navigationBar.barTintColor = UIColor(red: 243/255, green: 241/255, blue: 230/255, alpha: 1.0) setPlusButton() titleLabel = UILabel() titleLabel.hidden = true view.addSubview(titleLabel) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(true) tableDays = [] getDaysFromCoreData() setButtonToBeginState() tableView.reloadData() } //Segue - navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "addGreen" { let addCostslVC: AddCostsVC = segue.destinationViewController as! AddCostsVC addCostslVC.segueMode = "addGreen" } else if segue.identifier == "addRed" { let addCostslVC: AddCostsVC = segue.destinationViewController as! AddCostsVC addCostslVC.segueMode = "addRed" }else if segue.identifier == "addGrey" { let addCostslVC: AddCostsVC = segue.destinationViewController as! AddCostsVC addCostslVC.segueMode = "addGrey" }else if segue.identifier == "costDetail" { let costDetailVC: CostDetailVC = segue.destinationViewController as! CostDetailVC costDetailVC.costDetail = tableCostDay[tableView.indexPathForSelectedRow()!.section][tableView.indexPathForSelectedRow()!.row] } } //UITableViewDataSorce func numberOfSectionsInTableView(tableView: UITableView) -> Int { return tableDays.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableDays[section].1 { return tableDays[section].0.numberCost.integerValue } return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { tableCostDay = [] for day in tableDays { costDataForDay(day: day.0.date) } var cell = tableView.dequeueReusableCellWithIdentifier("cell") as! Cell cell.labelCategory.text = tableCostDay[indexPath.section][indexPath.row].category cell.labelCategory.textColor = UIColor.darkGrayColor() cell.labelCategory.sizeToFit() cell.labelCategory.frame.origin = CGPoint(x: 10, y: 12) cell.labelName.text = tableCostDay[indexPath.section][indexPath.row].name cell.labelName.textColor = UIColor.lightGrayColor() cell.labelName.sizeToFit() cell.labelName.frame.origin = CGPoint(x: (cell.labelCategory.frame.width + 20), y: 12) cell.labelCost.text = String(format: "€%.2f", (tableCostDay[indexPath.section][indexPath.row].cost).floatValue) cell.labelCost.textColor = UIColor.lightGrayColor() cell.labelCost.sizeToFit() cell.labelCost.frame.origin = CGPoint(x: view.bounds.width - cell.labelCost.bounds.width - 40, y: 12) cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator return cell } //TableViewDataSorce - Header func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { var cell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as! HeaderCell var cost:Float = tableDays[section].0.costs.floatValue cell.dateLabel.text = Date.toString(date:tableDays[section].0.date) cell.monthlyCostsLabel.text = String(format: "€%.2f", cost) var buttonPressed = UIButton(frame: CGRect(x: 0, y: 0, width: cell.bounds.width, height: cell.bounds.height)) buttonPressed.addTarget(self, action: "toggleCellPushDown:", forControlEvents: UIControlEvents.TouchUpInside) buttonPressed.tag = section cell.addSubview(buttonPressed) return cell } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } func toggleCellPushDown(sender: UIButton) { if tableDays[sender.tag].1 { tableDays[sender.tag].1 = false }else { tableDays[sender.tag].1 = true } tableView.reloadData() } //UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { performSegueWithIdentifier("costDetail", sender: self) } //Helper Funct func getDaysFromCoreData(){ let fetchRequest = NSFetchRequest(entityName: "DateDay") let sortDescriptor = NSSortDescriptor(key: "date", ascending: false) fetchRequest.sortDescriptors = [sortDescriptor] let objectsDay = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as! [DateDay] for object in objectsDay { tableDays += [(object,true)] } } func costDataForDay(#day: NSDate) { let fetchRequest = NSFetchRequest(entityName: "Cost") let exprTitle = NSExpression(forKeyPath: "date") let exprValue = NSExpression(forConstantValue: day) let predicate = NSComparisonPredicate(leftExpression: exprTitle, rightExpression: exprValue, modifier: NSComparisonPredicateModifier.DirectPredicateModifier, type: NSPredicateOperatorType.EqualToPredicateOperatorType, options: nil) fetchRequest.predicate = predicate var x = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as! [Cost] // println(x.count) tableCostDay += [x] } func setPlusButton() { plusButton = UIButton(frame: CGRect(x: 10, y: self.view.bounds.height * 0.9, width: 60, height: 60)) plusButton.setImage(UIImage(named: "redPlus"), forState: UIControlState.Normal) plusButton.tag = 0 // plusButton.addTarget(self, action: "buttonTuchDown:", forControlEvents: UIControlEvents.TouchDown) let panOnPoints = UIPanGestureRecognizer(target: self, action: Selector("panOnPoints:")) plusButton.addGestureRecognizer(panOnPoints) view.addSubview(plusButton) } func panOnPoints(sender:UIPanGestureRecognizer) { var xX:CGFloat = sender.locationInView(view).x var yY:CGFloat = sender.locationInView(view).y var point = CGPoint(x: xX, y: yY) let redArea = (view.bounds.width / 1.0/3.0) - 70 let greeArea = (view.bounds.width / 1.0/3.0) + 20 let greyArea = (view.bounds.width / 1.0/3.0 * 2) + 50 let yBound = self.view.bounds.height * 0.80 let yBoundSledi = self.view.bounds.height * 0.70 let centerPoint = CGPoint(x: view.bounds.width, y: view.bounds.height - 10) let radiusMax = CGFloat(view.bounds.width - 15) let radiusMin = CGFloat(view.bounds.width - 100) let radiusMiddel = CGFloat(view.bounds.width - 50) //println("radius: \(radius)") var dr = CGPoint(x: point.x - centerPoint.x, y: point.y - centerPoint.y) var pointRadius = abs(sqrt(pow((point.x - centerPoint.x), 2) + pow((point.y - centerPoint.y), 2))) //println("pointRadius: \(pointRadius)") //println("radiusMiddel: \(radiusMiddel)") var d = pointRadius - radiusMiddel var newPoint = CGPoint(x: point.x + d, y: point.y + d) if sender.state.hashValue == 2 { // println("ViewBound: \(CGPoint(x: view.bounds.width, y: view.bounds.height)))") titleLabel.hidden = false var newPoint = CGPoint(x: point.x + d, y: point.y + d) if pointRadius > radiusMin && pointRadius < radiusMax { plusButton.center = newPoint if newPoint.x < greeArea { titleLabel.hidden = false plusButton.setImage(UIImage(named: "redPlus"), forState: UIControlState.Normal) setTitleLabel(color: "red", point: newPoint) }else if newPoint.x >= greeArea && point.x < greyArea { titleLabel.hidden = false plusButton.setImage(UIImage(named: "greenPlus"), forState: UIControlState.Normal) setTitleLabel(color: "green", point: newPoint) } else if newPoint.x > greeArea { titleLabel.hidden = false plusButton.setImage(UIImage(named: "greyPlus"), forState: UIControlState.Normal) setTitleLabel(color: "grey", point: newPoint) }else{ setButtonToBeginState() } } else { setButtonToBeginState() } } else if sender.state.hashValue == 3 { if pointRadius > radiusMin && pointRadius < radiusMax { setButtonToBeginState() if newPoint.x < greeArea { performSegueWithIdentifier("addRed", sender: self) }else if newPoint.x >= greeArea && point.x < greyArea { performSegueWithIdentifier("addGreen", sender: self) } else if newPoint.x > greeArea { performSegueWithIdentifier("addGrey", sender: self) } } } } func setTitleLabel(#color:String, point: CGPoint){ switch color { case "red": titleLabel.text = "Add expense" titleLabel.backgroundColor = UIColor(red: 187/255, green: 45/255, blue: 62/255, alpha: 1.0) var textLabellength = titleLabel.bounds.width / 2 if point.x > textLabellength { textLabellength = textLabellength + (point.x - textLabellength) } titleLabel.center = CGPoint(x: textLabellength, y: point.y - 65) case "green": titleLabel.text = "Add income" titleLabel.backgroundColor = UIColor(red: 29/255, green: 156/255, blue: 61/255, alpha: 1.0) titleLabel.center = CGPoint(x: point.x, y: point.y - 65) case "grey": titleLabel.text = "Make transaction" titleLabel.backgroundColor = UIColor(red: 129/255, green: 127/255, blue: 121/255, alpha: 1.0) var textLabellength = titleLabel.bounds.width / 2 if point.x > (view.bounds.width - textLabellength) { textLabellength = (view.bounds.width - textLabellength) titleLabel.center = CGPoint(x: textLabellength, y: point.y - 65) }else { titleLabel.center = CGPoint(x: point.x, y: point.y - 65) } default: println("Error") } titleLabel.font = UIFont(name: "AmericanTypewriter", size: 14) titleLabel.textColor = UIColor.whiteColor() titleLabel.bounds.size = CGSize(width: 150, height: 35) titleLabel.textAlignment = NSTextAlignment.Center titleLabel.layer.cornerRadius = 10.0 titleLabel.clipsToBounds = true } func setButtonToBeginState(){ plusButton.frame.origin = CGPoint(x: 10, y: self.view.bounds.height - 70) plusButton.setImage(UIImage(named: "redPlus"), forState: UIControlState.Normal) titleLabel.hidden = true } }
mit
bf7c62e71043a6d40b07b1633e495e3c
40.463333
239
0.622397
4.634501
false
false
false
false
djwbrown/swift
test/Constraints/members.swift
2
11892
// RUN: %target-typecheck-verify-swift -swift-version 4 //// // Members of structs //// struct X { func f0(_ i: Int) -> X { } func f1(_ i: Int) { } mutating func f1(_ f: Float) { } func f2<T>(_ x: T) -> T { } } struct Y<T> { func f0(_: T) -> T {} func f1<U>(_ x: U, y: T) -> (T, U) {} } var i : Int var x : X var yf : Y<Float> func g0(_: (inout X) -> (Float) -> ()) {} _ = x.f0(i) x.f0(i).f1(i) g0(X.f1) _ = x.f0(x.f2(1)) _ = x.f0(1).f2(i) _ = yf.f0(1) _ = yf.f1(i, y: 1) // Members referenced from inside the struct struct Z { var i : Int func getI() -> Int { return i } mutating func incI() {} func curried(_ x: Int) -> (Int) -> Int { return { y in x + y } } subscript (k : Int) -> Int { get { return i + k } mutating set { i -= k } } } struct GZ<T> { var i : T func getI() -> T { return i } func f1<U>(_ a: T, b: U) -> (T, U) { return (a, b) } func f2() { var f : Float var t = f1(i, b: f) f = t.1 var zi = Z.i; // expected-error{{instance member 'i' cannot be used on type 'Z'}} var zj = Z.asdfasdf // expected-error {{type 'Z' has no member 'asdfasdf'}} } } var z = Z(i: 0) var getI = z.getI var incI = z.incI // expected-error{{partial application of 'mutating'}} var zi = z.getI() var zcurried1 = z.curried var zcurried2 = z.curried(0) var zcurriedFull = z.curried(0)(1) //// // Members of modules //// // Module Swift.print(3, terminator: "") //// // Unqualified references //// //// // Members of literals //// // FIXME: Crappy diagnostic "foo".lower() // expected-error{{value of type 'String' has no member 'lower'}} var tmp = "foo".debugDescription //// // Members of enums //// enum W { case Omega func foo(_ x: Int) {} func curried(_ x: Int) -> (Int) -> () {} } var w = W.Omega var foo = w.foo var fooFull : () = w.foo(0) var wcurried1 = w.curried var wcurried2 = w.curried(0) var wcurriedFull : () = w.curried(0)(1) // Member of enum type func enumMetatypeMember(_ opt: Int?) { opt.none // expected-error{{enum element 'none' cannot be referenced as an instance member}} } //// // Nested types //// // Reference a Type member. <rdar://problem/15034920> class G<T> { class In { class func foo() {} } } func goo() { G<Int>.In.foo() } //// // Misc ambiguities //// // <rdar://problem/15537772> struct DefaultArgs { static func f(_ a: Int = 0) -> DefaultArgs { return DefaultArgs() } init() { self = .f() } } class InstanceOrClassMethod { func method() -> Bool { return true } class func method(_ other: InstanceOrClassMethod) -> Bool { return false } } func testPreferClassMethodToCurriedInstanceMethod(_ obj: InstanceOrClassMethod) { let result = InstanceOrClassMethod.method(obj) let _: Bool = result // no-warning let _: () -> Bool = InstanceOrClassMethod.method(obj) } protocol Numeric { static func +(x: Self, y: Self) -> Self } func acceptBinaryFunc<T>(_ x: T, _ fn: (T, T) -> T) { } func testNumeric<T : Numeric>(_ x: T) { acceptBinaryFunc(x, +) } /* FIXME: We can't check this directly, but it can happen with multiple modules. class PropertyOrMethod { func member() -> Int { return 0 } let member = false class func methodOnClass(_ obj: PropertyOrMethod) -> Int { return 0 } let methodOnClass = false } func testPreferPropertyToMethod(_ obj: PropertyOrMethod) { let result = obj.member let resultChecked: Bool = result let called = obj.member() let calledChecked: Int = called let curried = obj.member as () -> Int let methodOnClass = PropertyOrMethod.methodOnClass let methodOnClassChecked: (PropertyOrMethod) -> Int = methodOnClass } */ struct Foo { var foo: Int } protocol ExtendedWithMutatingMethods { } extension ExtendedWithMutatingMethods { mutating func mutatingMethod() {} var mutableProperty: Foo { get { } set { } } var nonmutatingProperty: Foo { get { } nonmutating set { } } var mutatingGetProperty: Foo { mutating get { } set { } } } class ClassExtendedWithMutatingMethods: ExtendedWithMutatingMethods {} class SubclassExtendedWithMutatingMethods: ClassExtendedWithMutatingMethods {} func testClassExtendedWithMutatingMethods(_ c: ClassExtendedWithMutatingMethods, // expected-note* {{}} sub: SubclassExtendedWithMutatingMethods) { // expected-note* {{}} c.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'c' is a 'let' constant}} c.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}} c.mutableProperty.foo = 0 // expected-error{{cannot assign to property}} c.nonmutatingProperty = Foo(foo: 0) c.nonmutatingProperty.foo = 0 c.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}} c.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}} _ = c.mutableProperty _ = c.mutableProperty.foo _ = c.nonmutatingProperty _ = c.nonmutatingProperty.foo // FIXME: diagnostic nondeterministically says "member" or "getter" _ = c.mutatingGetProperty // expected-error{{cannot use mutating}} _ = c.mutatingGetProperty.foo // expected-error{{cannot use mutating}} sub.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'sub' is a 'let' constant}} sub.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}} sub.mutableProperty.foo = 0 // expected-error{{cannot assign to property}} sub.nonmutatingProperty = Foo(foo: 0) sub.nonmutatingProperty.foo = 0 sub.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}} sub.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}} _ = sub.mutableProperty _ = sub.mutableProperty.foo _ = sub.nonmutatingProperty _ = sub.nonmutatingProperty.foo _ = sub.mutatingGetProperty // expected-error{{cannot use mutating}} _ = sub.mutatingGetProperty.foo // expected-error{{cannot use mutating}} var mutableC = c mutableC.mutatingMethod() mutableC.mutableProperty = Foo(foo: 0) mutableC.mutableProperty.foo = 0 mutableC.nonmutatingProperty = Foo(foo: 0) mutableC.nonmutatingProperty.foo = 0 mutableC.mutatingGetProperty = Foo(foo: 0) mutableC.mutatingGetProperty.foo = 0 _ = mutableC.mutableProperty _ = mutableC.mutableProperty.foo _ = mutableC.nonmutatingProperty _ = mutableC.nonmutatingProperty.foo _ = mutableC.mutatingGetProperty _ = mutableC.mutatingGetProperty.foo var mutableSub = sub mutableSub.mutatingMethod() mutableSub.mutableProperty = Foo(foo: 0) mutableSub.mutableProperty.foo = 0 mutableSub.nonmutatingProperty = Foo(foo: 0) mutableSub.nonmutatingProperty.foo = 0 _ = mutableSub.mutableProperty _ = mutableSub.mutableProperty.foo _ = mutableSub.nonmutatingProperty _ = mutableSub.nonmutatingProperty.foo _ = mutableSub.mutatingGetProperty _ = mutableSub.mutatingGetProperty.foo } // <rdar://problem/18879585> QoI: error message for attempted access to instance properties in static methods are bad. enum LedModules: Int { case WS2811_1x_5V } extension LedModules { static var watts: Double { return [0.30][self.rawValue] // expected-error {{instance member 'rawValue' cannot be used on type 'LedModules'}} } } // <rdar://problem/15117741> QoI: calling a static function on an instance produces a non-helpful diagnostic class r15117741S { static func g() {} } func test15117741(_ s: r15117741S) { s.g() // expected-error {{static member 'g' cannot be used on instance of type 'r15117741S'}} } // <rdar://problem/22491394> References to unavailable decls sometimes diagnosed as ambiguous struct UnavailMember { @available(*, unavailable) static var XYZ : X { get {} } // expected-note {{'XYZ' has been explicitly marked unavailable here}} } let _ : [UnavailMember] = [.XYZ] // expected-error {{'XYZ' is unavailable}} let _ : [UnavailMember] = [.ABC] // expected-error {{type 'UnavailMember' has no member 'ABC'}} // <rdar://problem/22490787> QoI: Poor error message iterating over property with non-sequence type that defines an Iterator type alias struct S22490787 { typealias Iterator = AnyIterator<Int> } func f22490787() { var path: S22490787 = S22490787() for p in path { // expected-error {{type 'S22490787' does not conform to protocol 'Sequence'}} } } // <rdar://problem/23942743> [QoI] Bad diagnostic when errors inside enum constructor enum r23942743 { case Tomato(cloud: String) } let _ = .Tomato(cloud: .none) // expected-error {{reference to member 'Tomato' cannot be resolved without a contextual type}} // SR-650: REGRESSION: Assertion failed: (baseTy && "Couldn't find appropriate context"), function getMemberSubstitutions enum SomeErrorType { case StandaloneError case UnderlyingError(String) static func someErrorFromString(_ str: String) -> SomeErrorType? { if str == "standalone" { return .StandaloneError } if str == "underlying" { return .UnderlyingError } // expected-error {{member 'UnderlyingError' expects argument of type 'String'}} return nil } } // SR-2193: QoI: better diagnostic when a decl exists, but is not a type enum SR_2193_Error: Error { case Boom } do { throw SR_2193_Error.Boom } catch let e as SR_2193_Error.Boom { // expected-error {{enum element 'Boom' is not a member type of 'SR_2193_Error'}} } // rdar://problem/25341015 extension Sequence { func r25341015_1() -> Int { return max(1, 2) // expected-error {{use of 'max' refers to instance method 'max(by:)' rather than global function 'max' in module 'Swift'}} expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} } } class C_25341015 { static func baz(_ x: Int, _ y: Int) {} // expected-note {{'baz' declared here}} func baz() {} func qux() { baz(1, 2) // expected-error {{use of 'baz' refers to instance method 'baz()' rather than static method 'baz' in class 'C_25341015'}} expected-note {{use 'C_25341015.' to reference the static method}} } } struct S_25341015 { static func foo(_ x: Int, y: Int) {} // expected-note {{'foo(_:y:)' declared here}} func foo(z: Int) {} func bar() { foo(1, y: 2) // expected-error {{use of 'foo' refers to instance method 'foo(z:)' rather than static method 'foo(_:y:)' in struct 'S_25341015'}} expected-note {{use 'S_25341015.' to reference the static method}} } } func r25341015() { func baz(_ x: Int, _ y: Int) {} class Bar { func baz() {} func qux() { baz(1, 2) // expected-error {{argument passed to call that takes no arguments}} } } } func r25341015_local(x: Int, y: Int) {} func r25341015_inner() { func r25341015_local() {} r25341015_local(x: 1, y: 2) // expected-error {{argument passed to call that takes no arguments}} } // rdar://problem/32854314 - Emit shadowing diagnostics even if argument types do not much completely func foo_32854314() -> Double { return 42 } func bar_32854314() -> Int { return 0 } extension Array where Element == Int { func foo() { let _ = min(foo_32854314(), bar_32854314()) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}} // expected-error@-1 {{use of 'min' nearly matches global function 'min' in module 'Swift' rather than instance method 'min()'}} } func foo(_ x: Int, _ y: Double) { let _ = min(x, y) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}} // expected-error@-1 {{use of 'min' nearly matches global function 'min' in module 'Swift' rather than instance method 'min()'}} } func bar() { let _ = min(1.0, 2) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}} // expected-error@-1 {{use of 'min' nearly matches global function 'min' in module 'Swift' rather than instance method 'min()'}} } }
apache-2.0
3e30706cef0c341a5c69ab45bb91c059
27.381862
226
0.667423
3.626715
false
false
false
false
Hendrik44/pi-weather-app
Carthage/Checkouts/Charts/ChartsDemo-iOS/Swift/Components/BalloonMarker.swift
1
6753
// // BalloonMarker.swift // ChartsDemo-Swift // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import Charts #if canImport(UIKit) import UIKit #endif open class BalloonMarker: MarkerImage { open var color: UIColor open var arrowSize = CGSize(width: 15, height: 11) open var font: UIFont open var textColor: UIColor open var insets: UIEdgeInsets open var minimumSize = CGSize() fileprivate var label: String? fileprivate var _labelSize: CGSize = CGSize() fileprivate var _paragraphStyle: NSMutableParagraphStyle? fileprivate var _drawAttributes = [NSAttributedString.Key : Any]() public init(color: UIColor, font: UIFont, textColor: UIColor, insets: UIEdgeInsets) { self.color = color self.font = font self.textColor = textColor self.insets = insets _paragraphStyle = NSParagraphStyle.default.mutableCopy() as? NSMutableParagraphStyle _paragraphStyle?.alignment = .center super.init() } open override func offsetForDrawing(atPoint point: CGPoint) -> CGPoint { var offset = self.offset var size = self.size if size.width == 0.0 && image != nil { size.width = image!.size.width } if size.height == 0.0 && image != nil { size.height = image!.size.height } let width = size.width let height = size.height let padding: CGFloat = 8.0 var origin = point origin.x -= width / 2 origin.y -= height if origin.x + offset.x < 0.0 { offset.x = -origin.x + padding } else if let chart = chartView, origin.x + width + offset.x > chart.bounds.size.width { offset.x = chart.bounds.size.width - origin.x - width - padding } if origin.y + offset.y < 0 { offset.y = height + padding; } else if let chart = chartView, origin.y + height + offset.y > chart.bounds.size.height { offset.y = chart.bounds.size.height - origin.y - height - padding } return offset } open override func draw(context: CGContext, point: CGPoint) { guard let label = label else { return } let offset = self.offsetForDrawing(atPoint: point) let size = self.size var rect = CGRect( origin: CGPoint( x: point.x + offset.x, y: point.y + offset.y), size: size) rect.origin.x -= size.width / 2.0 rect.origin.y -= size.height context.saveGState() context.setFillColor(color.cgColor) if offset.y > 0 { context.beginPath() context.move(to: CGPoint( x: rect.origin.x, y: rect.origin.y + arrowSize.height)) context.addLine(to: CGPoint( x: rect.origin.x + (rect.size.width - arrowSize.width) / 2.0, y: rect.origin.y + arrowSize.height)) //arrow vertex context.addLine(to: CGPoint( x: point.x, y: point.y)) context.addLine(to: CGPoint( x: rect.origin.x + (rect.size.width + arrowSize.width) / 2.0, y: rect.origin.y + arrowSize.height)) context.addLine(to: CGPoint( x: rect.origin.x + rect.size.width, y: rect.origin.y + arrowSize.height)) context.addLine(to: CGPoint( x: rect.origin.x + rect.size.width, y: rect.origin.y + rect.size.height)) context.addLine(to: CGPoint( x: rect.origin.x, y: rect.origin.y + rect.size.height)) context.addLine(to: CGPoint( x: rect.origin.x, y: rect.origin.y + arrowSize.height)) context.fillPath() } else { context.beginPath() context.move(to: CGPoint( x: rect.origin.x, y: rect.origin.y)) context.addLine(to: CGPoint( x: rect.origin.x + rect.size.width, y: rect.origin.y)) context.addLine(to: CGPoint( x: rect.origin.x + rect.size.width, y: rect.origin.y + rect.size.height - arrowSize.height)) context.addLine(to: CGPoint( x: rect.origin.x + (rect.size.width + arrowSize.width) / 2.0, y: rect.origin.y + rect.size.height - arrowSize.height)) //arrow vertex context.addLine(to: CGPoint( x: point.x, y: point.y)) context.addLine(to: CGPoint( x: rect.origin.x + (rect.size.width - arrowSize.width) / 2.0, y: rect.origin.y + rect.size.height - arrowSize.height)) context.addLine(to: CGPoint( x: rect.origin.x, y: rect.origin.y + rect.size.height - arrowSize.height)) context.addLine(to: CGPoint( x: rect.origin.x, y: rect.origin.y)) context.fillPath() } if offset.y > 0 { rect.origin.y += self.insets.top + arrowSize.height } else { rect.origin.y += self.insets.top } rect.size.height -= self.insets.top + self.insets.bottom UIGraphicsPushContext(context) label.draw(in: rect, withAttributes: _drawAttributes) UIGraphicsPopContext() context.restoreGState() } open override func refreshContent(entry: ChartDataEntry, highlight: Highlight) { setLabel(String(entry.y)) } open func setLabel(_ newLabel: String) { label = newLabel _drawAttributes.removeAll() _drawAttributes[.font] = self.font _drawAttributes[.paragraphStyle] = _paragraphStyle _drawAttributes[.foregroundColor] = self.textColor _labelSize = label?.size(withAttributes: _drawAttributes) ?? CGSize.zero var size = CGSize() size.width = _labelSize.width + self.insets.left + self.insets.right size.height = _labelSize.height + self.insets.top + self.insets.bottom size.width = max(minimumSize.width, size.width) size.height = max(minimumSize.height, size.height) self.size = size } }
mit
30be5648efdad7827a5b5c737b5fbf72
31.311005
92
0.539464
4.30676
false
false
false
false
InsectQY/HelloSVU_Swift
HelloSVU_Swift/Classes/Expand/Tools/KingfisherExtension/KingfisherExtension.swift
1
4404
// // KingfisherExtension.swift // XMGTV // // Created by apple on 16/11/9. // Copyright © 2016年 coderwhy. All rights reserved. // import UIKit import Kingfisher extension UIImageView { func setImage(_ URLString: String?, _ placeHolderName: String? = nil,progress: ((_ receivedSize: Int64, _ totalSize: Int64) -> ())? = nil, completionHandler: ((_ image: Image?, _ error: NSError?, _ cacheType: CacheType, _ imageURL: URL?) -> ())? = nil) { guard let URLString = URLString else {return} guard let url = URL(string: URLString) else {return} guard let placeHolderName = placeHolderName else { kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) in progress?(receivedSize,totalSize) }) { (image, error, cacheType, imageURL) in completionHandler?(image, error, cacheType, imageURL) } return } kf.setImage(with: url, placeholder: UIImage(named: placeHolderName), options: nil, progressBlock: { (receivedSize, totalSize) in progress?(receivedSize,totalSize) }) { (image, error, cacheType, imageURL) in completionHandler?(image, error, cacheType, imageURL) } } func setImage(_ URLString: String?, _ placeHolderName: String? = nil) { setImage(URLString, placeHolderName, progress: nil, completionHandler: nil) } } extension UIButton { func setBackgroundImage(_ URLString: String?, _ placeHolderName: String? = nil, _ state:UIControlState = .normal ,progress: ((_ receivedSize: Int64, _ totalSize: Int64) -> ())? = nil, completionHandler: ((_ image: Image?, _ error: NSError?, _ cacheType: CacheType, _ imageURL: URL?) -> ())? = nil) { guard let URLString = URLString else {return} guard let url = URL(string: URLString) else {return} guard let placeHolderName = placeHolderName else { kf.setBackgroundImage(with: url, for: state, placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) in progress?(receivedSize,totalSize) }, completionHandler: { (image, error, cacheType, imageURL) in completionHandler?(image, error, cacheType, imageURL) }) return } kf.setBackgroundImage(with: url, for: state, placeholder: UIImage(named: placeHolderName), options: nil, progressBlock: { (receivedSize, totalSize) in progress?(receivedSize,totalSize) }, completionHandler: { (image, error, cacheType, imageURL) in completionHandler?(image, error, cacheType, imageURL) }) } func setBackgroundImage(_ URLString: String?, _ placeHolderName: String? = nil,_ state: UIControlState? = .normal) { setBackgroundImage(URLString, placeHolderName, state) } func setImage(_ URLString: String?, _ placeHolderName: String? = nil, _ state:UIControlState = .normal ,progress: ((_ receivedSize: Int64, _ totalSize: Int64) -> ())? = nil, completionHandler: ((_ image: Image?, _ error: NSError?, _ cacheType: CacheType, _ imageURL: URL?) -> ())? = nil) { guard let URLString = URLString else {return} guard let url = URL(string: URLString) else {return} guard let placeHolderName = placeHolderName else { kf.setImage(with: url, for: state, placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) in progress?(receivedSize,totalSize) }, completionHandler: { (image, error, cacheType, imageURL) in completionHandler?(image, error, cacheType, imageURL) }) return } kf.setImage(with: url, for: state, placeholder: UIImage(named: placeHolderName), options: nil, progressBlock: { (receivedSize, totalSize) in progress?(receivedSize,totalSize) }, completionHandler: { (image, error, cacheType, imageURL) in completionHandler?(image, error, cacheType, imageURL) }) } func setImage(_ URLString: String?, _ placeHolderName: String? = nil,_ state: UIControlState? = .normal) { setImage(URLString, placeHolderName, state) } }
apache-2.0
539b3f4f7f2803b73d698ce493ad5bfe
43.908163
303
0.613497
4.879157
false
false
false
false
modocache/swift
test/IRGen/meta_meta_type.swift
3
1499
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-build-swift %s -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s // RUN: %target-swift-frontend -primary-file %s -emit-ir | %FileCheck -check-prefix=CHECKIR %s // REQUIRES: executable_test protocol Proto { } struct Mystruct : Proto { } // CHECKIR-LABEL: define hidden {{.*}} @_TF14meta_meta_type6testitFPS_5Proto_PMPMPS0__ // CHECKIR: [[M1:%[0-9]+]] = call {{.*}} @swift_getDynamicType // CHECKIR: [[M2:%[0-9]+]] = call {{.*}} @swift_getMetatypeMetadata(%swift.type* [[M1]]) // CHECKIR: [[R1:%[0-9]+]] = insertvalue {{.*}} [[M2]] // CHECKIR: [[R2:%[0-9]+]] = insertvalue {{.*}} [[R1]] // CHECKIR: ret { %swift.type*, i8** } [[R2]] func testit(_ p: Proto) -> Proto.Type.Type { return type(of: type(of: p)) } // CHECKIR-LABEL: define hidden {{.*}} @_TF14meta_meta_type7testit2FPS_5Proto_PMPMPMPS0__ // CHECKIR: [[M1:%[0-9]+]] = call {{.*}} @swift_getDynamicType // CHECKIR: [[M2:%[0-9]+]] = call {{.*}} @swift_getMetatypeMetadata(%swift.type* [[M1]]) // CHECKIR: [[M3:%[0-9]+]] = call {{.*}} @swift_getMetatypeMetadata(%swift.type* [[M2]]) // CHECKIR: [[R1:%[0-9]+]] = insertvalue {{.*}} [[M3]] // CHECKIR: [[R2:%[0-9]+]] = insertvalue {{.*}} [[R1]] // CHECKIR: ret { %swift.type*, i8** } [[R2]] func testit2(_ p: Proto) -> Proto.Type.Type.Type { return type(of: type(of: type(of: p))) } var tt = testit(Mystruct()) var tt2 = testit2(Mystruct()) // CHECK: a.Mystruct.Type debugPrint(tt) // CHECK: a.Mystruct.Type.Type debugPrint(tt2)
apache-2.0
3d93a0b628157d4eb318bfc8e7584711
35.560976
94
0.594396
2.740402
false
true
false
false
3DprintFIT/octoprint-ios-client
OctoPhone/View Related/Slicing Profile/SlicingProfileView.swift
1
2024
// // SlicingProfileView.swift // OctoPhone // // Created by Josef Dolezal on 22/04/2017. // Copyright © 2017 Josef Dolezal. All rights reserved. // import UIKit import SnapKit import ReactiveSwift /// View for slicing profile detail class SlicingProfileView: UIView { // MARK: Public API /// Label for profile name text let nameLabel: UILabel = { let label = UILabel() label.font = UIFont.preferredFont(forTextStyle: .caption1) return label }() /// Actual profile name let nameTextField = UITextField() /// Label for profile description text let descriptionLabel: UILabel = { let label = UILabel() label.font = UIFont.preferredFont(forTextStyle: .caption1) return label }() /// Actual description text let descriptionTextView: UITextView = { let textView = UITextView() textView.isScrollEnabled = false textView.textContainerInset = .zero textView.textContainer.lineFragmentPadding = 0 textView.backgroundColor = nil textView.font = UIFont.preferredFont(forTextStyle: .body) return textView }() init() { super.init(frame: .zero) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Private properties // MARK: Initializers override func layoutSubviews() { super.layoutSubviews() let stackView = UIStackView(arrangedSubviews: [nameLabel, nameTextField, descriptionLabel, descriptionTextView], axis: .vertical) addSubview(stackView) stackView.spacing = 10 stackView.snp.makeConstraints { make in make.leading.trailing.top.equalToSuperview() make.width.equalToSuperview() make.bottom.greaterThanOrEqualTo(descriptionTextView.snp.bottom) } } // MARK: Internal logic }
mit
9b8c09824f67958e6d839eade7f610d1
23.975309
98
0.622343
5.337731
false
false
false
false
ccorrea/SaveDate
SaveDate/SaveDate/Models/Calendar.swift
1
2789
// // Calendar.swift // SaveDate // // Created by Christian Correa on 10/5/17. // Copyright © 2017 Twelfth Station Software. All rights reserved. // import Foundation struct Calendar { static let numberOfCells = 49 let calendar: Foundation.Calendar let date: Date let monthName: String private (set) lazy var cells: [Cell] = createCells() init(date: Date) { let dateFormatter = Calendar.createLocalizedDateFormatter() dateFormatter.setLocalizedDateFormatFromTemplate("MMMM") self.calendar = Foundation.Calendar.current self.date = date self.monthName = dateFormatter.string(from: date) } private func createCells() -> [Cell] { var cells = Array<Cell>() let dateFormatter = Calendar.createLocalizedDateFormatter() let range = calendar.range(of: .day, in: .month, for: date)! let firstDateComponents = DateComponents(year: date.year, month: date.month, day: 1) let firstDate = calendar.date(from: firstDateComponents)! let weekdaySymbols = dateFormatter.veryShortWeekdaySymbols! var delta = firstDate.weekday - 1 for weekdaySymbol in weekdaySymbols { let symbolCell = SymbolCell(name: weekdaySymbol) cells.append(symbolCell) } while delta > 0 { let operand = delta * -1 let currentDate = calendar.date(byAdding: .day, value: operand, to: firstDate)! let currentDay = DayCell(date: currentDate, inMonth: false) cells.append(currentDay) delta -= 1 } for index in 1 ... range.count { let currentDateComponents = DateComponents(year: date.year, month: date.month, day: index) let currentDate = calendar.date(from: currentDateComponents)! let currentDay = DayCell(date: currentDate) cells.append(currentDay) } while cells.count < Calendar.numberOfCells { if let lastCell = cells.last { if let lastDayCell = lastCell as? DayCell { let lastDate = lastDayCell.date let nextDate = calendar.date(byAdding: .day, value: 1, to: lastDate)! let nextDayCell = DayCell(date: nextDate, inMonth: false) cells.append(nextDayCell) } } } return cells } private static func createLocalizedDateFormatter() -> DateFormatter { let dateFormatter = DateFormatter() dateFormatter.locale = Locale.current return dateFormatter } }
mit
26e4fb22bb11754bdace4cf96dd6bfc0
31.8
102
0.581062
5.059891
false
false
false
false
tomesm/ShinyWeather
ShinyWeather/WeatherCell.swift
1
782
// // WeatherCell.swift // ShinyWeather // // Created by martin on 28/09/2017. // Copyright © 2017 Martin Tomes. All rights reserved. // import UIKit class WeatherCell: UITableViewCell { @IBOutlet weak var weatherIcon: UIImageView! @IBOutlet weak var dayLbl: UILabel! @IBOutlet weak var weatherTypeLbl: UILabel! @IBOutlet weak var highTempLbl: UILabel! @IBOutlet weak var lowTempLbl: UILabel! func configureCell(forecast: Forecast) { lowTempLbl.text = "\(forecast.lowTemp)" highTempLbl.text = "\(forecast.highTemp)" weatherTypeLbl.text = forecast.weatherType dayLbl.text = forecast.date // name of the type is name of the image weatherIcon.image = UIImage(named: forecast.weatherType) } }
mit
945aeec69eaac4349a3172bbac3f4ae9
27.925926
64
0.678617
4.067708
false
false
false
false
alexsanderskywork/Test-List-View
Test List View/AppDelegate.swift
1
6122
// // AppDelegate.swift // Test List View // // Created by Alexsander on 10/30/15. // Copyright © 2015 Alexsander Khitev. 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 "Alexsander-Khitev.Test_List_View" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Test_List_View", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
apache-2.0
41a55897796f360e33a200dc395ff31f
54.144144
291
0.719817
5.835081
false
false
false
false
abdullahwaseer/NetworkBase
NetworkBase/Classes/Response/Response.swift
1
707
// // Response.swift // TcigPlatformMobile // // Created by M Abdullah Waseer on 17/05/2017. // Copyright © 2017 M Abdullah Waseer. All rights reserved. // import Foundation public enum ResponseType : Int { case Success case Failure } open class Response { public var status : ResponseType = .Failure //private(set) public var data : AnyObject? public init(data : [String : Any]?,parser : ParserBase) { let status = data?["status"] as? Int if let s = status { self.status = (s == 200 || s == 201) ? .Success : .Failure } if let d = data { self.data = parser.parseData(data: d) } } }
mit
2a311cfef2fb3db18c6801487c13a2d1
21.0625
70
0.567989
3.857923
false
false
false
false
cwaffles/Soulcast
Soulcast/SoulRecorder.swift
1
6076
import UIKit import AVFoundation import TheAmazingAudioEngine let audioController = AEAudioController(audioDescription: AEAudioController.nonInterleaved16BitStereoAudioDescription(), inputEnabled: true) enum FileReadWrite { case read case write } enum RecorderState { case standby // 0 case recordingStarted case recordingLongEnough // 2 case paused case failed // 4 case finished // 5 case unknown // 6 case err } protocol SoulRecorderDelegate: class { func soulDidStartRecording() func soulIsRecording(_ progress:CGFloat) func soulDidFinishRecording(_ newSoul: Soul) func soulDidFailToRecord() func soulDidReachMinimumDuration() } class SoulRecorder: NSObject { let minimumRecordDuration:Int = 1 var maximumRecordDuration:Int = 5 var currentRecordingPath:String! var displayLink:CADisplayLink! var displayCounter:Int = 0 var recorder:AERecorder? weak var delegate:SoulRecorderDelegate? //records and spits out the url var state: RecorderState = .standby{ didSet{ switch (oldValue, state){ case (.standby, .recordingStarted): break case (.recordingStarted, .recordingLongEnough): break case (.recordingStarted, .failed): break case (.recordingLongEnough, .failed): assert(false, "Should not be here!!") case (.recordingLongEnough, .finished): break case (.failed, .standby): break case (.finished, .standby): break case (let x, .err): print("state x.hashValue: \(x.hashValue)") default: print("oldValue: \(oldValue.hashValue), state: \(state.hashValue)") assert(false, "OOPS!!!") } } } override init() { super.init() setup() } func setup() { displayLink = CADisplayLink(target: self, selector: #selector(SoulRecorder.displayLinkFired(_:))) displayLink.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode) do { try audioController?.start() } catch { print("audioController.start() fail!") } } func displayLinkFired(_ link:CADisplayLink) { if state == .recordingStarted || state == .recordingLongEnough { displayCounter += 1 } if displayCounter == 60 * minimumRecordDuration { print("displayCounter == 60 * minimumRecordDuration") if state == .recordingStarted { minimumDurationDidPass() } } if displayCounter == 60 * maximumRecordDuration { print("displayCounter == 60 * maximumRecordDuration") if state == .recordingLongEnough { pleaseStopRecording() } displayCounter = 0 } if state == .recordingStarted || state == .recordingLongEnough { let currentRecordDuration = CGFloat(displayCounter) / 60 let progress:CGFloat = currentRecordDuration/CGFloat(maximumRecordDuration) self.delegate?.soulIsRecording(progress) } } func pleaseStartRecording() { print("pleaseStartRecording()") if SoulPlayer.playing { assert(false, "Should not be recording while audio is being played") } if state != .standby { assert(false, "OOPS!! Tried to start recording from an inappropriate state!") } else { startRecording() state = .recordingStarted } } func pleaseStopRecording() { print("pleaseStopRecording()") if state == .recordingStarted { discardRecording() } else if state == .recordingLongEnough { saveRecording() } displayCounter = 0 } fileprivate func startRecording() { print("startRecording()") do { try audioController?.start() } catch { assert(true, "audioController start error") } recorder = AERecorder(audioController: audioController) currentRecordingPath = outputPath() do { try recorder?.beginRecordingToFile(atPath: currentRecordingPath, fileType: AudioFileTypeID(kAudioFileM4AType)) delegate?.soulDidStartRecording() } catch { print("OOPS! at startRecording()") } audioController?.addOutputReceiver(recorder) audioController?.addInputReceiver(recorder) } fileprivate func minimumDurationDidPass() { print("minimumDurationDidPass()") state = .recordingLongEnough delegate?.soulDidReachMinimumDuration() } fileprivate func pauseRecording() { //TODO: } fileprivate func resumeRecording() { //TODO: } func outputPath() -> String { var outputPath:String! let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true) if paths.count > 0 { let randomNumberString = String(Date.timeIntervalSinceReferenceDate.description) print("randomNumberString: \(randomNumberString)") outputPath = paths[0] + "/Recording" + randomNumberString! + ".m4a" let manager = FileManager.default if manager.fileExists(atPath: outputPath) { do { try manager.removeItem(atPath: outputPath) } catch { print("outputPath(readOrWrite:FileReadWrite)") } } } return outputPath } fileprivate func discardRecording() { print("discardRecording") state = .failed recorder?.finishRecording() resetRecorder() delegate?.soulDidFailToRecord() } fileprivate func saveRecording() { print("saveRecording") state = .finished recorder?.finishRecording() let newSoul = Soul() newSoul.localURL = currentRecordingPath delegate?.soulDidFinishRecording(newSoul) resetRecorder() } fileprivate func resetRecorder() { print("resetRecorder") state = .standby audioController?.removeOutputReceiver(recorder) audioController?.removeInputReceiver(recorder) recorder = nil } static func askForMicrophonePermission(_ success:@escaping ()->(), failure:@escaping ()->()) { //TODO: AVAudioSession.sharedInstance().requestRecordPermission { (granted) in if granted { success() } else { failure() } } } }
mit
ed10560391fc7cf833ebdb53d49330d5
27.392523
155
0.673469
4.655939
false
false
false
false
teaxus/TSAppEninge
Source/Basic/View/BasicView/TSBasicTextView.swift
1
3881
// // TSBasicTextView.swift // TSAppEngine // // Created by teaxus on 15/12/14. // Copyright © 2015年 teaxus. All rights reserved. // import UIKit public typealias TSTextViewFinishEdit = (_ textview:UITextView,_ message:String)->Void public class TSBasicTextView: UITextView { var blockFinishEdit:TSTextViewFinishEdit? public var int_line:Int=1//行数 public var max_char:Int=Int.max//最大输入 public func BlockFinishEdit(action:@escaping TSTextViewFinishEdit){ blockFinishEdit=action } public var placeHolder:String = ""{ didSet{ updatePlaceHolder() } } override public var text:String!{ set(newValue){ super.text = newValue updatePlaceHolder() } get{ return super.text } } public var label_place = UILabel() public var size_design = CGSize(width:Screen_width,height:Screen_height){ didSet{ self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.size.width, height: self.frame.size.height) } } override public var frame:CGRect{ set(newValue){ super.frame = CGRect(x:newValue.origin.x/Screen_width*size_design.width, y:newValue.origin.y/Screen_height*size_design.height, width:newValue.size.width/Screen_width*size_design.width, height:newValue.size.height/Screen_height*size_design.height) } get{ return super.frame } } func initializer(){ #if swift(>=2.2) NotificationCenter.default.addObserver(self, selector: #selector(self.textviewdDidChange(noti:)), name: NSNotification.Name.UITextViewTextDidChange, object: nil) #else NSNotificationCenter.defaultCenter().addObserver(self, selector: "textviewdDidChange:", name: UITextViewTextDidChangeNotification, object: nil) #endif } override public init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) initializer() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initializer() self.tintColor = UIColor.clear } public override func layoutSubviews() { super.layoutSubviews() updatePlaceHolder() } deinit{ NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UITextViewTextDidChange, object: nil) } //MARK:textview在改变的时候 func textviewdDidChange(noti:NSNotification){ let textview = noti.object as? TSBasicTextView var string_message = "" if textview != nil{ if textview!.text.length > textview!.max_char{ textview?.text = textview?.text[0..<(textview!.max_char-1)] string_message = "超出范围" } updatePlaceHolder() if textview?.blockFinishEdit != nil{ textview!.blockFinishEdit!(textview!,string_message) } } } func updatePlaceHolder(){ if self.text.length == 0{ label_place.font = self.font label_place.numberOfLines = 0 label_place.text = placeHolder label_place.textColor = UIColor.lightGray label_place.sizeToFit() let height = StringManage.textViewHeightForText(text: placeHolder, width: self.frame.size.width, font: self.font) label_place.frame = CGRect(x: 2.5, y: 0, width: self.frame.size.width, height: height) label_place.isUserInteractionEnabled = false self.addSubview(label_place) } else{ label_place.removeFromSuperview() } } }
mit
d928687829cee5774fd9f056c717d329
31.59322
173
0.612064
4.514085
false
false
false
false
BeanstalkData/beanstalk-ios-sdk
BeanstalkEngageiOSSDK/Classes/Model/BEStore.swift
1
3804
// // BEStore.swift // Pods // // Created by Pavel Dvorovenko on 1/12/17. // // import Foundation import ObjectMapper public class BEStore : Mappable { private static let kId = "BEStore_id" private static let kCustomerId = "BEStore_customerId" private static let kDate = "BEStore_date" private static let kStoreId = "BEStore_storeId" private static let kCountry = "BEStore_country" private static let kAddress1 = "BEStore_address1" private static let kCity = "BEStore_city" private static let kState = "BEStore_state" private static let kZip = "BEStore_zip" private static let kPhone = "BEStore_phone" private static let kLongitude = "BEStore_longitude" private static let kLatitude = "BEStore_latitude" private static let kGeoEnabled = "BEStore_geoEnabled" private static let kPaymentLoyaltyParticipation = "BEStore_paymentLoyaltyParticipation" // private static let kStoreName = "_storeName" // private static let kAddress2 = "_address2" // private static let kFax = "_fax" // private static let kConcept = "_concept" // private static let kVenue = "_venue" // private static let kSubVenue = "_subVenue" // private static let kRegion = "_region" // private static let kRegionName = "_regionName" public var id: String? public var customerId: String? public var openDate: NSDate? public var storeId: String? public var country: String? public var address1: String? public var city: String? public var state: String? public var zip: Int? public var phone: String? public var longitude: String? public var latitude: String? public var geoEnabled: Bool? public var paymentLoyaltyParticipation: Bool? // public var storeName: String? // public var address2: String? // public var fax: String? // public var concept: String? // public var venue: String? // public var subVenue: String? // public var region: String? // public var regionName: String? public init(id: String){ self.id = id } required public init?(_ map: Map) { self.mapping(map) } public func getStoreName() -> String { let storeName = "Store" + (self.storeId != nil ? " #\(storeId!)" : "") return storeName } public func mapping(map: Map) { var idDict: Dictionary<String, String>? idDict <- map["_id"] if idDict != nil { id = idDict!["$id"] } var openDateDict: Dictionary<String, Double>? openDateDict <- map["OpenDate"] if openDateDict != nil { let sec = openDateDict!["sec"] let usec = openDateDict!["usec"] if (sec != nil && usec != nil) { let timeInterval: Double = sec! + usec! / 1000000.0 self.openDate = NSDate(timeIntervalSince1970: timeInterval) } } customerId <- map["CustomerId"] storeId <- map["StoreId"] city <- map["City"] longitude <- map["Longitude"] latitude <- map["Latitude"] address1 <- map["Address1"] zip <- map["Zip"] state <- map["State"] country <- map["Country"] phone <- map["Phone"] var geoEnabledNumber: String? geoEnabledNumber <- map["geoEnabled"] if (geoEnabledNumber != nil) { geoEnabled = (Int(geoEnabledNumber!) != 0) } var paymentLoyaltyParticipationNumber: NSNumber? paymentLoyaltyParticipationNumber <- map["PaymentLoyaltyParticipation"] if (paymentLoyaltyParticipationNumber != nil) { paymentLoyaltyParticipation = paymentLoyaltyParticipationNumber?.boolValue } // storeName <- map["StoreName"] // address2 <- map["Address2"] // fax <- map["Fax"] // concept <- map["Concept"] // venue <- map["Venue"] // subVenue <- map["SubVenue"] // region <- map["Region"] // regionName <- map["RegionName"] } }
mit
b9f155004ae4303bca7b0b34dd0998b1
28.71875
89
0.649842
3.893552
false
false
false
false
mleiv/KeyboardUtility
KeyboardUtilityDemo/KeyboardUtilityDemo/KeyboardUtility.swift
2
25357
// // KeyboardUtility.swift // // Copyright 2015 Emily Ivie // Licensed under The MIT License // For full copyright and license information, please see the LICENSE.txt // Redistributions of files must retain the above copyright notice. import UIKit //MARK: KeyboardUtilityDelegate Protocol /** Delegate Protocol for implementing KeyboardUtility Required: properties view and textFields */ @objc public protocol KeyboardUtilityDelegate{ //NOTE: @objc required to use optional, and then I can't use any swift-specific types (like Bool? or custom enums, sigh) /** Return all form text fields (needed for processing Next/Done according to tag index) - returns: an array of UITextField objects */ var textFields: [UITextField] { get } //expects field "tag" indexes to order Next/Done /** Processes form when final field (field not marked "Next") is finished. */ optional func submitForm() //https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextFieldDelegate_Protocol/#//apple_ref/occ/intfm/UITextFieldDelegate/ /** Asks the delegate if editing should begin in the specified text field. - parameter textField: The text field for which editing is about to begin. - returns: true if an editing session should be initiated; otherwise, false to disallow editing. */ optional func textFieldShouldBeginEditing(textField:UITextField) -> Bool /** Tells the delegate that editing began for the specified text field. (Redirects UITextFieldDelegate back to KeyboardUtilityDelegate so it can share use of this function) - parameter textField: The text field for which an editing session began. */ optional func textFieldDidBeginEditing(textField:UITextField) /** Asks the delegate if editing should stop in the specified text field. VALIDATE FIELD VALUES HERE. - parameter textField: The text field for which editing is about to end. - returns: true if editing should stop; otherwise, false if the editing session should continue */ optional func textFieldShouldEndEditing(textField:UITextField) -> Bool /** Tells the delegate that editing stopped for the specified text field. (Redirects UITextFieldDelegate back to KeyboardUtilityDelegate so it can share use of this function) - parameter textField: The text field for which editing ended. */ optional func textFieldDidEndEditing(textField:UITextField) /** Asks the delegate if the specified text should be changed. - parameter textField: The text field containing the text. - parameter range: The range of characters to be replaced - parameter string: The replacement string. - returns: true if the specified text range should be replaced; otherwise, false to keep the old text. */ optional func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool /** Asks the delegate if the text field’s current contents should be removed. - parameter textField: The text field containing the text. - returns: true if the text field’s contents should be cleared; otherwise, false. */ optional func textFieldShouldClear(textField:UITextField) -> Bool /** Asks the delegate if the text field should process the pressing of the return button. Overrides/blocks KeyboardUtility from handling textFieldShouldReturn() - parameter textField: The text field whose return button was pressed. - returns: true if the text field should implement its default behavior for the return button; otherwise, false. */ optional func textFieldShouldReturnInstead(textField:UITextField) -> Bool /** Asks the delegate if the text field should process the pressing of the return button. (Redirects UITextFieldDelegate back to KeyboardUtilityDelegate so it can share use of this function) - parameter textField: The text field whose return button was pressed. - returns: true if the text field should implement its default behavior for the return button; otherwise, false. */ optional func textFieldShouldReturn(textField:UITextField) -> Bool } //MARK: KeyboardUtility Class /** Extension to UIView/Controller to better manage text field/keyboard things. Automates next/done based on tag index. Moves text fields up when keyboard is shown, so they stay visible. - init(delegate: self) - start(): call *AFTER* view has been added to view hierarchy - stop(): lets go of all the keyboard tracking listeners */ public class KeyboardUtility: NSObject, UITextFieldDelegate, UIScrollViewDelegate { public var delegate: KeyboardUtilityDelegate? /** Allows a UITableViewController to use other keyboard utilities without using the keyboard shift (since table view has its own built-in version) */ public var dontShiftForKeyboard = false /** Amount of space between field bottom and keyboard. */ public var keyboardPadding: CGFloat = 0 /** Amount of time to delay shifting window. */ public var animationDelay: NSTimeInterval = 0.2 // calculated at keyboard display or field edit: private weak var topController: UIViewController? private var currentField: UITextField? private var keyboardTop: CGFloat? private var isTableView = false // some placement values to save so things go back to normal when keyboard closed private var onloadOrigin: CGPoint? private var startingOrigin: CGPoint? private var offsetY: CGFloat { if topController?.view == nil || startingOrigin == nil { return 0 } return startingOrigin!.y - topController!.view.frame.origin.y } private var offsetX: CGFloat { if topController?.view == nil || startingOrigin == nil { return 0 } return startingOrigin!.x - topController!.view.frame.origin.x } private var scrollViewOriginalValues = [(UIView, CGPoint, UIEdgeInsets)]() // short-term storage to correct for bad apple autoscroll (use KBScrollView for better results) private var scrollViewLastSetValues = [(UIView, CGPoint, UIEdgeInsets)]() // track if keyboard utility is on private var isRunning = false init(delegate myDelegate:KeyboardUtilityDelegate) { self.delegate = myDelegate } //MARK: Listeners /** Begins listening for keyboard show/hide events and registers for UITextField events. */ public func start() { isRunning = true topController = topViewController() onloadOrigin = topController?.view.frame.origin registerForKeyboardNotifications() setTextFieldDelegates() } /** Stops listening to keyboard show/hide events. */ public func stop() { isRunning = false deregisterFromKeyboardNotifications() } /** Sets up keyboard event listeners for show/hide */ private func registerForKeyboardNotifications() { if dontShiftForKeyboard { return } let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: "keyboardWillBeShown:", name: UIKeyboardDidShowNotification, object: nil) notificationCenter.addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil) notificationCenter.addObserver(self, selector: "keyboardWasHidden:", name: UIKeyboardDidHideNotification, object: nil) } /** Removes keyboard event listeners for show/hide */ private func deregisterFromKeyboardNotifications() { if dontShiftForKeyboard { return } let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.removeObserver(self, name: UIKeyboardDidShowNotification, object: nil) notificationCenter.removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) notificationCenter.removeObserver(self, name: UIKeyboardDidHideNotification, object: nil) } //MARK: UITextFieldDelegate implementation /** Sets up text field delegate to be self, for every text field sent from KeyboardUtilityDelegate */ private func setTextFieldDelegates() { if let textFields = delegate?.textFields{ for textField in textFields { textField.delegate = self } } } /** DELEGATE FUNCTION Triggered by listener to text field events. Saves initial positioning data for returning to that state when keyboard is closed. Allows KeyboardUtilityDelegate control in textFieldShouldBeginEditing() */ public func textFieldShouldBeginEditing(textField:UITextField) -> Bool { //do this before keyboard is opened or anything else is called: saveInitialValues(textField as UIView) if let result = delegate?.textFieldShouldBeginEditing?(textField) { return result } return true } /** DELEGATE FUNCTION Triggered by listener to text field events. Tracks field being edited and calls a second shiftWindowUp() - in addition to the one in the keyboard event listeners - to always keep current text field above keyboard. Allows KeyboardUtilityDelegate control in textFieldDidBeginEditing() */ public func textFieldDidBeginEditing(textField: UITextField) { if currentField != textField { let priorCurrentField = (currentField != nil) currentField = textField if priorCurrentField { animateWindowShift() } // else leave to keyboard opener } delegate?.textFieldDidBeginEditing?(textField) } /** DELEGATE FUNCTION Triggered by listener to text field events. Allows KeyboardUtilityDelegate control in textFieldShouldEndEditing() */ public func textFieldShouldEndEditing(textField:UITextField) -> Bool { if let result = delegate?.textFieldShouldEndEditing?(textField) { return result } return true } /** DELEGATE FUNCTION Triggered by listener to text field events. Allows KeyboardUtilityDelegate control in textFieldDidEndEditing() */ public func textFieldDidEndEditing(textField:UITextField) { delegate?.textFieldDidEndEditing?(textField) } /** DELEGATE FUNCTION Triggered by listener to text field events. Allows KeyboardUtilityDelegate control in textField() */ public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if let result = delegate?.textField?(textField, shouldChangeCharactersInRange: range, replacementString: string) { return result } return true } /** DELEGATE FUNCTION Triggered by listener to text field events. Allows KeyboardUtilityDelegate control in textFieldShouldClear() */ public func textFieldShouldClear(textField:UITextField) -> Bool { if let result = delegate?.textFieldShouldClear?(textField) { return result } return true } /** DELEGATE FUNCTION Triggered by listener to text field events. Handles Next/Done behavior on fields according to tag index. Allows KeyboardUtilityDelegate control in textFieldShouldReturn() and textFieldShouldReturnInstead() */ public func textFieldShouldReturn(textField:UITextField) -> Bool { var finalResult = true if let result = delegate?.textFieldShouldReturnInstead?(textField) { // instead of KeyboardUtility: return result } if let result = delegate?.textFieldShouldReturn?(textField) { // in addition to KeyboardUtility (could run validation here): finalResult = result } let view = topController?.view if textField.returnKeyType == .Next { var next = view?.viewWithTag(textField.tag + 1) as UIResponder? if next == nil { // try looping back up to field #1 next = view?.viewWithTag(1) as UIResponder? } next?.becomeFirstResponder() } else { textField.resignFirstResponder() delegate?.submitForm?() } return finalResult } //MARK: Keyboard show/hide calculations /** Triggered by listener to keyboard events. Sets keyboard size values for later calculations. */ internal func keyboardWillBeShown (notification: NSNotification) { if let userInfo = notification.userInfo { let keyboardSize = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue.size var keyboardHeight = CGFloat(keyboardSize?.height ?? 0) keyboardTop = keyboardHeight + keyboardPadding if currentField != nil { animateWindowShift() } } } /** Triggered by listener to keyboard events. Restores positioning to state before keyboard opened. */ internal func keyboardWillBeHidden (notification: NSNotification) { restoreInitialValues() currentField = nil } /** Triggered by listener to keyboard events. Restores positioning to state before keyboard opened. */ internal func keyboardWasHidden (notification: NSNotification) { restoreInitialScrollableValues(true) // scroll views are stubborn: force them to be the right value currentField = nil } /** Animates the window sliding up to look nicer. Also forces any scroll views we didn't fix to behave properly. */ private func animateWindowShift() { if dontShiftForKeyboard { return } // Reset all the base scroll view values or we will start seeing black bars of unknown source: for values in scrollViewOriginalValues { setScrollableValues(values) } //there is a bit of a lag where a black bar below top view appears before keyboard does, so teeny delay helps: UIView.animateWithDuration(animationDelay, animations: { [weak self]() in self?.scrollViewLastSetValues = [] //reset self?.shiftWindowUp() }, completion: { [weak self](finished) in // wrestle positoning control from Apple for scroll views. Better solution: use KBScrollView class and this won't be called. for values in self!.scrollViewLastSetValues { self?.setScrollableValues(values) } }) } /** Moves the main window up to keep the field being edited above the keyboard. If this is called when shifting between fields (like with Next), then it only moves the field up/down the minimum amount required to keep it above the keyboard. */ private func shiftWindowUp() { if currentField == nil || topController?.view == nil || keyboardTop == nil { return } // calculate necessary height adjustment (minus scroll adjustments): let fieldHeight = currentField!.bounds.height + keyboardPadding var lastView = currentField as UIView? var bottom = fieldHeight while let view = lastView { bottom += view.frame.origin.y if let scrollableView = view as? UITableView ?? view as? UIScrollView { // note: we've already accounted for frame origin y above // now we just need to make sure field is within visible scroll area // and adjust bottom to account for scrolled area var savedInset = scrollableView.contentInset var savedOffset = scrollableView.contentOffset let scrollTopY = savedOffset.y + savedInset.top let scrollBottomY = scrollTopY + scrollableView.bounds.height - savedInset.top let overage: CGFloat = { if bottom - fieldHeight < scrollTopY { // content above current top return (bottom - fieldHeight) - scrollTopY } else if bottom > scrollBottomY { // content below current bottom return bottom - scrollBottomY } return CGFloat(0) }() if overage != 0 { savedOffset.y += overage savedInset.top -= overage } // because scroll happens automatically on UITextField selection, decide if we need to set values now or AFTER autoscroll (the wrong scroll) happens: if doesntNeedForcedPositioning(view) { setScrollableValues((view: view, offset: savedOffset, inset: savedInset), animated: true) } else { //the painful route of repeatedly forcing offset/inset scrollViewLastSetValues.append((scrollableView, savedOffset, savedInset)) } bottom -= savedOffset.y } if view == topController?.view { break } lastView = view.superview } // now, move main frame up if necessary: let distanceToKeyboardTop = topController!.view.bounds.height - keyboardTop! let newOffset = distanceToKeyboardTop - bottom if newOffset != 0 { // don't go too far though, or we will see a black bar of nothingness: topController!.view.frame.origin.y = min(startingOrigin?.y ?? 0, topController!.view.frame.origin.y + newOffset) } } //MARK: Scrolling Corrections /** Because some scroll views might be in one field's hierarchy but not another's, this allows us to add any new scroll views that might have showed up between "Next" fields. - parameter scrollView: The view to add if it is not already in the list */ private func addUniqueToScrollOriginals(view: UIView) { for (existingView, offset, inset) in scrollViewOriginalValues { if existingView == view { return } } if let scrollableView = view as? UITableView ?? view as? UIScrollView { scrollViewOriginalValues.append((scrollableView, scrollableView.contentOffset, scrollableView.contentInset)) } } /** Saves original placement state of any views that might be altered - parameter fromView: the initial view to begin looking in (goes up the hierarchy, so start with the field if possible) */ private func saveInitialValues(fromView: UIView? = nil) { if startingOrigin == nil { startingOrigin = topController?.view.frame.origin } var view = fromView while view != nil { if let scrollableView = view as? UITableView ?? view as? UIScrollView { addUniqueToScrollOriginals(scrollableView) } if view == topController?.view { break } view = view?.superview } } /** Restores original placement state of any views that might have been altered */ private func restoreInitialValues() { // reset top frame offset to saved value: if startingOrigin != nil && topController != nil { topController!.view.frame.origin = startingOrigin! startingOrigin = nil } restoreInitialScrollableValues() } /** Restores just the saved scroll views' placement. This runs twice if we aren't using our subclassed scroll elements to disable autoscrolling. - parameter isFinal: If true, erases the list of saved positioning values when done */ private func restoreInitialScrollableValues(isFinal: Bool = false) { // reset scroll views to saved values: var runTwice = false for values in scrollViewOriginalValues { setScrollableValues(values, animated: true) if !doesntNeedForcedPositioning(values.0) { runTwice = true } } if !runTwice || isFinal { scrollViewOriginalValues = [] } } /** Checks to see if the view is one of our subclassed scroll elements to disable autoscrolling. - parameter view: the scrollable view */ private func doesntNeedForcedPositioning(view: UIView) -> Bool { return view is KBScrollView || view is KBTableView } /** Stops all offset-related autoscrolling animations on the element in question - parameter view: the scrollable view */ private func stopScroll(view: UIView) { if let scrollableView = view as? UITableView ?? view as? UIScrollView { var offset = scrollableView.contentOffset offset.x -= 1.0; offset.y -= 1.0 scrollableView.setContentOffset(offset, animated: false) offset.x += 1.0; offset.y += 1.0 scrollableView.setContentOffset(offset, animated: false) } } /** Sets the inset/offset values of a scrollable element if they have changed. Stops any existing autoscrolling animations if this is an autoscrolling element. - parameter values: a tuple of view, offset, and inset - parameter animated: true if the offset should be set to animate its changed value */ private func setScrollableValues(values: (view: UIView, offset: CGPoint, inset: UIEdgeInsets), var animated: Bool = false) { // reset scroll views to saved values: if let scrollableView = values.view as? UITableView ?? values.view as? UIScrollView { if !doesntNeedForcedPositioning(scrollableView) { stopScroll(scrollableView) animated = false } if scrollableView.contentInset.top != values.inset.top || scrollableView.contentInset.bottom != values.inset.bottom { scrollableView.contentInset = values.inset scrollableView.scrollIndicatorInsets = values.inset } if scrollableView.contentOffset.y != values.offset.y { scrollableView.setContentOffset(values.offset, animated: animated) } } } //MARK: Top ViewController /** Locates the top-most view controller that is under the tab/nav controllers - parameter topController: (optional) view controller to start looking under, defaults to window's rootViewController - returns: an (optional) view controller */ private func topViewController(_ topController: UIViewController? = nil) -> UIViewController? { let controller: UIViewController? = { if let controller = topController ?? UIApplication.sharedApplication().keyWindow?.rootViewController { return controller } else if let window = UIApplication.sharedApplication().delegate?.window { //this is only called if window.makeKeyAndVisible() didn't happen...? return window?.rootViewController } return nil }() if let tabController = controller as? UITabBarController, let nextController = tabController.selectedViewController { return topViewController(nextController) } else if let navController = controller as? UINavigationController, let nextController = navController.visibleViewController { return topViewController(nextController) } else if let nextController = controller?.presentedViewController { return topViewController(nextController) } return controller } } //MARK: Subclasses Disabling Autoscroll /** A UIScrollView with disabled autoscroll behavior */ class KBScrollView: UIScrollView { // Stops scroll view from trying to autoscroll on keyboard events override func scrollRectToVisible(rect: CGRect, animated: Bool) { //nothing } } /** A UITableView with (mostly) disabled autoscroll behavior */ class KBTableView: UITableView { // Stops scroll view from trying to autoscroll on keyboard events override func scrollToRowAtIndexPath(indexPath: NSIndexPath, atScrollPosition scrollPosition: UITableViewScrollPosition, animated: Bool) { //nothing } override func scrollToNearestSelectedRowAtScrollPosition(scrollPosition: UITableViewScrollPosition, animated: Bool) { //nothing } override func scrollRectToVisible(rect: CGRect, animated: Bool) { //nothing } }
mit
1be376dd95957caf184db861d049bdc4
40.428105
178
0.651836
5.604111
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/Splash/QSSplashScreen.swift
1
7342
// // QSSplashScreen.swift // zhuishushenqi // // Created by yung on 2017/6/8. // Copyright © 2017年 QS. All rights reserved. // import UIKit import RxSwift import RxCocoa typealias SplashCallback = ()->Void class QSSplashScreen: NSObject { var splashInfo:[String:Any] = [:] var subject:PublishSubject<Any>! private var splashRootVC:QSSplashViewController? private var remainDelay:Int = 3 private var shouldHidden:Bool = true private let splashInfoKey = "splashInfoKey" private let splashImageNameKey = "splashImageNameKey" var completion:SplashCallback? private let splashURL = "http://api.zhuishushenqi.com/splashes/ios" func show(completion:@escaping SplashCallback){ self.completion = completion let subject = PublishSubject<Any>() self.subject = subject detachRootViewController() let splashWindoww = UIWindow(frame: UIScreen.main.bounds) splashWindoww.backgroundColor = UIColor.black splashRootVC = QSSplashViewController() splashRootVC?.finishCallback = { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.showSplash), object: nil) self.subject.onNext(true) self.hide() } splashRootVC?.view.backgroundColor = UIColor.clear splashWindoww.rootViewController = splashRootVC splashWindow = splashWindoww splashWindow?.makeKeyAndVisible() getSplashInfo() } func getSplashInfo(){ QSLog("info:\(String(describing: USER_DEFAULTS.object(forKey: splashInfoKey)))") // first check network, load image from disk,if not reachable if Reachability(hostname: IMAGE_BASEURL)?.isReachable == false { let path = "/ZSSQ/Splash" if let dict = ZSCacheHelper.shared.cachedObj(for: splashInfoKey, cachePath: path) as? [String:Any] { let splashInfo = dict // image not exist,skip // searchPah exchange everytime you run your app let imageName = splashInfo[splashImageNameKey] as? String ?? "" let imagePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first?.appending("/\(imageName)") ?? "" let image = UIImage(contentsOfFile: imagePath) if let splashImage = image { self.perform(#selector(self.showSplash), with: nil, afterDelay: 1.0) self.splashRootVC?.setSplashImage(image: splashImage) }else{ hide() } } else { hide() } return } // request splash image // QSNetwork.request(splashURL) { (response) in // let splash = response.json?["splash"] as? [[String:Any]] // if (splash?.count ?? 0) > 0{ // if let splashInfo = splash?[0] { // // save splash info,download image and save it // self.splashInfo = splashInfo // self.downloadSplashImage() // }else{ // self.hide() // } // }else { // } // } self.hide() } func downloadSplashImage(){ let urlString = getSplashURLString() zs_download(url: urlString) { (response) in } // QSNetwork.download(urlString) { (fileURL, response, error) in // QSLog("\(fileURL?.path ?? "")") // let splashImage = UIImage(contentsOfFile: fileURL?.path ?? "") // self.splashInfo[self.splashImageNameKey] = fileURL?.lastPathComponent ?? "" // let path = "/ZSSQ/Splash" // ZSCacheHelper.shared.storage(obj: self.splashInfo, for: self.splashInfoKey, cachePath: path) // self.perform(#selector(self.showSplash), with: nil, afterDelay: 1.0) // if let image = splashImage { // self.splashRootVC?.setSplashImage(image: image) // } // } } @objc func showSplash(){ remainDelay -= 1 if remainDelay == 0 { hide() } self.perform(#selector(self.showSplash), with: nil, afterDelay: 1.0) } func getSplashURLString()->String { //according to screen dimension let imageString = self.splashInfo["img"] as? String ?? "" return imageString } func hide(){ if shouldHidden { shouldHidden = false attachRootViewController() splashWindow = nil if let completion = self.completion { completion() } } } } var originalRootViewController:UIViewController? var splashWindow:UIWindow? extension QSSplashScreen { func detachRootViewController(){ if originalRootViewController == nil { let mainWindow:UIWindow? = (UIApplication.shared.delegate?.window)! originalRootViewController = mainWindow?.rootViewController } } func attachRootViewController(){ if originalRootViewController != nil { let mainWindow:UIWindow? = (UIApplication.shared.delegate?.window)! mainWindow?.rootViewController = originalRootViewController } } } class QSSplashViewController: UIViewController { private var bgView:UIImageView! private var splashIcon:UIImageView! private var skipBtn:UIButton! var finishCallback:SplashCallback? override func viewDidLoad() { super.viewDidLoad() setupSubviews() } private func setupSubviews(){ bgView = UIImageView(frame: UIScreen.main.bounds) bgView.image = UIImage(named: getImageName()) view.addSubview(bgView) splashIcon = UIImageView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width , height: UIScreen.main.bounds.height - 100)) splashIcon.backgroundColor = UIColor.clear view.addSubview(splashIcon) skipBtn = UIButton(type: .custom) skipBtn.frame = CGRect(x: UIScreen.main.bounds.width - 80, y:UIScreen.main.bounds.height - 65, width: 60, height: 30) skipBtn.setTitle("跳过", for: .normal) skipBtn.setTitleColor(UIColor.gray, for: .normal) skipBtn.backgroundColor = UIColor(white: 0.0, alpha: 0.1) skipBtn.addTarget(self, action: #selector(skipAction(btn:)), for: .touchUpInside) skipBtn.layer.cornerRadius = 5 view.addSubview(skipBtn) } func getImageName()->String{ var imageName = "" if IPHONE4 { imageName = "Default" }else if IPHONE5 { imageName = "Default-640x1136" }else if IPHONE6 { imageName = "Default-750x1334" }else { imageName = "Default-1242x2208" } return imageName } override var preferredStatusBarStyle: UIStatusBarStyle{ return .lightContent } @objc private func skipAction(btn:UIButton){ if let callback = finishCallback { callback() } } func setSplashImage(image:UIImage){ splashIcon.image = image } }
mit
45475fa6590cb03b7f5dbc21cd4ab2be
33.43662
150
0.592229
4.72616
false
false
false
false
codeliling/HXDYWH
dywh/dywh/controllers/MusicViewController.swift
1
22244
// // MusicViewController.swift // dywh // // Created by lotusprize on 15/5/22. // Copyright (c) 2015年 geekTeam. All rights reserved. // import UIKit import Alamofire import Haneke class MusicViewController: HXWHViewController,UITableViewDataSource,UITableViewDelegate,UMSocialUIDelegate { var mapViewController:MusicMapViewController? let cache = Shared.imageCache @IBOutlet weak var listBtn: UIButton! @IBOutlet weak var mapBtn: UIButton! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var musicView: UIView! var cyclePlayBtn:UIButton! var shareBtn:UIButton! var prePlayBtn:UIButton! var nextPlayBtn:UIButton! var musicNameLayer:CATextLayer! var authorNameLayer:CATextLayer! var musicName:String? var musicAuthorName:String? var cdView:UIImageView! var musicList:[MusicModel] = [] var currentMusicIndex:Int = 0 var audioStream:AudioStreamer? var cdViewAngle:CGFloat = 1.0 var cycleAnimationFlag:Bool = true var currentPage:Int = 1 let limit:Int = 10 var playLayer:UIButton! var shareUrl:String! var timer:NSTimer? var settingTotalTime:Bool = false var leftTimerLayer:CATextLayer! var rightTimerLayer:CATextLayer! var musicModel:MusicModel! var image:UIImage? var lastIndexPath:NSIndexPath? @IBOutlet weak var musicProgressView: UIProgressView! @IBOutlet weak var activeIndicatorView: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. listBtn.setBackgroundImage(UIImage(named: "btnSelected"), forState: UIControlState.Selected) listBtn.setBackgroundImage(UIImage(named: "btnNormal"), forState: UIControlState.Normal) mapBtn.setBackgroundImage(UIImage(named: "btnSelected"), forState: UIControlState.Selected) mapBtn.setBackgroundImage(UIImage(named: "btnNormal"), forState: UIControlState.Normal) listBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 10) mapBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 10) musicView.layer.contents = UIImage(named: "musicPanelBg")?.CGImage cyclePlayBtn = UIButton() cyclePlayBtn.setBackgroundImage(UIImage(named: "musicCyclePlay"), forState: UIControlState.Normal) cyclePlayBtn.frame = CGRectMake(20, 10, 30, 30) cyclePlayBtn.addTarget(self, action: "cycleBtnClick:", forControlEvents: UIControlEvents.TouchUpInside) cyclePlayBtn.hidden = true musicView.addSubview(cyclePlayBtn) shareBtn = UIButton() shareBtn.setBackgroundImage(UIImage(named: "shareIconWhite"), forState: UIControlState.Normal) shareBtn.frame = CGRectMake(UIScreen.mainScreen().bounds.size.width - 55, 10, 30, 30) shareBtn.addTarget(self, action: "shareBtnClick:", forControlEvents: UIControlEvents.TouchUpInside) musicView.addSubview(shareBtn) musicNameLayer=CATextLayer() musicNameLayer.foregroundColor = UIColor.whiteColor().CGColor musicNameLayer.frame = CGRectMake(75, 10, UIScreen.mainScreen().bounds.size.width - 150, 20) musicNameLayer.fontSize = 16.0 musicNameLayer.contentsScale = 2.0 musicNameLayer.alignmentMode = kCAAlignmentCenter musicView.layer.addSublayer(musicNameLayer) authorNameLayer = CATextLayer() authorNameLayer.foregroundColor = UIColor.whiteColor().CGColor authorNameLayer.frame = CGRectMake(75, 30, UIScreen.mainScreen().bounds.size.width - 150, 20) authorNameLayer.fontSize = 14.0 authorNameLayer.contentsScale = 2.0 authorNameLayer.alignmentMode = kCAAlignmentCenter musicView.layer.addSublayer(authorNameLayer) prePlayBtn = UIButton(frame: CGRectMake(40, 80, 30, 30)) prePlayBtn.addTarget(self, action: "preBtnClick:", forControlEvents: UIControlEvents.TouchUpInside) prePlayBtn.setBackgroundImage(UIImage(named: "musicPrePlay"), forState: UIControlState.Normal) musicView.addSubview(prePlayBtn) nextPlayBtn = UIButton(frame: CGRectMake(UIScreen.mainScreen().bounds.size.width - 70, 80, 30, 30)) nextPlayBtn.addTarget(self, action: "nextBtnClick:", forControlEvents: UIControlEvents.TouchUpInside) nextPlayBtn.setBackgroundImage(UIImage(named: "musicNextPlay"), forState: UIControlState.Normal) musicView.addSubview(nextPlayBtn) cdView = UIImageView(frame: CGRectMake(UIScreen.mainScreen().bounds.size.width / 2 - 45, 55, 100, 100)) cdView.image = UIImage(named: "musicCDCover")! cdView.layer.cornerRadius = cdView.frame.size.width / 2 cdView.clipsToBounds = true cdView.layer.borderWidth = 5.0 cdView.layer.borderColor = UIColor.blackColor().CGColor cdView.userInteractionEnabled = true musicView.addSubview(cdView) playLayer = UIButton() playLayer.setBackgroundImage(UIImage(named: "musicPlayIcon"), forState: UIControlState.Normal) playLayer.frame = CGRectMake(UIScreen.mainScreen().bounds.size.width / 2 - 25, 75, 60, 60) playLayer.addTarget(self, action: "playBtnClick:", forControlEvents: UIControlEvents.TouchUpInside) musicView.addSubview(playLayer) leftTimerLayer = CATextLayer() leftTimerLayer.fontSize = 14.0 leftTimerLayer.alignmentMode = kCAAlignmentLeft leftTimerLayer.contentsScale = 2.0 leftTimerLayer.foregroundColor = UIColor.blackColor().CGColor leftTimerLayer.frame = CGRectMake(10, 150, 60, 15) self.musicView.layer.addSublayer(leftTimerLayer) rightTimerLayer = CATextLayer() rightTimerLayer.fontSize = 14.0 rightTimerLayer.alignmentMode = kCAAlignmentLeft rightTimerLayer.contentsScale = 2.0 rightTimerLayer.foregroundColor = UIColor.blackColor().CGColor rightTimerLayer.frame = CGRectMake(UIScreen.mainScreen().bounds.size.width - 50, 150, 40, 15) self.musicView.layer.addSublayer(rightTimerLayer) tableView.dataSource = self tableView.delegate = self tableView.tableFooterView = UIView(frame: CGRectZero); listBtn.selected = true mapBtn.selected = false tableView.addPullToRefreshWithActionHandler{ () -> Void in println(self.currentPage) self.loadingMusicDataList() self.currentPage++ } NSNotificationCenter.defaultCenter().addObserver(self, selector: "closeMusicOfReceivedNotification:", name: "CloseMusicNotification", object: nil) } override func viewDidAppear(animated: Bool) { if (mapViewController == nil){ mapViewController = MusicMapViewController() mapViewController?.view.frame = CGRectMake(0, musicView.frame.origin.y,musicView.frame.size.width, musicView.frame.size.height + tableView.frame.size.height) mapViewController!.view.backgroundColor = UIColor.redColor() self.addChildViewController(mapViewController!) self.view.addSubview(mapViewController!.view) mapViewController!.view.hidden = true self.tableView.triggerPullToRefresh() } } @IBAction func listBtnClick(sender: UIButton) { mapViewController!.view.hidden = true sender.selected = true mapBtn.selected = false } @IBAction func mapBtnClick(sender: UIButton) { mapViewController!.view.hidden = false sender.selected = true listBtn.selected = false } func cycleBtnClick(target:UIButton){ println("cycleBtnClick") } func shareBtnClick(target:UIButton){ if musicModel != nil { UMSocialSnsService.presentSnsIconSheetView(self, appKey: "556a5c3e67e58e57a3003c8a", shareText: self.musicModel.musicName, shareImage: image, shareToSnsNames: [UMShareToQzone,UMShareToQQ,UMShareToSms,UMShareToWechatFavorite,UMShareToWechatSession,UMShareToWechatTimeline], delegate: self) UMSocialData.defaultData().extConfig.wechatSessionData.url = self.shareUrl UMSocialData.defaultData().extConfig.wechatTimelineData.url = self.shareUrl UMSocialData.defaultData().extConfig.wechatFavoriteData.url = self.shareUrl UMSocialData.defaultData().extConfig.qqData.url = self.shareUrl UMSocialData.defaultData().extConfig.qzoneData.url = self.shareUrl } else{ self.view.makeToast("无分享数据", duration: 2.0, position: kCAGravityBottom) } } func playBtnClick(target:UIButton){ println("click......") if audioStream != nil{ println(audioStream!.isPlaying()) println(audioStream!.isPaused()) if audioStream!.isPlaying(){ audioStream?.pause() cycleAnimationFlag = false target.setBackgroundImage(UIImage(named: "musicPauseIcon"), forState: UIControlState.Normal) } else if audioStream!.isPaused(){ audioStream?.start() cycleAnimationFlag = true target.setBackgroundImage(UIImage(named: "musicPlayIcon"), forState: UIControlState.Normal) self.CDCycleAnimation(cdView) } } } func preBtnClick(target:UIButton){ currentMusicIndex-- resetPlayMusicStatus() if (currentMusicIndex >= 0 && currentMusicIndex < musicList.count){ var index1:NSIndexPath = NSIndexPath(forRow: currentMusicIndex + 1, inSection: 0) var cell1:MusicTableViewCell? = tableView.cellForRowAtIndexPath(index1) as? MusicTableViewCell cell1?.musicContentView.boardIconLayer.hidden = true var index2:NSIndexPath = NSIndexPath(forRow: currentMusicIndex, inSection: 0) var cell2:MusicTableViewCell? = tableView.cellForRowAtIndexPath(index2) as? MusicTableViewCell cell2?.musicContentView.boardIconLayer.hidden = false lastIndexPath = index2 cycleAnimationFlag = true self.CDCycleAnimation(cdView) musicModel = musicList[currentMusicIndex] if let playing = audioStream?.isPlaying(){ audioStream?.stop() } else if let pause = audioStream?.isPaused(){ audioStream?.stop() } if musicModel.musicImageUrl != nil{ initImageData(musicModel.musicImageUrl!) } shareUrl = musicModel.musicFileUrl! audioStream = AudioStreamer(URL: NSURL(string: musicModel.musicFileUrl!)) audioStream?.start() musicNameLayer.string = musicModel.musicName authorNameLayer.string = musicModel.musicAuthor } else{ //show Tips self.view.makeToast("无上一首!", duration: 1.0, position: kCAGravityBottom) } } func nextBtnClick(target:UIButton){ currentMusicIndex++ resetPlayMusicStatus() if (currentMusicIndex >= 0 && currentMusicIndex < musicList.count){ var index1:NSIndexPath = NSIndexPath(forRow: currentMusicIndex - 1, inSection: 0) var cell1:MusicTableViewCell? = tableView.cellForRowAtIndexPath(index1) as? MusicTableViewCell cell1?.musicContentView.boardIconLayer.hidden = true var index2:NSIndexPath = NSIndexPath(forRow: currentMusicIndex, inSection:0) var cell2:MusicTableViewCell? = tableView.cellForRowAtIndexPath(index2) as? MusicTableViewCell cell2?.musicContentView.boardIconLayer.hidden = false lastIndexPath = index2 cycleAnimationFlag = true self.CDCycleAnimation(cdView) musicModel = musicList[currentMusicIndex] if let playing = audioStream?.isPlaying(){ audioStream?.stop() } else if let pause = audioStream?.isPaused(){ audioStream?.stop() } if musicModel.musicImageUrl != nil{ initImageData(musicModel.musicImageUrl!) } shareUrl = musicModel.musicFileUrl! audioStream = AudioStreamer(URL: NSURL(string: musicModel.musicFileUrl!)) audioStream?.start() musicNameLayer.string = musicModel.musicName authorNameLayer.string = musicModel.musicAuthor } else{ //show Tips self.view.makeToast("无下一首!", duration: 1.0, position: kCAGravityBottom) } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return musicList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var musicModel:MusicModel = musicList[indexPath.row] var cell:MusicTableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? MusicTableViewCell //cell?.shareBtn.center = CGPointMake(UIScreen.mainScreen().bounds.size.width - 50, 30) //cell?.musicContentView.frame = CGRectMake(15, 0, UIScreen.mainScreen().bounds.size.width - 100, 60) for view in cell!.contentView.subviews { if let v = view as? MusicCellView{ cell?.musicContentView.musicAuthor = musicModel.musicAuthor! cell?.musicContentView.musicName = musicModel.musicName! cell?.musicContentView.setNeedsDisplay() } } cell?.selectionStyle = UITableViewCellSelectionStyle.None return cell! } func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { var cell:MusicTableViewCell? = tableView.cellForRowAtIndexPath(indexPath) as? MusicTableViewCell cell?.musicContentView.boardIconLayer.hidden = true } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if (lastIndexPath != nil){ var cell:MusicTableViewCell? = tableView.cellForRowAtIndexPath(lastIndexPath!) as? MusicTableViewCell cell?.musicContentView.boardIconLayer.hidden = true } var cell:MusicTableViewCell? = tableView.cellForRowAtIndexPath(indexPath) as? MusicTableViewCell cell?.musicContentView.boardIconLayer.hidden = false lastIndexPath = indexPath musicModel = musicList[indexPath.row] musicNameLayer.string = musicModel.musicName authorNameLayer.string = musicModel.musicAuthor if (musicModel.musicFileUrl != nil){ if audioStream != nil{ audioStream?.stop() } if musicModel.musicImageUrl != nil{ initImageData(musicModel.musicImageUrl!) } var filePath:String = musicModel.musicFileUrl! var utfFilePath:String = filePath.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! utfFilePath = utfFilePath.stringByReplacingOccurrencesOfString(" ", withString: "") println(utfFilePath) shareUrl = musicModel.musicFileUrl! var url:NSURL = NSURL(string: utfFilePath)! audioStream = AudioStreamer(URL: url) audioStream?.start() resetPlayMusicStatus() currentMusicIndex = indexPath.row self.CDCycleAnimation(cdView) self.startUpdateProgressView() } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 60.0 } func loadingMusicDataList(){ self.activeIndicatorView.hidden = false self.activeIndicatorView.startAnimating() Alamofire.request(.GET, ServerUrl.ServerContentURL, parameters: ["content_type":"3","limit":limit,"offset":limit*(currentPage-1)]) .responseJSON { (req, res, json, error) in if(error != nil) { NSLog("Error: \(error)") println(req) println(res) } else { println(json) var resultDict:NSDictionary? = json as? NSDictionary var dataDict:NSDictionary? = resultDict?.objectForKey("data") as? NSDictionary var success:Int = dataDict?.objectForKey("success") as! Int var count:Int = dataDict?.objectForKey("count") as! Int if success == 1{ var articles:NSArray = dataDict?.objectForKey("articles") as! NSArray if articles.count > 0{ var musicModel:MusicModel? for tempDict in articles{ musicModel = MusicModel() musicModel?.musicName = tempDict.objectForKey("title") as? String musicModel?.musicAuthor = tempDict.objectForKey("author") as? String var assetArray:NSArray? = tempDict.objectForKey("assets") as? NSArray if (assetArray?.count > 0){ var assetDict:NSDictionary = assetArray?.objectAtIndex(0) as! NSDictionary musicModel?.musicFileUrl = assetDict.objectForKey("media_file") as? String } musicModel?.latitude = tempDict.objectForKey("latitude") as! CGFloat musicModel?.longitude = tempDict.objectForKey("longitude") as! CGFloat musicModel?.musicDescription = tempDict.objectForKey("description") as? String musicModel?.musicId = tempDict.objectForKey("id") as! Int musicModel?.musicImageUrl = tempDict.objectForKey("profile") as? String self.musicList.insert(musicModel!, atIndex: 0) self.mapViewController?.addMapPoint(musicModel!) } self.tableView.reloadData() } else{ self.view.makeToast("无更多数据!") } } else{ self.view.makeToast("获取数据失败!") } } self.activeIndicatorView.hidden = true self.activeIndicatorView.stopAnimating() self.tableView.pullToRefreshView.stopAnimating() } } func CDCycleAnimation(cdView:UIView){ var endAngle:CGAffineTransform = CGAffineTransformMakeRotation(cdViewAngle * CGFloat(M_PI / 180.0)); UIView.animateWithDuration(0.1, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in cdView.transform = endAngle }) { (Bool) -> Void in self.cdViewAngle += 2.0 if (self.audioStream != nil && self.audioStream!.isFinishing()){ self.cycleAnimationFlag = false } if self.cycleAnimationFlag{ self.CDCycleAnimation(cdView) } } } func resetPlayMusicStatus(){ musicProgressView.progress = 0.0 settingTotalTime = false cdViewAngle = 1.0 playLayer.setBackgroundImage(UIImage(named: "musicPlayIcon"), forState: UIControlState.Normal) } func startUpdateProgressView(){ timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateProgressView", userInfo: nil, repeats:true) timer!.fire() } func updateProgressView(){ if audioStream != nil{ var totalTime = TimerStringTools().getTotleTime(audioStream!.totalTime()) if totalTime > 0 { if !settingTotalTime{ rightTimerLayer.string = (audioStream!.totalTime() as NSString).substringFromIndex(1) } settingTotalTime = true leftTimerLayer.string = audioStream?.currentTime() } var currentTime:Int = TimerStringTools().getCurrentTotleTime(audioStream!.currentTime()) if(Double(currentTime) < audioStream!.duration) { musicProgressView.progress = Float(Double(currentTime)/audioStream!.duration) } if audioStream!.isFinishing(){ leftTimerLayer.string = "00:00" musicProgressView.progress = 0.0 timer!.invalidate() } } } func initImageData(url:String){ let URL = NSURL(string: url)! let fetcher = NetworkFetcher<UIImage>(URL: URL) cache.fetch(fetcher: fetcher).onSuccess { image in // Do something with image self.image = image } } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) println("music view did disappear") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func closeMusicOfReceivedNotification(notification:NSNotification){ if audioStream != nil{ if audioStream!.isPlaying(){ audioStream?.stop() } } } deinit{ NSNotificationCenter.defaultCenter().removeObserver(self, name: "CloseMusicNotification", object: nil) } }
apache-2.0
f1e50aeac037e26dd77b58a6d72041f8
43.019841
300
0.624538
5.209204
false
false
false
false
brave/browser-ios
Storage/CompletionOps.swift
8
2531
/* 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 XCGLogger private let log = Logger.syncLogger public protocol PerhapsNoOp { var isNoOp: Bool { get } } open class LocalOverrideCompletionOp: PerhapsNoOp { open var processedLocalChanges: Set<GUID> = Set() // These can be deleted when we're run. Mark mirror as non-overridden, too. open var mirrorItemsToDelete: Set<GUID> = Set() // These were locally or remotely deleted. open var mirrorItemsToInsert: [GUID: BookmarkMirrorItem] = [:] // These were locally or remotely added. open var mirrorItemsToUpdate: [GUID: BookmarkMirrorItem] = [:] // These were already in the mirror, but changed. open var mirrorStructures: [GUID: [GUID]] = [:] // New or changed structure. open var mirrorValuesToCopyFromBuffer: Set<GUID> = Set() // No need to synthesize BookmarkMirrorItem instances in memory. open var mirrorValuesToCopyFromLocal: Set<GUID> = Set() open var modifiedTimes: [Timestamp: [GUID]] = [:] // Only for copy. open var isNoOp: Bool { return processedLocalChanges.isEmpty && mirrorValuesToCopyFromBuffer.isEmpty && mirrorValuesToCopyFromLocal.isEmpty && mirrorItemsToDelete.isEmpty && mirrorItemsToInsert.isEmpty && mirrorItemsToUpdate.isEmpty && mirrorStructures.isEmpty } open func setModifiedTime(_ time: Timestamp, guids: [GUID]) { var forCopy: [GUID] = self.modifiedTimes[time] ?? [] for guid in guids { // This saves us doing an UPDATE on these items. if var item = self.mirrorItemsToInsert[guid] { item.serverModified = time } else if var item = self.mirrorItemsToUpdate[guid] { item.serverModified = time } else { forCopy.append(guid) } } if !forCopy.isEmpty { modifiedTimes[time] = forCopy } } public init() { } } open class BufferCompletionOp: PerhapsNoOp { open var processedBufferChanges: Set<GUID> = Set() // These can be deleted when we're run. open var isNoOp: Bool { return self.processedBufferChanges.isEmpty } public init() { } }
mpl-2.0
738fad5cb8b083cffaf38a23c7663805
36.220588
144
0.624654
4.644037
false
false
false
false
DylanModesitt/Verb
Verb/Verb/UserCommunitiesViewController.swift
1
5158
// // UserCommunitiesViewController.swift // Verb // // Created by dcm on 12/24/15. // Copyright © 2015 Verb. All rights reserved. // import UIKit import Parse class UserCommunitiesViewController: UITableViewController { // MARK - Variables let interfaceModel = UIModel() var communityNames = [String]() var communityObjectIds = [String]() var selectedCommunityObjectID: String = "" let headerHeight: CGFloat = 120.0 var headerView: UIView! var headerMaskLayer: CAShapeLayer! var color = UIModel().uicolorFromHex(0xFF3B30) var queryNeeded = 0 var shouldContinue = true // MARK: - Methods func addCommunities() { do { try UserAPI().getUserCommunities(10, queriesToSkip: queryNeeded, completionHandler: { (names, objectIds) -> Void in if names!.count > 0 { self.communityNames += names! self.communityObjectIds += objectIds! self.queryNeeded++ self.tableView.reloadData() } else { self.shouldContinue = false } }) } catch { interfaceModel.presentThrownErrorController(error) } } override func scrollViewDidScroll(scrollView: UIScrollView) { updateHeader(headerView, headerHeight: headerHeight, headerMaskLayer: headerMaskLayer) } // MARK: - ViewController Lifecylce override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) // TestAPI().emptyUserCommunities() } override func viewDidLayoutSubviews() { updateNavigationBar(color) } override func viewDidLoad() { super.viewDidLoad() addCommunities() setupAutomaticCellSizing() headerView = self.tableView.tableHeaderView headerMaskLayer = CAShapeLayer() createHeader(headerView, headerHeight: headerHeight, headerMaskLayer: headerMaskLayer) updateHeader(headerView, headerHeight: headerHeight, headerMaskLayer: headerMaskLayer) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.communityNames.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: CommunityCell = tableView.dequeueReusableCellWithIdentifier("Community", forIndexPath: indexPath) as! CommunityCell cell.communityName.text = communityNames[indexPath.row] return cell } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row > communityNames.count - 40 && shouldContinue { addCommunities() } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { selectedCommunityObjectID = communityObjectIds[indexPath.row] self.performSegueWithIdentifier("loadCommunity", sender: self) } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // 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?) { if segue.identifier == "loadCommunity" { if let destination = segue.destinationViewController as? CommunityViewController { destination.objectID = self.selectedCommunityObjectID } } } }
apache-2.0
c6464d6cd0ed3e30026f4ac32c1fd577
33.152318
157
0.659686
5.521413
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
Source/ContentInsetsController.swift
3
3605
// // ContentInsetsController.swift // edX // // Created by Akiva Leffert on 5/18/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit public protocol ContentInsetsSourceDelegate : class { func contentInsetsSourceChanged(source : ContentInsetsSource) } public protocol ContentInsetsSource : class { var currentInsets : UIEdgeInsets { get } weak var insetsDelegate : ContentInsetsSourceDelegate? { get set } var affectsScrollIndicators : Bool { get } } public class ConstantInsetsSource : ContentInsetsSource { public var currentInsets : UIEdgeInsets { didSet { self.insetsDelegate?.contentInsetsSourceChanged(self) } } public let affectsScrollIndicators : Bool public weak var insetsDelegate : ContentInsetsSourceDelegate? public init(insets : UIEdgeInsets, affectsScrollIndicators : Bool) { self.currentInsets = insets self.affectsScrollIndicators = affectsScrollIndicators } } /// General solution to the problem of edge insets that can change and need to /// match a scroll view. When we drop iOS 7 support there may be a way to simplify this /// by using the new layout margins API. /// /// Other things like pull to refresh can be supported by creating a class that implements `ContentInsetsSource` /// and providing a way to add it to the `insetsSources` list. /// /// To use: /// #. Call `setupInController:scrollView:` in the `viewDidLoad` method of your controller /// #. Call `updateInsets` in the `viewDidLayoutSubviews` method of your controller public class ContentInsetsController: NSObject, ContentInsetsSourceDelegate { private var scrollView : UIScrollView? private weak var owner : UIViewController? private var insetSources : [ContentInsetsSource] = [] // Keyboard is separated out since it isn't a simple sum, but instead overrides other // insets when present private var keyboardSource : ContentInsetsSource? public func setupInController(owner : UIViewController, scrollView : UIScrollView) { self.owner = owner self.scrollView = scrollView keyboardSource = KeyboardInsetsSource(scrollView: scrollView) keyboardSource?.insetsDelegate = self } private var controllerInsets : UIEdgeInsets { let topGuideHeight = self.owner?.topLayoutGuide.length ?? 0 let bottomGuideHeight = self.owner?.bottomLayoutGuide.length ?? 0 return UIEdgeInsets(top : topGuideHeight, left : 0, bottom : bottomGuideHeight, right : 0) } public func contentInsetsSourceChanged(source: ContentInsetsSource) { updateInsets() } public func addSource(source : ContentInsetsSource) { source.insetsDelegate = self insetSources.append(source) updateInsets() } public func updateInsets() { var regularInsets = insetSources .map { $0.currentInsets } .reduce(controllerInsets, combine: +) let indicatorSources = insetSources .filter { $0.affectsScrollIndicators } .map { $0.currentInsets } var indicatorInsets = indicatorSources.reduce(controllerInsets, combine: +) if let keyboardHeight = keyboardSource?.currentInsets.bottom { regularInsets.bottom = max(keyboardHeight, regularInsets.bottom) indicatorInsets.bottom = max(keyboardHeight, indicatorInsets.bottom) } self.scrollView?.contentInset = regularInsets self.scrollView?.scrollIndicatorInsets = indicatorInsets } }
apache-2.0
447525a3f0f284aeabe10ca7d1bc51cd
35.424242
112
0.699029
5.04902
false
false
false
false
monsterkodi/krkkl
krkkl/ColorCell.swift
1
2053
import Cocoa class ColorCell : NSColorWell { var doActivate = false var isSelected = false static var isActive = false init(color:NSColor) { super.init(frame:NSRect()) self.color = color } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setSelected(_ selected:Bool) { isSelected = selected needsDisplay = true if ColorCell.isActive && selected { activate(true) } } override func draw(_ dirtyRect: NSRect) { NSGraphicsContext.saveGraphicsState() let round = NSBezierPath(roundedRect: NSRect(x:0, y:0, width:bounds.width, height:bounds.height), xRadius:5, yRadius:5) round.addClip() let rect = NSBezierPath(rect: NSRect(x:0, y:0, width:bounds.width, height:bounds.height)) color.set() rect.fill() if isSelected { colorRGB([1-color.r(), 1-color.g(), 1-color.b()]).set() let rect = NSBezierPath(ovalIn: NSRect(x:8,y:8,width:bounds.height-16, height:bounds.height-16)) rect.fill() } NSGraphicsContext.restoreGraphicsState() } func table() -> TableView { return superview!.superview as! TableView } func rgb() -> NSColor { return color.usingColorSpace(NSColorSpace.deviceRGB)! } func index() -> Int { return table().row(for: self) } override func mouseDown(with theEvent: NSEvent) { doActivate = true } override func mouseDragged(with theEvent: NSEvent) { super.mouseDown(with: theEvent) super.mouseDragged(with: theEvent) doActivate = false } override func mouseUp(with theEvent: NSEvent) { if doActivate { activate(true) doActivate = false ColorCell.isActive = true table().becomeFirstResponder() table().selectRow(index()) } } }
apache-2.0
362b304ff34f6f89c3d7b61af2f699db
23.73494
127
0.573794
4.522026
false
false
false
false
tkremenek/swift
test/Parse/builtin_word.swift
66
2124
// RUN: %target-typecheck-verify-swift -parse-stdlib precedencegroup AssignmentPrecedence { assignment: true } var word: Builtin.Word var i16: Builtin.Int16 var i32: Builtin.Int32 var i64: Builtin.Int64 var i128: Builtin.Int128 // Check that trunc/?ext operations are appropriately available given the // abstract range of potential Word sizes. word = Builtin.truncOrBitCast_Int128_Word(i128) word = Builtin.truncOrBitCast_Int64_Word(i64) word = Builtin.truncOrBitCast_Int32_Word(i32) // expected-error{{}} word = Builtin.truncOrBitCast_Int16_Word(i16) // expected-error{{}} i16 = Builtin.truncOrBitCast_Word_Int16(word) i32 = Builtin.truncOrBitCast_Word_Int32(word) i64 = Builtin.truncOrBitCast_Word_Int64(word) // expected-error{{}} i128 = Builtin.truncOrBitCast_Word_Int128(word) // expected-error{{}} word = Builtin.zextOrBitCast_Int128_Word(i128) // expected-error{{}} word = Builtin.zextOrBitCast_Int64_Word(i64) // expected-error{{}} word = Builtin.zextOrBitCast_Int32_Word(i32) word = Builtin.zextOrBitCast_Int16_Word(i16) i16 = Builtin.zextOrBitCast_Word_Int16(word) // expected-error{{}} i32 = Builtin.zextOrBitCast_Word_Int32(word) // expected-error{{}} i64 = Builtin.zextOrBitCast_Word_Int64(word) i128 = Builtin.zextOrBitCast_Word_Int128(word) word = Builtin.trunc_Int128_Word(i128) word = Builtin.trunc_Int64_Word(i64) // expected-error{{}} word = Builtin.trunc_Int32_Word(i32) // expected-error{{}} word = Builtin.trunc_Int16_Word(i16) // expected-error{{}} i16 = Builtin.trunc_Word_Int16(word) i32 = Builtin.trunc_Word_Int32(word) // expected-error{{}} i64 = Builtin.trunc_Word_Int64(word) // expected-error{{}} i128 = Builtin.trunc_Word_Int128(word) // expected-error{{}} word = Builtin.zext_Int128_Word(i128) // expected-error{{}} word = Builtin.zext_Int64_Word(i64) // expected-error{{}} word = Builtin.zext_Int32_Word(i32) // expected-error{{}} word = Builtin.zext_Int16_Word(i16) i16 = Builtin.zext_Word_Int16(word) // expected-error{{}} i32 = Builtin.zext_Word_Int32(word) // expected-error{{}} i64 = Builtin.zext_Word_Int64(word) // expected-error{{}} i128 = Builtin.zext_Word_Int128(word)
apache-2.0
7d3c8dd94622a2dac71b14d8561591b1
39.846154
73
0.741055
2.917582
false
false
false
false
nghiaphunguyen/NKit
NKit/Demo/OtherTestingCollection/OtherTestingCollectionReactor.swift
1
1688
// // OtherTestingCollectionReactor.swift // NKit // // Created by Apple on 5/27/17. // Copyright © 2017 Nghia Nguyen. All rights reserved. // import UIKit import RxSwift //MARK: -------Reactable------- protocol OtherTestingCollectionState { var itemsObservable: Observable<[NKDiffable]> {get} } protocol OtherTestingCollectionAction { func loadMore() } protocol OtherTestingCollectionReactable { var state: OtherTestingCollectionState {get} var action: OtherTestingCollectionAction {get} } //MARK: -------Reactor------- final class OtherTestingCollectionReactor: NSObject { let packageItemCount = 1000 var offset = 0 let rx_items = Variable<[Int]>([]) } //MARK: React extension OtherTestingCollectionReactor: OtherTestingCollectionState { var itemsObservable: Observable<[NKDiffable]> { return self.rx_items.asObservable().map({ items in return items.map({ return NumberTableViewCellModelImp(num: $0) }) }) } } extension OtherTestingCollectionReactor: OtherTestingCollectionAction { func loadMore() { let start = self.offset let end = start + packageItemCount self.offset = end self.rx_items.value = self.rx_items.value + (start..<end) } } extension OtherTestingCollectionReactor: OtherTestingCollectionReactable { var state: OtherTestingCollectionState { return self } var action: OtherTestingCollectionAction { return self } } //MARK: Creator extension OtherTestingCollectionReactor { static func instance() -> OtherTestingCollectionReactor { return OtherTestingCollectionReactor() } }
mit
4f6383f4f53431c3654054618881856c
23.808824
74
0.687611
4.393229
false
true
false
false
GabrielMassana/ColorWithHex-iOS
ColorWithHex-iOS/UIColor+Hex.swift
1
4355
// // UIColor+Hex.swift // ColorWithHex // // Created by GabrielMassana on 18/03/2016. // Copyright © 2016 GabrielMassana. All rights reserved. // // Credit: https://www.hackingwithswift.com/example-code/uicolor/how-to-convert-a-hex-color-to-a-uicolor // import UIKit public extension UIColor { //MARK: - Public method /** Creates UIColor object based on given hexadecimal color value (rrggbb), (#rrggbb), (rrggbbaa), (#rrggbbaa), (rgb) or (#rgb). - parameter hex: String with the hex information. With or without hash symbol. - returns: A UIColor from the given String. */ @objc(cwh_colorWithHex:) public class func colorWithHex(_ hex: String) -> UIColor? { var color:UIColor? = nil let noHash = hex.replacingOccurrences(of: "#", with: "") let start = noHash.startIndex let hexColor = noHash.substring(from: start) if (hexColor.characters.count == 8) { color = colorWithHexAlpha(hexColor) } else if (hexColor.characters.count == 6) { color = colorWithHexSixCharacters(hexColor) } else if (hexColor.characters.count == 3) { color = colorWithHexThreeCharacters(hexColor) } return color } //MARK: - Private methods /** Creates UIColor object based on given hexadecimal color value with alpha (rrggbbaa). - parameter hexColor: String with the hex information. - returns: A UIColor from the given String. */ fileprivate class func colorWithHexAlpha(_ hexColor: String) -> UIColor? { let red: CGFloat let green: CGFloat let blue: CGFloat let alpha: CGFloat var color:UIColor? = nil if hexColor.characters.count == 8 { let scanner = Scanner(string: hexColor) var hexNumber: UInt64 = 0 if scanner.scanHexInt64(&hexNumber) { red = CGFloat((hexNumber & 0xff000000) >> 24) / 255 green = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255 blue = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255 alpha = CGFloat(hexNumber & 0x000000ff) / 255 color = UIColor(red: red, green: green, blue: blue, alpha: alpha) } } return color } /** Creates UIColor object based on given hexadecimal color value without alpha (rrggbb) by adding alpha 1.0 to the given hex color. - parameter hexColor: String with the hex information. - returns: A UIColor from the given String. */ fileprivate class func colorWithHexSixCharacters(_ hexColor: String) -> UIColor? { return colorWithHexAlpha(String(format: "%@ff", hexColor)) } /** Creates UIColor object based on given short hexadecimal color value without alpha (rgb). Alpha will be 1.0. - parameter hexColor: String with the hex information. - returns: A UIColor from the given String. */ fileprivate class func colorWithHexThreeCharacters(_ hexColor: String) -> UIColor? { let redRange: Range = (hexColor.characters.index(hexColor.startIndex, offsetBy: 0) ..< hexColor.characters.index(hexColor.startIndex, offsetBy: 1)) let redString: String = String(format: "%@%@", hexColor.substring(with: redRange), hexColor.substring(with: redRange)) let greenRange: Range = (hexColor.characters.index(hexColor.startIndex, offsetBy: 1) ..< hexColor.characters.index(hexColor.startIndex, offsetBy: 2)) let greenString: String = String(format: "%@%@", hexColor.substring(with: greenRange), hexColor.substring(with: greenRange)) let blueRange: Range = (hexColor.characters.index(hexColor.startIndex, offsetBy: 2) ..< hexColor.characters.index(hexColor.startIndex, offsetBy: 3)) let blueString: String = String(format: "%@%@", hexColor.substring(with: blueRange), hexColor.substring(with: blueRange)) let hex: String = String(format: "%@%@%@", redString, greenString, blueString) return colorWithHexSixCharacters(hex) } }
mit
5b9888ed7dec0cbd2399d0e6cf4c9fe8
34.983471
157
0.605191
4.641791
false
false
false
false
nRewik/swift-corelibs-foundation
Foundation/NSJSONSerialization.swift
2
23568
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // public struct NSJSONReadingOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let MutableContainers = NSJSONReadingOptions(rawValue: 1 << 0) public static let MutableLeaves = NSJSONReadingOptions(rawValue: 1 << 1) public static let AllowFragments = NSJSONReadingOptions(rawValue: 1 << 2) } public struct NSJSONWritingOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let PrettyPrinted = NSJSONWritingOptions(rawValue: 1 << 0) } /* A class for converting JSON to Foundation/Swift objects and converting Foundation/Swift objects to JSON. An object that may be converted to JSON must have the following properties: - Top level object is a `Swift.Array` or `Swift.Dictionary` - All objects are `Swift.String`, `Foundation.NSNumber`, `Swift.Array`, `Swift.Dictionary`, or `Foundation.NSNull` - All dictionary keys are `Swift.String`s - `NSNumber`s are not NaN or infinity */ public class NSJSONSerialization : NSObject { /* Determines whether the given object can be converted to JSON. Other rules may apply. Calling this method or attempting a conversion are the definitive ways to tell if a given object can be converted to JSON data. - parameter obj: The object to test. - returns: `true` if `obj` can be converted to JSON, otherwise `false`. */ public class func isValidJSONObject(obj: Any) -> Bool { // TODO: - revisit this once bridging story gets fully figured out func isValidJSONObjectInternal(obj: Any) -> Bool { // object is Swift.String or NSNull if obj is String || obj is NSNull { return true } // object is NSNumber and is not NaN or infinity if let number = obj as? NSNumber { let invalid = number.doubleValue.isInfinite || number.doubleValue.isNaN || number.floatValue.isInfinite || number.floatValue.isNaN return !invalid } // object is Swift.Array if let array = obj as? [Any] { for element in array { guard isValidJSONObjectInternal(element) else { return false } } return true } // object is Swift.Dictionary if let dictionary = obj as? [String: Any] { for (_, value) in dictionary { guard isValidJSONObjectInternal(value) else { return false } } return true } // invalid object return false } // top level object must be an Swift.Array or Swift.Dictionary guard obj is [Any] || obj is [String: Any] else { return false } return isValidJSONObjectInternal(obj) } /* Generate JSON data from a Foundation object. If the object will not produce valid JSON then an exception will be thrown. Setting the NSJSONWritingPrettyPrinted option will generate JSON with whitespace designed to make the output more readable. If that option is not set, the most compact possible JSON will be generated. If an error occurs, the error parameter will be set and the return value will be nil. The resulting data is a encoded in UTF-8. */ public class func dataWithJSONObject(obj: AnyObject, options opt: NSJSONWritingOptions) throws -> NSData { NSUnimplemented() } /* Create a Foundation object from JSON data. Set the NSJSONReadingAllowFragments option if the parser should allow top-level objects that are not an NSArray or NSDictionary. Setting the NSJSONReadingMutableContainers option will make the parser generate mutable NSArrays and NSDictionaries. Setting the NSJSONReadingMutableLeaves option will make the parser generate mutable NSString objects. If an error occurs during the parse, then the error parameter will be set and the result will be nil. The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8. */ /// - Experiment: Note that the return type of this function is different than on Darwin Foundation (Any instead of AnyObject). This is likely to change once we have a more complete story for bridging in place. public class func JSONObjectWithData(data: NSData, options opt: NSJSONReadingOptions) throws -> Any { guard let string = NSString(data: data, encoding: detectEncoding(data)) else { throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [ "NSDebugDescription" : "Unable to convert data to a string using the detected encoding. The data may be corrupt." ]) } let result = try JSONObjectWithString(string._swiftObject) return result } /* Write JSON data into a stream. The stream should be opened and configured. The return value is the number of bytes written to the stream, or 0 on error. All other behavior of this method is the same as the dataWithJSONObject:options:error: method. */ public class func writeJSONObject(obj: AnyObject, toStream stream: NSOutputStream, options opt: NSJSONWritingOptions) throws -> Int { NSUnimplemented() } /* Create a JSON object from JSON data stream. The stream should be opened and configured. All other behavior of this method is the same as the JSONObjectWithData:options:error: method. */ public class func JSONObjectWithStream(stream: NSInputStream, options opt: NSJSONReadingOptions) throws -> AnyObject { NSUnimplemented() } } //MARK: - Deserialization internal extension NSJSONSerialization { static func JSONObjectWithString(string: String) throws -> Any { let parser = JSONDeserializer.UnicodeParser(viewSkippingBOM: string.unicodeScalars) if let (object, _) = try JSONDeserializer.parseObject(parser) { return object } else if let (array, _) = try JSONDeserializer.parseArray(parser) { return array } throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [ "NSDebugDescription" : "JSON text did not start with array or object and option to allow fragments not set." ]) } } //MARK: - Encoding Detection internal extension NSJSONSerialization { /// Detect the encoding format of the NSData contents class func detectEncoding(data: NSData) -> NSStringEncoding { let bytes = UnsafePointer<UInt8>(data.bytes) let length = data.length if let encoding = parseBOM(bytes, length: length) { return encoding } if length >= 4 { switch (bytes[0], bytes[1], bytes[2], bytes[3]) { case (0, 0, 0, _): return NSUTF32BigEndianStringEncoding case (_, 0, 0, 0): return NSUTF32LittleEndianStringEncoding case (0, _, 0, _): return NSUTF16BigEndianStringEncoding case (_, 0, _, 0): return NSUTF16LittleEndianStringEncoding default: break } } else if length >= 2 { switch (bytes[0], bytes[1]) { case (0, _): return NSUTF16BigEndianStringEncoding case (_, 0): return NSUTF16LittleEndianStringEncoding default: break } } return NSUTF8StringEncoding } static func parseBOM(bytes: UnsafePointer<UInt8>, length: Int) -> NSStringEncoding? { if length >= 2 { switch (bytes[0], bytes[1]) { case (0xEF, 0xBB): if length >= 3 && bytes[2] == 0xBF { return NSUTF8StringEncoding } case (0x00, 0x00): if length >= 4 && bytes[2] == 0xFE && bytes[3] == 0xFF { return NSUTF32BigEndianStringEncoding } case (0xFF, 0xFE): if length >= 4 && bytes[2] == 0 && bytes[3] == 0 { return NSUTF32LittleEndianStringEncoding } return NSUTF16LittleEndianStringEncoding case (0xFE, 0xFF): return NSUTF16BigEndianStringEncoding default: break } } return nil } } //MARK: - JSONDeserializer private struct JSONDeserializer { struct UnicodeParser { let view: String.UnicodeScalarView let index: String.UnicodeScalarIndex init(view: String.UnicodeScalarView, index: String.UnicodeScalarIndex) { self.view = view self.index = index } init(viewSkippingBOM view: String.UnicodeScalarView) { if view.startIndex < view.endIndex && view[view.startIndex] == UnicodeScalar(0xFEFF) { self.init(view: view, index: view.startIndex.successor()) return } self.init(view: view, index: view.startIndex) } func successor() -> UnicodeParser { return UnicodeParser(view: view, index: index.successor()) } var distanceFromStart: String.UnicodeScalarIndex.Distance { return view.startIndex.distanceTo(index) } } static let whitespaceScalars = "\u{20}\u{09}\u{0A}\u{0D}".unicodeScalars static func consumeWhitespace(parser: UnicodeParser) -> UnicodeParser { var index = parser.index let view = parser.view let endIndex = view.endIndex while index < endIndex && whitespaceScalars.contains(view[index]) { index = index.successor() } return UnicodeParser(view: view, index: index) } struct StructureScalar { static let BeginArray = UnicodeScalar(0x5B) // [ left square bracket static let EndArray = UnicodeScalar(0x5D) // ] right square bracket static let BeginObject = UnicodeScalar(0x7B) // { left curly bracket static let EndObject = UnicodeScalar(0x7D) // } right curly bracket static let NameSeparator = UnicodeScalar(0x3A) // : colon static let ValueSeparator = UnicodeScalar(0x2C) // , comma } static func consumeStructure(scalar: UnicodeScalar, input: UnicodeParser) throws -> UnicodeParser? { if let parser = try consumeScalar(scalar, input: consumeWhitespace(input)) { return consumeWhitespace(parser) } return nil } static func consumeScalar(scalar: UnicodeScalar, input: UnicodeParser) throws -> UnicodeParser? { switch takeScalar(input) { case nil: throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [ "NSDebugDescription" : "Unexpected end of file during JSON parse." ]) case let (taken, parser)? where taken == scalar: return parser default: return nil } } static func consumeSequence(sequence: String, input: UnicodeParser) throws -> UnicodeParser? { var parser = input for scalar in sequence.unicodeScalars { guard let newParser = try consumeScalar(scalar, input: parser) else { return nil } parser = newParser } return parser } static func takeScalar(input: UnicodeParser) -> (UnicodeScalar, UnicodeParser)? { guard input.index < input.view.endIndex else { return nil } return (input.view[input.index], input.successor()) } static func takeInClass(matchClass: String.UnicodeScalarView, count: UInt = UInt.max, input: UnicodeParser) -> (String.UnicodeScalarView, UnicodeParser)? { var output = String.UnicodeScalarView() var remaining = count var parser = input while remaining > 0, let (taken, newParser) = takeScalar(parser) where matchClass.contains(taken) { output.append(taken) parser = newParser remaining -= 1 } guard output.count > 0 && (count != UInt.max || remaining == 0) else { return nil } return (output, parser) } //MARK: - String Parsing struct StringScalar{ static let QuotationMark = UnicodeScalar(0x22) // " static let Escape = UnicodeScalar(0x5C) // \ } static func parseString(input: UnicodeParser) throws -> (String, UnicodeParser)? { guard let begin = try consumeScalar(StringScalar.QuotationMark, input: input) else { return nil } let view = begin.view let endIndex = view.endIndex var index = begin.index var value = String.UnicodeScalarView() while index < endIndex { let scalar = view[index] index = index.successor() switch scalar { case StringScalar.QuotationMark: return (String(value), UnicodeParser(view: view, index: index)) case StringScalar.Escape: let parser = UnicodeParser(view: view, index: index) if let (escaped, newParser) = try parseEscapeSequence(parser) { value.append(escaped) index = newParser.index } else { throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [ "NSDebugDescription" : "Invalid unicode escape sequence at position \(parser.distanceFromStart - 1)" ]) } default: value.append(scalar) } } throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [ "NSDebugDescription" : "Unexpected end of file during string parse." ]) } static func parseEscapeSequence(input: UnicodeParser) throws -> (UnicodeScalar, UnicodeParser)? { guard let (scalar, parser) = takeScalar(input) else { throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [ "NSDebugDescription" : "Early end of unicode escape sequence around character" ]) } switch scalar { case UnicodeScalar(0x22): // " quotation mark U+0022 fallthrough case UnicodeScalar(0x5C): // \ reverse solidus U+005F fallthrough case UnicodeScalar(0x2F): // / solidus U+002F return (scalar, parser) case UnicodeScalar(0x62): // b backspace U+0008 return (UnicodeScalar(0x08), parser) case UnicodeScalar(0x66): // f form feed U+000C return (UnicodeScalar(0x0C), parser) case UnicodeScalar(0x6E): // n line feed U+000A return (UnicodeScalar(0x0A), parser) case UnicodeScalar(0x72): // r carriage return U+000D return (UnicodeScalar(0x0D), parser) case UnicodeScalar(0x74): // t tab U+0009 return (UnicodeScalar(0x09), parser) case UnicodeScalar(0x75): // u unicode return try parseUnicodeSequence(parser) default: return nil } } static func parseUnicodeSequence(input: UnicodeParser) throws -> (UnicodeScalar, UnicodeParser)? { guard let (codeUnit, parser) = parseCodeUnit(input) else { return nil } if !UTF16.isLeadSurrogate(codeUnit) { return (UnicodeScalar(codeUnit), parser) } guard let (trailCodeUnit, finalParser) = try consumeSequence("\\u", input: parser).flatMap(parseCodeUnit) where UTF16.isTrailSurrogate(trailCodeUnit) else { throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [ "NSDebugDescription" : "Unable to convert hex escape sequence (no high character) to UTF8-encoded character at position \(parser.distanceFromStart)" ]) } var utf = UTF16() var generator = [codeUnit, trailCodeUnit].generate() switch utf.decode(&generator) { case .Result(let scalar): return (scalar, finalParser) default: return nil } } static let hexScalars = "1234567890abcdefABCDEF".unicodeScalars static func parseCodeUnit(input: UnicodeParser) -> (UTF16.CodeUnit, UnicodeParser)? { guard let (result, parser) = takeInClass(hexScalars, count: 4, input: input), let value = Int(String(result), radix: 16) else { return nil } return (UTF16.CodeUnit(value), parser) } //MARK: - Number parsing static let numberScalars = ".+-0123456789eE".unicodeScalars static func parseNumber(input: UnicodeParser) throws -> (Double, UnicodeParser)? { let view = input.view let endIndex = view.endIndex var index = input.index var value = String.UnicodeScalarView() while index < endIndex && numberScalars.contains(view[index]) { value.append(view[index]) index = index.successor() } guard value.count > 0, let result = Double(String(value)) else { return nil } return (result, UnicodeParser(view: view, index: index)) } //MARK: - Value parsing static func parseValue(input: UnicodeParser) throws -> (Any, UnicodeParser)? { if let (value, parser) = try parseString(input) { return (value, parser) } else if let parser = try consumeSequence("true", input: input) { return (true, parser) } else if let parser = try consumeSequence("false", input: input) { return (false, parser) } else if let parser = try consumeSequence("null", input: input) { return (NSNull(), parser) } else if let (object, parser) = try parseObject(input) { return (object, parser) } else if let (array, parser) = try parseArray(input) { return (array, parser) } else if let (number, parser) = try parseNumber(input) { return (number, parser) } return nil } //MARK: - Object parsing static func parseObject(input: UnicodeParser) throws -> ([String: Any], UnicodeParser)? { guard let beginParser = try consumeStructure(StructureScalar.BeginObject, input: input) else { return nil } var parser = beginParser var output: [String: Any] = [:] while true { if let finalParser = try consumeStructure(StructureScalar.EndObject, input: parser) { return (output, finalParser) } if let (key, value, newParser) = try parseObjectMember(parser) { output[key] = value if let finalParser = try consumeStructure(StructureScalar.EndObject, input: newParser) { return (output, finalParser) } else if let nextParser = try consumeStructure(StructureScalar.ValueSeparator, input: newParser) { parser = nextParser continue } else { return nil } } return nil } } static func parseObjectMember(input: UnicodeParser) throws -> (String, Any, UnicodeParser)? { guard let (name, parser) = try parseString(input) else { throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [ "NSDebugDescription" : "Missing object key at location \(input.distanceFromStart)" ]) } guard let separatorParser = try consumeStructure(StructureScalar.NameSeparator, input: parser) else { throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [ "NSDebugDescription" : "Invalid value at location \(input.distanceFromStart)" ]) } guard let (value, finalParser) = try parseValue(separatorParser) else { throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [ "NSDebugDescription" : "Invalid value at location \(input.distanceFromStart)" ]) } return (name, value, finalParser) } //MARK: - Array parsing static func parseArray(input: UnicodeParser) throws -> ([Any], UnicodeParser)? { guard let beginParser = try consumeStructure(StructureScalar.BeginArray, input: input) else { return nil } var parser = beginParser var output: [Any] = [] while true { if let finalParser = try consumeStructure(StructureScalar.EndArray, input: parser) { return (output, finalParser) } if let (value, newParser) = try parseValue(parser) { output.append(value) if let finalParser = try consumeStructure(StructureScalar.EndArray, input: newParser) { return (output, finalParser) } else if let nextParser = try consumeStructure(StructureScalar.ValueSeparator, input: newParser) { parser = nextParser continue } else { throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [ "NSDebugDescription" : "Unexpected end of file while parsing array at location \(input.distanceFromStart)" ]) } } throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [ "NSDebugDescription" : "Unexpected end of file while parsing array at location \(input.distanceFromStart)" ]) } } }
apache-2.0
e0161f6252012903b330214d50e2f58d
42.403315
499
0.603191
5.062943
false
false
false
false
lieonCX/Live
Live/Others/Lib/RITLImagePicker/Tool/Closure/RITLPhotoClosure.swift
1
889
// // RITLPhotoClosure.swift // RITLImagePicker-Swift // // Created by YueWen on 2017/1/9. // Copyright © 2017年 YueWen. All rights reserved. // import Foundation import UIKit // //typealias RITLPhotoDidSelectedClosure = (_:(([UIImage]) -> Swift.Void)) //typealias RITLPhotoDidSelectedBlockAsset = (_:([UIImage],[NSNumber]) -> Swift.Void) typealias id = Any typealias PhotoBlock = ((Void) -> Void) typealias PhotoCompleteBlock0 = ((id) -> Void) typealias PhotoCompleteBlock1 = ((id,id) -> Void) typealias PhotoCompleteBlock2 = ((id,id,id,UInt) -> Void) typealias PhotoCompleteBlock4 = ((id,id,Bool) -> Void) typealias PhotoCompleteBlock5 = ((id,id,UInt) -> Void) typealias PhotoCompleteBlock6 = ((Bool,UInt) -> Void) typealias PhotoCompleteBlock7 = ((id,id,id,id,Int) -> Void) typealias PhotoCompleteBlock8 = ((Bool,id) -> Void) typealias PhotoCompleteBlock9 = ((Bool) -> Void)
mit
52bda974de44052329e67b5556e3005c
30.642857
85
0.714447
3.616327
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/Kingfisher/Sources/Extensions/UIButton+Kingfisher.swift
4
17221
// // UIButton+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/13. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit extension KingfisherWrapper where Base: UIButton { // MARK: Setting Image /// Sets an image to the button for a specified state with a source. /// /// - Parameters: /// - source: The `Source` object contains information about the image. /// - state: The button state to which the image should be set. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested source, from either cache /// or network. Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setImage( with source: Source?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { guard let source = source else { base.setImage(placeholder, for: state) setTaskIdentifier(nil, for: state) completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) return nil } let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) if !options.keepCurrentImageWhileLoading { base.setImage(placeholder, for: state) } var mutatingSelf = self let issuedTaskIdentifier = Source.Identifier.next() setTaskIdentifier(issuedTaskIdentifier, for: state) let task = KingfisherManager.shared.retrieveImage( with: source, options: options, progressBlock: { receivedSize, totalSize in guard issuedTaskIdentifier == self.taskIdentifier(for: state) else { return } progressBlock?(receivedSize, totalSize) }, completionHandler: { result in CallbackQueue.mainCurrentOrAsync.execute { guard issuedTaskIdentifier == self.taskIdentifier(for: state) else { let reason: KingfisherError.ImageSettingErrorReason do { let value = try result.get() reason = .notCurrentSourceTask(result: value, error: nil, source: source) } catch { reason = .notCurrentSourceTask(result: nil, error: error, source: source) } let error = KingfisherError.imageSettingError(reason: reason) completionHandler?(.failure(error)) return } mutatingSelf.imageTask = nil switch result { case .success(let value): self.base.setImage(value.image, for: state) completionHandler?(result) case .failure: if let image = options.onFailureImage { self.base.setImage(image, for: state) } completionHandler?(result) } } }) mutatingSelf.imageTask = task return task } /// Sets an image to the button for a specified state with a requested resource. /// /// - Parameters: /// - resource: The `Resource` object contains information about the resource. /// - state: The button state to which the image should be set. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache /// or network. Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setImage( with resource: Resource?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { return setImage( with: resource.map { Source.network($0) }, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } // MARK: Cancelling Downloading Task /// Cancels the image download task of the button if it is running. /// Nothing will happen if the downloading has already finished. public func cancelImageDownloadTask() { imageTask?.cancel() } // MARK: Setting Background Image /// Sets a background image to the button for a specified state with a source. /// /// - Parameters: /// - source: The `Source` object contains information about the image. /// - state: The button state to which the image should be set. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested source /// Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setBackgroundImage( with source: Source?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { guard let source = source else { base.setBackgroundImage(placeholder, for: state) setBackgroundTaskIdentifier(nil, for: state) completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) return nil } let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) if !options.keepCurrentImageWhileLoading { base.setBackgroundImage(placeholder, for: state) } var mutatingSelf = self let issuedTaskIdentifier = Source.Identifier.next() setBackgroundTaskIdentifier(issuedTaskIdentifier, for: state) let task = KingfisherManager.shared.retrieveImage( with: source, options: options, progressBlock: { receivedSize, totalSize in guard issuedTaskIdentifier == self.backgroundTaskIdentifier(for: state) else { return } if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: { result in CallbackQueue.mainCurrentOrAsync.execute { guard issuedTaskIdentifier == self.backgroundTaskIdentifier(for: state) else { let reason: KingfisherError.ImageSettingErrorReason do { let value = try result.get() reason = .notCurrentSourceTask(result: value, error: nil, source: source) } catch { reason = .notCurrentSourceTask(result: nil, error: error, source: source) } let error = KingfisherError.imageSettingError(reason: reason) completionHandler?(.failure(error)) return } mutatingSelf.backgroundImageTask = nil switch result { case .success(let value): self.base.setBackgroundImage(value.image, for: state) completionHandler?(result) case .failure: if let image = options.onFailureImage { self.base.setBackgroundImage(image, for: state) } completionHandler?(result) } } }) mutatingSelf.backgroundImageTask = task return task } /// Sets a background image to the button for a specified state with a requested resource. /// /// - Parameters: /// - resource: The `Resource` object contains information about the resource. /// - state: The button state to which the image should be set. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache /// or network. Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setBackgroundImage( with resource: Resource?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { return setBackgroundImage( with: resource.map { .network($0) }, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } // MARK: Cancelling Background Downloading Task /// Cancels the background image download task of the button if it is running. /// Nothing will happen if the downloading has already finished. public func cancelBackgroundImageDownloadTask() { backgroundImageTask?.cancel() } } // MARK: - Associated Object private var taskIdentifierKey: Void? private var imageTaskKey: Void? // MARK: Properties extension KingfisherWrapper where Base: UIButton { public func taskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? { return (taskIdentifierInfo[NSNumber(value:state.rawValue)] as? Box<Source.Identifier.Value>)?.value } private func setTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) { taskIdentifierInfo[NSNumber(value:state.rawValue)] = identifier.map { Box($0) } } private var taskIdentifierInfo: NSMutableDictionary { get { guard let dictionary: NSMutableDictionary = getAssociatedObject(base, &taskIdentifierKey) else { let dic = NSMutableDictionary() var mutatingSelf = self mutatingSelf.taskIdentifierInfo = dic return dic } return dictionary } set { setRetainedAssociatedObject(base, &taskIdentifierKey, newValue) } } private var imageTask: DownloadTask? { get { return getAssociatedObject(base, &imageTaskKey) } set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} } } private var backgroundTaskIdentifierKey: Void? private var backgroundImageTaskKey: Void? // MARK: Background Properties extension KingfisherWrapper where Base: UIButton { public func backgroundTaskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? { return (backgroundTaskIdentifierInfo[NSNumber(value:state.rawValue)] as? Box<Source.Identifier.Value>)?.value } private func setBackgroundTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) { backgroundTaskIdentifierInfo[NSNumber(value:state.rawValue)] = identifier.map { Box($0) } } private var backgroundTaskIdentifierInfo: NSMutableDictionary { get { guard let dictionary: NSMutableDictionary = getAssociatedObject(base, &backgroundTaskIdentifierKey) else { let dic = NSMutableDictionary() var mutatingSelf = self mutatingSelf.backgroundTaskIdentifierInfo = dic return dic } return dictionary } set { setRetainedAssociatedObject(base, &backgroundTaskIdentifierKey, newValue) } } private var backgroundImageTask: DownloadTask? { get { return getAssociatedObject(base, &backgroundImageTaskKey) } mutating set { setRetainedAssociatedObject(base, &backgroundImageTaskKey, newValue) } } } extension KingfisherWrapper where Base: UIButton { /// Gets the image URL of this button for a specified state. /// /// - Parameter state: The state that uses the specified image. /// - Returns: Current URL for image. @available(*, deprecated, message: "Use `taskIdentifier` instead to identify a setting task.") public func webURL(for state: UIControl.State) -> URL? { return nil } /// Gets the background image URL of this button for a specified state. /// /// - Parameter state: The state that uses the specified background image. /// - Returns: Current URL for image. @available(*, deprecated, message: "Use `backgroundTaskIdentifier` instead to identify a setting task.") public func backgroundWebURL(for state: UIControl.State) -> URL? { return nil } }
mit
ad0e2a1ca4ed1d813ebf6fbd04e6e563
44.437995
119
0.629812
5.508957
false
false
false
false
adis300/Swift-Learn
SwiftLearn/Source/Arithmetic/Division.swift
1
4599
// // Inverse.swift // Swift-Learn // // Created by Disi A on 11/21/16. // Copyright © 2016 Votebin. All rights reserved. // import Foundation import Accelerate // MARK: Divide public func / (lhs: [Float], rhs: [Float]) -> [Float] { var results = [Float](lhs) vvdivf(&results, lhs, rhs, [Int32(lhs.count)]) return results } public func / (lhs: [Double], rhs: [Double]) -> [Double] { var results = [Double](lhs) vvdiv(&results, lhs, rhs, [Int32(lhs.count)]) return results } public func / (lhs: [Float], rhs: Float) -> [Float] { var rhs = rhs var results = [Float](lhs) vDSP_vsdiv(lhs,1, &rhs, &results, 1, vDSP_Length(lhs.count)) return results } public func / (lhs: [Double], rhs: Double) -> [Double] { var rhs = rhs var results = [Double](lhs) vDSP_vsdivD(lhs,1, &rhs, &results, 1, vDSP_Length(lhs.count)) return results } public func / (lhs: Float, rhs: [Float]) -> [Float] { var lhs = lhs var results = [Float](rhs) vDSP_svdiv(&lhs, rhs, 1, &results, 1, vDSP_Length(rhs.count)) return results } public func / (lhs: Double, rhs: [Double]) -> [Double] { var lhs = lhs var results = [Double](rhs) vDSP_svdivD(&lhs, rhs, 1, &results, 1, vDSP_Length(rhs.count)) return results } public func /= (lhs: inout [Float], rhs: Float){ var rhs = rhs vDSP_vsdiv(lhs,1, &rhs, &lhs, 1, vDSP_Length(lhs.count)) } public func /= (lhs: inout [Double], rhs: Double){ var rhs = rhs vDSP_vsdivD(lhs,1, &rhs, &lhs, 1, vDSP_Length(lhs.count)) } public func / (lhs: Float, rhs: Int) -> Float { return lhs/Float(rhs) } public func / (lhs: Double, rhs: Int) -> Double { return lhs/Double(rhs) } // MARK: Vector division implementation public func /= (lhs: inout Vector<Float>, rhs: Float){ var rhs = rhs vDSP_vsdiv(lhs.vector,1, &rhs, &lhs.vector, 1, vDSP_Length(lhs.length)) } public func /= (lhs: inout Vector<Double>, rhs: Double){ var rhs = rhs vDSP_vsdivD(lhs.vector,1, &rhs, &lhs.vector, 1, vDSP_Length(lhs.length)) } public func inv(_ x: inout Vector<Float>){ var top:Float = 1 vDSP_svdiv(&top, x.vector, 1, &x.vector, 1, vDSP_Length(x.length)) } public func inv(_ x: inout Vector<Double>){ var top:Double = 1 vDSP_svdivD(&top, x.vector, 1, &x.vector, 1, vDSP_Length(x.length)) } // MARK: Matrix division implementation public func / (lhs: Matrix<Float>, rhs: Matrix<Float>) -> Matrix<Float> { let BInv = inv(rhs) precondition(lhs.cols == BInv.rows, "Matrix dimensions not compatible") return lhs * BInv } public func / (lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> { let BInv = inv(rhs) precondition(lhs.cols == BInv.rows, "Matrix dimensions not compatible") return lhs * BInv } public func / (lhs: Matrix<Double>, rhs: Double) -> Matrix<Double> { var result = Matrix<Double>(rows: lhs.rows, cols: lhs.cols, repeatedValue: 0.0) result.grid = lhs.grid / rhs; return result; } public func / (lhs: Matrix<Float>, rhs: Float) -> Matrix<Float> { var result = Matrix<Float>(rows: lhs.rows, cols: lhs.cols, repeatedValue: 0.0) result.grid = lhs.grid / rhs; return result; } public func inv(_ x : Matrix<Float>) -> Matrix<Float> { precondition(x.rows == x.cols, "Matrix must be square") var results = x var ipiv = [__CLPK_integer](repeating: 0, count: x.rows * x.rows) var lwork = __CLPK_integer(x.cols * x.cols) var work = [CFloat](repeating: 0.0, count: Int(lwork)) var error: __CLPK_integer = 0 var nc = __CLPK_integer(x.cols) _ = withUnsafeMutablePointer(to: &nc) { sgetrf_($0, $0, &(results.grid), $0, &ipiv, &error) } _ = withUnsafeMutablePointer(to: &nc) { sgetri_($0, &(results.grid), $0, &ipiv, &work, &lwork, &error) } assert(error == 0, "Matrix not invertible") return results } public func inv(_ x : Matrix<Double>) -> Matrix<Double> { precondition(x.rows == x.cols, "Matrix must be square") var results = x var ipiv = [__CLPK_integer](repeating: 0, count: x.rows * x.rows) var lwork = __CLPK_integer(x.cols * x.cols) var work = [CDouble](repeating: 0.0, count: Int(lwork)) var error: __CLPK_integer = 0 var nc = __CLPK_integer(x.cols) _ = withUnsafeMutablePointer(to: &nc) { dgetrf_($0, $0, &(results.grid), $0, &ipiv, &error) } _ = withUnsafeMutablePointer(to: &nc) { dgetri_($0, &(results.grid), $0, &ipiv, &work, &lwork, &error) } assert(error == 0, "Matrix not invertible") return results }
apache-2.0
c21218eaada93cabe846675430c114d0
27.036585
83
0.611135
3.065333
false
false
false
false
xpush/lib-xpush-ios
XpushFramework/Alamofire.swift
120
11586
// Alamofire.swift // // Copyright (c) 2014–2015 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 Foundation /// Alamofire errors public let AlamofireErrorDomain = "com.alamofire.error" public let AlamofireInputStreamReadFailed = -6000 public let AlamofireOutputStreamWriteFailed = -6001 // MARK: - URLStringConvertible /** Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests. */ public protocol URLStringConvertible { /** A URL that conforms to RFC 2396. Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808. See http://tools.ietf.org/html/rfc2396 See http://tools.ietf.org/html/rfc1738 See http://tools.ietf.org/html/rfc1808 */ var URLString: String { get } } extension String: URLStringConvertible { public var URLString: String { return self } } extension NSURL: URLStringConvertible { public var URLString: String { return absoluteString! } } extension NSURLComponents: URLStringConvertible { public var URLString: String { return URL!.URLString } } extension NSURLRequest: URLStringConvertible { public var URLString: String { return URL!.URLString } } // MARK: - URLRequestConvertible /** Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. */ public protocol URLRequestConvertible { /// The URL request. var URLRequest: NSURLRequest { get } } extension NSURLRequest: URLRequestConvertible { public var URLRequest: NSURLRequest { return self } } // MARK: - Convenience func URLRequest(method: Method, URLString: URLStringConvertible, headers: [String: String]? = nil) -> NSMutableURLRequest { let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!) mutableURLRequest.HTTPMethod = method.rawValue if let headers = headers { for (headerField, headerValue) in headers { mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField) } } return mutableURLRequest } // MARK: - Request Methods /** Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding. :param: method The HTTP method. :param: URLString The URL string. :param: parameters The parameters. `nil` by default. :param: encoding The parameter encoding. `.URL` by default. :param: headers The HTTP headers. `nil` by default. :returns: The created request. */ public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request { return Manager.sharedInstance.request(method, URLString, parameters: parameters, encoding: encoding, headers: headers) } /** Creates a request using the shared manager instance for the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. :param: URLRequest The URL request :returns: The created request. */ public func request(URLRequest: URLRequestConvertible) -> Request { return Manager.sharedInstance.request(URLRequest.URLRequest) } // MARK: - Upload Methods // MARK: File /** Creates an upload request using the shared manager instance for the specified method, URL string, and file. :param: method The HTTP method. :param: URLString The URL string. :param: headers The HTTP headers. `nil` by default. :param: file The file to upload. :returns: The created upload request. */ public func upload(method: Method, URLString: URLStringConvertible, headers: [String: String]? = nil, #file: NSURL) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file) } /** Creates an upload request using the shared manager instance for the specified URL request and file. :param: URLRequest The URL request. :param: file The file to upload. :returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, #file: NSURL) -> Request { return Manager.sharedInstance.upload(URLRequest, file: file) } // MARK: Data /** Creates an upload request using the shared manager instance for the specified method, URL string, and data. :param: method The HTTP method. :param: URLString The URL string. :param: headers The HTTP headers. `nil` by default. :param: data The data to upload. :returns: The created upload request. */ public func upload(method: Method, URLString: URLStringConvertible, headers: [String: String]? = nil, #data: NSData) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data) } /** Creates an upload request using the shared manager instance for the specified URL request and data. :param: URLRequest The URL request. :param: data The data to upload. :returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, #data: NSData) -> Request { return Manager.sharedInstance.upload(URLRequest, data: data) } // MARK: Stream /** Creates an upload request using the shared manager instance for the specified method, URL string, and stream. :param: method The HTTP method. :param: URLString The URL string. :param: headers The HTTP headers. `nil` by default. :param: stream The stream to upload. :returns: The created upload request. */ public func upload(method: Method, URLString: URLStringConvertible, headers: [String: String]? = nil, #stream: NSInputStream) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream) } /** Creates an upload request using the shared manager instance for the specified URL request and stream. :param: URLRequest The URL request. :param: stream The stream to upload. :returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, #stream: NSInputStream) -> Request { return Manager.sharedInstance.upload(URLRequest, stream: stream) } // MARK: MultipartFormData /** Creates an upload request using the shared manager instance for the specified method and URL string. :param: method The HTTP method. :param: URLString The URL string. :param: headers The HTTP headers. `nil` by default. :param: multipartFormData The closure used to append body parts to the `MultipartFormData`. :param: encodingMemoryThreshold The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. :param: encodingCompletion The closure called when the `MultipartFormData` encoding is complete. */ public func upload( method: Method, #URLString: URLStringConvertible, headers: [String: String]? = nil, #multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, #encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) { return Manager.sharedInstance.upload( method, URLString, headers: headers, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } /** Creates an upload request using the shared manager instance for the specified method and URL string. :param: URLRequest The URL request. :param: multipartFormData The closure used to append body parts to the `MultipartFormData`. :param: encodingMemoryThreshold The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. :param: encodingCompletion The closure called when the `MultipartFormData` encoding is complete. */ public func upload( URLRequest: URLRequestConvertible, #multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, #encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) { return Manager.sharedInstance.upload( URLRequest, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } // MARK: - Download Methods // MARK: URL Request /** Creates a download request using the shared manager instance for the specified method and URL string. :param: method The HTTP method. :param: URLString The URL string. :param: headers The HTTP headers. `nil` by default. :param: destination The closure used to determine the destination of the downloaded file. :returns: The created download request. */ public func download(method: Method, URLString: URLStringConvertible, headers: [String: String]? = nil, #destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download(method, URLString, headers: headers, destination: destination) } /** Creates a download request using the shared manager instance for the specified URL request. :param: URLRequest The URL request. :param: destination The closure used to determine the destination of the downloaded file. :returns: The created download request. */ public func download(URLRequest: URLRequestConvertible, #destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download(URLRequest, destination: destination) } // MARK: Resume Data /** Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation. :param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information. :param: destination The closure used to determine the destination of the downloaded file. :returns: The created download request. */ public func download(resumeData data: NSData, #destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download(data, destination: destination) }
mit
d4cc8d6838167ad04897cbbca7f1ba71
35.774603
208
0.731613
4.918896
false
false
false
false