repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
YuhuaBillChen/Spartify
refs/heads/master
Spartify/Spartify/HostPartyViewController.swift
gpl-3.0
1
// // HostPartyViewController.swift // Spartify // // Created by Bill on 1/23/16. // Copyright © 2016 pennapps. All rights reserved. // import UIKit import Parse import ParseUI import CoreMotion import AudioToolbox class HostPartyViewController: UIViewController { @IBOutlet weak var XYZLabel: UILabel! @IBOutlet weak var leavePartyButton: UIButton! @IBOutlet weak var setSeqButton: UIButton! @IBOutlet weak var seqLab: UILabel! @IBOutlet weak var seqLabel1: UILabel! @IBOutlet weak var seqLabel2: UILabel! @IBOutlet weak var seqLabel3: UILabel! @IBOutlet weak var seqLabel4: UILabel! @IBOutlet weak var clearSeqButton: UIButton! let SEQ_LENGTH = 4 let manager = CMMotionManager() let GRAVITY_MARGIN = 0.2 let ACCELE_TRH = 0.3 let DELAY_TRH = 50 var delayCounter = 0 var sucessfullyChangStatus = false var currentState = "Normal" let userObj = PFUser.currentUser()! var partyObj:PFObject! var isSettingSeq = false var settingSeqNo = -1 var seqArray = [String]() func changeMotionStatus(gx:Double,ax:Double,gy:Double,ay:Double,gz:Double,az:Double){ if (delayCounter > DELAY_TRH){ if (gx < (-1+self.GRAVITY_MARGIN) && (abs(ax) + abs(ay) + abs(az)) > self.ACCELE_TRH*3 ){ self.currentState = "Left" self.sucessfullyChangStatus = true self.delayCounter = 0 } else if (gx > (1-self.GRAVITY_MARGIN) && (abs(ax) + abs(ay) + abs(az)) > self.ACCELE_TRH*3){ self.currentState = "Right" self.sucessfullyChangStatus = true self.delayCounter = 0 } else if (gz < (-1+self.GRAVITY_MARGIN) && (abs(ax) + abs(ay) + abs(az)) > self.ACCELE_TRH*3 ){ self.currentState = "Forward" self.sucessfullyChangStatus = true self.delayCounter = 0 } else if (gz > (1-self.GRAVITY_MARGIN) && (abs(ax) + abs(ay) + abs(az)) > self.ACCELE_TRH*3){ self.currentState = "Backward" self.sucessfullyChangStatus = true self.delayCounter = 0 } else if (abs(gx) < (self.GRAVITY_MARGIN) && abs(gz) < self.GRAVITY_MARGIN && gy < -(1-self.GRAVITY_MARGIN) && (abs(ax) + abs(ay) + abs(az)) > self.ACCELE_TRH*3){ self.currentState = "Up" self.sucessfullyChangStatus = true self.delayCounter = 0 } else if (abs(gx) < (self.GRAVITY_MARGIN) && abs(gz) < self.GRAVITY_MARGIN && gy > (1-self.GRAVITY_MARGIN) && (abs(ax) + abs(ay) + abs(az)) > self.ACCELE_TRH*3){ self.currentState = "Down" self.sucessfullyChangStatus = true self.delayCounter = 0 } else{ if (self.currentState != "Normal"){ self.currentState = "Normal" self.sucessfullyChangStatus = true } } } } func changeBackground(){ if (self.currentState == "Normal"){ self.view.backgroundColor = UIColor.whiteColor() } else if (self.currentState == "Left"){ self.view.backgroundColor = UIColor.redColor() } else if (self.currentState == "Right"){ self.view.backgroundColor = UIColor.greenColor() } else if (self.currentState == "Up"){ self.view.backgroundColor = UIColor.orangeColor() } else if (self.currentState == "Down"){ self.view.backgroundColor = UIColor.purpleColor() } else if (self.currentState == "Forward"){ self.view.backgroundColor = UIColor.blueColor() } else if (self.currentState == "Backward"){ self.view.backgroundColor = UIColor.yellowColor() } else{ self.view.backgroundColor = UIColor.grayColor() } } func vibrate(){ AudioToolbox.AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) } func beep(){ AudioToolbox.AudioServicesPlaySystemSound(1109) } func addSeqUpdater(){ if (isSettingSeq){ if (self.settingSeqNo < self.SEQ_LENGTH ){ self.addOneSeq(self.currentState) self.delayCounter = -DELAY_TRH vibrate() if ( self.settingSeqNo == self.SEQ_LENGTH ){ self.setSeqEnd(); } } } } func updateCheck(){ if (self.sucessfullyChangStatus){ self.XYZLabel!.text = self.currentState changeBackground() beep() if (self.currentState != "Normal"){ addSeqUpdater() } self.sucessfullyChangStatus = false; } else{ self.delayCounter += 1 } } func motionInit(){ if manager.deviceMotionAvailable { let _:CMAccelerometerData! let _:NSError! manager.deviceMotionUpdateInterval = 0.01 manager.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler:{ accelerometerData, error in let x = accelerometerData!.gravity.x let y = accelerometerData!.gravity.y let z = accelerometerData!.gravity.z let x2 = accelerometerData!.userAcceleration.x; let y2 = accelerometerData!.userAcceleration.y; let z2 = accelerometerData!.userAcceleration.z; let dispStr = String(format:"g x: %1.2f, y: %1.2f, z: %1.2f a x: %1.2f y:%1.2f z:%1.2f",x,y,z,x2,y2,z2) self.changeMotionStatus(x,ax:x2,gy:y,ay:y2,gz:z,az:z2) self.updateCheck() print(dispStr) }) } } func jumpToMainMenu(){ let vc = self.storyboard?.instantiateViewControllerWithIdentifier("MainMenuVC") as! ViewController manager.stopDeviceMotionUpdates(); self.presentViewController(vc, animated: false, completion: nil) } @IBAction func leavePartyPressed(sender: UIButton) { sender.enabled = false; partyObj.deleteInBackgroundWithBlock{ (success: Bool, error: NSError?) -> Void in if (success) { // The object has been saved. self.jumpToMainMenu() } else { // There was a problem, check error.description print("failed to create a new party room") self.leavePartyButton.enabled = true; } } } func setSeqStart(){ clearSeq() isSettingSeq = true settingSeqNo = 0 self.setSeqButton.enabled = false self.seqLab.hidden = false } func setSeqEnd(){ isSettingSeq = false self.setSeqButton.enabled = true updateSeqArrayInParse() settingSeqNo = 0 } func updateSeqArrayInParse(){ partyObj["sequence"] = self.seqArray partyObj.saveInBackground() } func getCorrespondingSeqLabel(number:Int) -> UILabel{ switch (number){ case 1: return self.seqLabel1 case 2: return self.seqLabel2 case 3: return self.seqLabel3 case 4: return self.seqLabel4 default: return self.seqLabel1 } } func addOneSeq(motion:String){ self.seqArray.append(motion) settingSeqNo = seqArray.count let currentLabel = getCorrespondingSeqLabel(settingSeqNo) currentLabel.hidden = false currentLabel.text = motion } func clearSeq(){ self.isSettingSeq = false self.seqLab.hidden = true self.setSeqButton.enabled = true self.settingSeqNo = -1 seqArray.removeAll() updateSeqArrayInParse() for index in 1...5{ getCorrespondingSeqLabel(index).hidden = true } } @IBAction func setSeqPressed(sender: AnyObject) { if (!isSettingSeq){ setSeqStart() } } @IBAction func clearSeqPressed(sender: UIButton) { clearSeq(); } func parseInit(){ let partyQuery = PFQuery(className: "Party"); partyQuery.whereKey("userId", equalTo:userObj); partyQuery.getFirstObjectInBackgroundWithBlock{ (obj: PFObject?, error: NSError?) -> Void in if (error != nil){ print ("Fetching party query failed") } else{ self.partyObj = obj! } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. motionInit() parseInit() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
05fc5be4657cc6aef37d3efb7976999f
30.735099
173
0.557387
false
false
false
false
AjayOdedara/CoreKitTest
refs/heads/master
CoreKit/Pods/p2.OAuth2/Sources/Base/OAuth2Response.swift
mit
2
// // OAuth2Response.swift // OAuth2 // // Created by Pascal Pfiffner on 9/12/16. // Copyright © 2016 Pascal Pfiffner. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /** Encapsulates a URLResponse to a URLRequest. Instances of this class are returned from `OAuth2Requestable` calls, they can be used like so: perform(request: req) { response in do { let data = try response.responseData() // do what you must with `data` as Data and `response.response` as HTTPURLResponse } catch let error { // the request failed because of `error` } } */ open class OAuth2Response { /// The data that was returned. open var data: Data? /// The request that generated this response. open var request: URLRequest /// The underlying HTTPURLResponse. open var response: HTTPURLResponse /// Error reported by the underlying mechanisms. open var error: Error? public init(data: Data?, request: URLRequest, response: HTTPURLResponse, error: Error?) { self.data = data self.request = request self.response = response self.error = error } // MARK: - Response Check /** Throws errors if something with the request went wrong, noop otherwise. You can use this to quickly figure out how to proceed in request callbacks. If data is returned but the status code is >= 400, nothing will be raised **except** if there's a 401 or 403. - throws: Specific OAuth2Errors (.requestCancelled, .unauthorizedClient, .noDataInResponse) or any Error returned from the request - returns: Response data */ open func responseData() throws -> Data { if let error = error { if NSURLErrorDomain == error._domain && -999 == error._code { // request was cancelled throw OAuth2Error.requestCancelled } throw error } else if 401 == response.statusCode { throw OAuth2Error.unauthorizedClient } else if 403 == response.statusCode { throw OAuth2Error.forbidden } else if let data = data { return data } else { throw OAuth2Error.noDataInResponse } } /** Uses `responseData()`, then decodes JSON using `Foundation.JSONSerialization` on the resulting data (if there was any). - throws: Any error thrown by `responseData()`, plus .jsonParserError if JSON did not decode into `[String: Any]` - returns: OAuth2JSON on success */ open func responseJSON() throws -> OAuth2JSON { let data = try responseData() let json = try JSONSerialization.jsonObject(with: data, options: []) if let json = json as? OAuth2JSON { return json } throw OAuth2Error.jsonParserError } }
e8f6064452aac686c9b91995da61d007
28.091743
132
0.699779
false
false
false
false
HiSAGiN/KillingTime
refs/heads/master
test/AppDelegate.swift
gpl-3.0
1
// // AppDelegate.swift // test // // Created by Silbird-Tateyama on 2016/04/28. // Copyright © 2016年 Silbird-Tateyama. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self 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:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
fdf4429230b279358db698673d2d8602
53.737705
285
0.765199
false
false
false
false
sadawi/ModelKit
refs/heads/master
ModelKit/ModelStore/ArchiveModelStore.swift
mit
1
// // ArchiveModelStore.swift // Pods // // Created by Sam Williams on 2/13/16. // // import Foundation import PromiseKit enum ArchiveError: Error { case noPath case unarchiveError case archiveError case directoryError } private let kDefaultGroup = "" open class ArchiveModelStore: ListableModelStore, ClearableModelStore { open static let sharedInstance = ArchiveModelStore() public var valueTransformerContext: ModelValueTransformerContext = .defaultModelContext /** Unarchives the default group of instances of a model class. This will not include any lists of this model class that were saved with a group name. */ open func list<T : Model>(_ modelClass: T.Type) -> Promise<[T]> { return self.list(modelClass, group: kDefaultGroup) } /** Unarchives a named group of instances of a model class. - parameter modelClass: The model class to unarchive. - parameter group: An identifier for the group */ open func list<T : Model>(_ modelClass: T.Type, group: String) -> Promise<[T]> { let results = self.unarchive(modelClass, suffix: group) return Promise(value: results) } public func list<T : Model>(_ field: ModelArrayField<T>) -> Promise<[T]> { return Promise(value: field.value ?? []) } fileprivate func accumulateRelatedModels(_ models: [Model], suffix: String) -> [String:[Model]] { var registry:[String:[Model]] = [:] let add = { (model:Model?) -> () in guard let model = model else { return } let key = self.keyForClass(type(of: model)) + suffix var existing:[Model]? = registry[key] if existing == nil { existing = [] registry[key] = existing! } existing!.append(model) registry[key] = existing! } for model in models { add(model) for relatedModel in model.foreignKeyModels() { add(relatedModel) } } return registry } /** Archives a collection of instances, replacing the previously archived collection. A group name may be provided, which identifies a named set of instances that can be retrieved separately from the default group. - parameter modelClass: The class of models to be archived - parameter models: The list of models to be archived - parameter group: A specific group name identifying this model list. - parameter includeRelated: Whether the entire object graph should be archived. */ open func saveList<T: Model>(_ modelClass:T.Type, models: [T], group: String="", includeRelated: Bool = false) -> Promise<Void> { guard let _ = self.createdDirectory() else { return Promise(error: ArchiveError.directoryError) } let registry = self.accumulateRelatedModels(models, suffix: group) for (key, models) in registry { _ = self.archive(models, key: key) } return Promise<Void>(value: ()) } open func deleteAll() -> Promise<Void> { let filemanager = FileManager.default if let directory = self.directory() { do { try filemanager.removeItem(atPath: directory) return Promise<Void>(value: ()) } catch let error { return Promise(error: error) } } else { return Promise(error: ArchiveError.noPath) } } open func deleteAll<T : Model>(_ modelClass: T.Type) -> Promise<Void> { return self.deleteAll(modelClass, group: kDefaultGroup) } open func deleteAll<T : Model>(_ modelClass: T.Type, group suffix: String) -> Promise<Void> { let key = self.keyForClass(modelClass) + suffix if let path = self.pathForKey(key) { let filemanager = FileManager.default do { try filemanager.removeItem(atPath: path) return Promise<Void>(value: ()) } catch let error { return Promise(error: error) } } else { return Promise(error: ArchiveError.noPath) } } /** Loads all instances of a class, and recursively unarchives all classes of related (shell) models. */ @discardableResult fileprivate func unarchive<T: Model>(_ modelClass: T.Type, suffix: String, keysToIgnore:NSMutableSet=NSMutableSet()) -> [T] { let key = self.keyForClass(modelClass) + suffix if !keysToIgnore.contains(key) { keysToIgnore.add(key) if let path = self.pathForKey(key) { let unarchived = NSKeyedUnarchiver.unarchiveObject(withFile: path) if let dictionaries = unarchived as? [AttributeDictionary] { let models = dictionaries.map { modelClass.from(dictionaryValue: $0) }.flatMap { $0 } for model in models { for shell in model.incompleteChildModels() { self.unarchive(type(of: shell), suffix: suffix, keysToIgnore: keysToIgnore) } } return models } } } return [] } fileprivate func archive<T: Model>(_ models: [T], key: String) -> Bool { if let path = self.pathForKey(key) { let dictionaries = models.map { $0.dictionaryValue() } if NSKeyedArchiver.archiveRootObject(dictionaries, toFile: path) { return true } else { return false } } else { return false } } func keyForClass(_ cls: AnyClass) -> String { return cls.description() } func directory() -> String? { if let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last as NSString? { return path.appendingPathComponent("archives") } else { return nil } } func createdDirectory() -> String? { guard let path = self.directory() else { return nil } do { try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) return path } catch { return nil } } func pathForKey(_ key: String) -> String? { return (self.directory() as NSString?)?.appendingPathComponent(key) } }
046435087fcddac0d33588c39c0b2551
33.312821
148
0.574802
false
false
false
false
richardpiazza/SOSwift
refs/heads/master
Sources/SOSwift/NumberOrQuantitativeValue.swift
mit
1
import Foundation import CodablePlus public enum NumberOrQuantitativeValue: Codable { case number(value: Number) case quantitativeValue(value: QuantitativeValue) public init(_ value: Number) { self = .number(value: value) } public init(_ value: QuantitativeValue) { self = .quantitativeValue(value: value) } public init(from decoder: Decoder) throws { var dictionary: [String : Any]? do { let jsonContainer = try decoder.container(keyedBy: DictionaryKeys.self) dictionary = try jsonContainer.decode(Dictionary<String, Any>.self) } catch { } guard let jsonDictionary = dictionary else { let container = try decoder.singleValueContainer() let value = try container.decode(Number.self) self = .number(value: value) return } guard let type = jsonDictionary[SchemaKeys.type.rawValue] as? String else { throw SchemaError.typeDecodingError } let container = try decoder.singleValueContainer() switch type { case QuantitativeValue.schemaName: let value = try container.decode(QuantitativeValue.self) self = .quantitativeValue(value: value) default: throw SchemaError.typeDecodingError } } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .number(let value): try container.encode(value) case .quantitativeValue(let value): try container.encode(value) } } public var number: Number? { switch self { case .number(let value): return value default: return nil } } public var quantitativeValue: QuantitativeValue? { switch self { case .quantitativeValue(let value): return value default: return nil } } }
241dd3f4149e61c72589773955be4541
26.986842
83
0.573578
false
false
false
false
eurofurence/ef-app_ios
refs/heads/release/4.0.0
Packages/EurofurenceComponents/Tests/EventDetailComponentTests/Presenter Tests/EventDetailPresenterTestBuilder.swift
mit
1
import EurofurenceModel import EventDetailComponent import Foundation import UIKit.UIViewController import XCTComponentBase import XCTEurofurenceModel import XCTEventDetailComponent class EventDetailPresenterTestBuilder { struct Context { var producedViewController: UIViewController var scene: CapturingEventDetailScene var hapticEngine: CapturingSelectionChangedHaptic var delegate: CapturingEventDetailComponentDelegate var eventInteractionRecorder: CapturingEventInteractionRecorder } private var viewModelFactory: EventDetailViewModelFactory init() { viewModelFactory = DummyEventDetailViewModelFactory() } @discardableResult func with(_ viewModelFactory: EventDetailViewModelFactory) -> EventDetailPresenterTestBuilder { self.viewModelFactory = viewModelFactory return self } func build(for event: FakeEvent = .random) -> Context { let sceneFactory = StubEventDetailSceneFactory() let hapticEngine = CapturingSelectionChangedHaptic() let delegate = CapturingEventDetailComponentDelegate() let interactionRecorder = CapturingEventInteractionRecorder() let module = EventDetailComponentBuilder( eventDetailViewModelFactory: viewModelFactory, interactionRecorder: interactionRecorder ) .with(sceneFactory) .with(hapticEngine) .build() .makeEventDetailComponent(for: event.identifier, delegate: delegate) return Context( producedViewController: module, scene: sceneFactory.interface, hapticEngine: hapticEngine, delegate: delegate, eventInteractionRecorder: interactionRecorder ) } } extension EventDetailPresenterTestBuilder.Context { func simulateSceneDidLoad() { scene.simulateSceneDidLoad() } func simulateSceneDidAppear() { scene.simulateSceneDidAppear() } func simulateSceneDidDisappear() { scene.simulateSceneDidDisappear() } }
27cc445a858aab446ac9aeeed31aca93
28.971429
99
0.712107
false
false
false
false
shineycode/cocoaconf-ble
refs/heads/master
talk-demo/source/central/PeripheralStore.swift
mit
1
// // PeripheralStore.swift // talk-demo // // Created by Shiney Code on 10/25/15. // Copyright © 2015 Shiney Code. All rights reserved. // import Foundation import CoreBluetooth class PeripheralStore { private(set) var peripherals: [String: PeripheralData] init() { peripherals = [String: PeripheralData]() } func peripheralWithIdentifier(identifier: String) -> PeripheralData? { guard let foundPeripheral = peripherals[identifier] else { return nil } return foundPeripheral } func serviceDataForPeripheral(peripheral: CBPeripheral, characteristic: CBCharacteristic) -> ServiceData? { let peripheralId = PeripheralData.generateIdentifier(peripheral) guard let peripheralData = peripheralWithIdentifier(peripheralId) else { return nil } return peripheralData.findServiceData(characteristic.service) } /** Adds the discovered peripheral to the local collection of peripherals */ func addDiscoverPeripheral(peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) -> PeripheralData { let peripheralData = PeripheralData(peripheral: peripheral, advertisementData: advertisementData, RSSI: RSSI) peripherals[peripheralData.identifier] = peripheralData return peripheralData } /** Adds the discovered services to the already stored peripheral */ func addDiscoveredServices(services: [CBService], associatedPeripheral: CBPeripheral) -> [ServiceData] { var addedServices = [ServiceData]() // Get the peripheral that's already stored. If it doesn't exist, we won't create one because we don't have // any advertisement data & RSSI associated with this unknown peripheral. let peripheralId = PeripheralData.generateIdentifier(associatedPeripheral) guard let peripheralData = peripherals[peripheralId] else { return addedServices } // Add these services to the existing collection for associated peripheral for service in services { let newService = ServiceData(rawService: service, characteristics: nil) peripheralData.addServiceData(newService) // Also add to local copy so we can return all added services back to the caller addedServices.append(newService) } return addedServices } func addDiscoveredCharacteristics(characteristics: [CBCharacteristic], associatedService:CBService, associatedPeripheral: CBPeripheral) -> (serviceData: ServiceData, addedCharacteristics: [CharacteristicData])? { var addedCharacteristics = [CharacteristicData]() let peripheralId = PeripheralData.generateIdentifier(associatedPeripheral) guard let peripheralData = peripherals[peripheralId] else { return nil } guard let serviceData = peripheralData.findServiceData(associatedService) else { return nil } // Add these characteristics to our existing collection for the associated service for characteristic in characteristics { print("Looking at characteristic: \(characteristic)") let characteristicData = CharacteristicData(rawCharacteristic: characteristic) serviceData.addCharacteristicData(characteristicData) // Also add to the local copy so we can return all added characteristics back to the caller addedCharacteristics.append(characteristicData) } return (serviceData: serviceData, addedCharacteristics: addedCharacteristics) } func updateCharacteristicValue(value: NSData?, forCharacteristic characteristic: CBCharacteristic, associatedPeripheral: CBPeripheral) -> CharacteristicData? { guard let _ = value else { return nil } let peripheralId = PeripheralData.generateIdentifier(associatedPeripheral) guard let peripheralData = peripherals[peripheralId] else { return nil } let serviceId = ServiceData.generateIdentifier(characteristic.service) guard let serviceData = peripheralData.findServiceDataById(serviceId) else { return nil } // Find the associated characteristic and update the value let charId = CharacteristicData.generateIdentifier(characteristic) guard let characteristicData = serviceData.findCharacteristicDataById(charId)else { return nil } return characteristicData } func clear() { peripherals.removeAll() } }
2d0380f6be39c6b28d0e6bdbe0b77464
36.590551
163
0.67798
false
false
false
false
p-orbitum/XAsync
refs/heads/master
Application/XAsyncSample/XAsyncSampleSwift/main.swift
mit
1
// // main.swift // XAsyncSampleSwift // // Created by Pavel Gorb on 4/11/16. // Copyright © 2016 Orbitum. All rights reserved. // import Foundation // --------------- AWAIT ------------------- // let t1 = XAsyncTask { (task) in print("Task 1 has been started.") for _ in 0..<1000000000 { } print("Task 1 is about to end.") } print("Task 1 is about to start.") t1.await() print("Task 1 has been done.") print("<<<<<<<<<<<<<<<!!!!!!!!!!>>>>>>>>>>>>>>>>>>") // --------------- AWAIT ------------------- // // --------------- AWAIT RESULT ------------ // let t2 = XAsyncTask { (task) in print("Task 2 has been started.") var i = 0 for _ in 0..<1000000000 { i += 1; } print("Task 2 is about to end.") task?.result = i; } print("Task 2 is about to start.") t2.await() print("Task 2 has been done with result: \(t2.result)") print("<<<<<<<<<<<<<<<!!!!!!!!!!>>>>>>>>>>>>>>>>>>") // --------------- AWAIT RESULT ------------ // // --------------- AWAIT SIGNAL ------------------- // let t3 = XAsyncTask { (task) in print("Signal task 3 has been started."); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) { var i = 0; for _ in 0..<1000000000 { i += 1 } task?.result = i task?.fireSignal() } print("Signal task 3 is about to end.") } t3.awaitSignal() print("Signal task 3 has been done: \(t3.result)") print("<<<<<<<<<<<<<<<!!!!!!!!!!>>>>>>>>>>>>>>>>>>") // --------------- AWAIT SIGNAL ------------------- // // ------------- AWAIT SEQUENCE ---------------- // let one_s = XAsyncTask { (task) in print("Sequence task 1 has been started.") for _ in 0..<100000000 { } print("Sequence task 1 is about to end.") } let two_s = XAsyncTask { (task) in print("Sequence task 2 has been started.") for _ in 0..<100000000 { } print("Sequence task 2 is about to end.") } let three_s = XAsyncTask { (task) in print("Sequence task 3 has been started.") for _ in 0..<100000000 { } print("Sequence task 3 is about to end.") } print("About to start sequence.") XAsyncTask.awaitSequence([one_s, two_s, three_s]) print("Sequence has been finished") print("<<<<<<<<<<<<<<<!!!!!!!!!!>>>>>>>>>>>>>>>>>>") // ---------------AWAIT SEQUENCE ------------------ // // ------------- AWAIT ALL ---------------- // let one_all = XAsyncTask { (task) in print("Pool task 1 has been started.") for _ in 0..<100000000 { } print("Pool task 1 is about to end.") } let two_all = XAsyncTask { (task) in print("Pool task 2 has been started.") for _ in 0..<100000000 { } print("Pool task 2 is about to end.") } let three_all = XAsyncTask { (task) in print("Pool task 3 has been started.") for _ in 0..<100000000 { } print("Pool task 3 is about to end.") } let four_all = XAsyncTask { (task) in print("Pool task 4 has been started.") for _ in 0..<100000000 { } print("Pool task 4 is about to end.") } let five_all = XAsyncTask { (task) in print("Pool task 5 has been started.") for _ in 0..<100000000 { } print("Pool task 5 is about to end.") } print("About to start all tasks' pool.") XAsyncTask.awaitAll(Set(arrayLiteral: one_all, two_all, three_all, four_all, five_all)) print("Sequence has been finished") print("<<<<<<<<<<<<<<<!!!!!!!!!!>>>>>>>>>>>>>>>>>>"); // ---------------AWAIT ALL ------------------ // // ------------- AWAIT ANY ---------------- // let one_any = XAsyncTask { (task) in print("Pool task 1 has been started.") for _ in 0..<100000000 { } print("Pool task 1 is about to end.") } let two_any = XAsyncTask { (task) in print("Pool task 2 has been started.") for _ in 0..<100000000 { } print("Pool task 2 is about to end.") } let three_any = XAsyncTask { (task) in print("Pool task 3 has been started.") for _ in 0..<100000000 { } print("Pool task 3 is about to end.") } let four_any = XAsyncTask { (task) in print("Pool task 4 has been started.") for _ in 0..<100000000 { } print("Pool task 4 is about to end.") } let five_any = XAsyncTask { (task) in print("Pool task 5 has been started.") for _ in 0..<100000000 { } print("Pool task 5 is about to end.") } print("About to start ANY.") XAsyncTask.awaitAny(Set(arrayLiteral: one_all, two_all, three_all, four_all, five_all)) print("Waiting has been finished.") print("<<<<<<<<<<<<<<<!!!!!!!!!!>>>>>>>>>>>>>>>>>>"); // ---------------AWAIT ANY ------------------ //
e08a1caba2e0a427788e26e96ef47cb2
29.152318
87
0.519438
false
false
false
false
openbuild-sheffield/jolt
refs/heads/master
Sources/RouteCMS/model.CMSWords.swift
gpl-2.0
1
import PerfectLib import OpenbuildExtensionPerfect public class ModelCMSWords: JSONConvertibleObject, DocumentationProtocol { static let registerName = "CMS.CMSWords" public var cms_words_id: Int? public var handle: String? public var words: String? public var errors: [String: String] = [:] public init(dictionary: [String : Any]) { self.cms_words_id = Int(dictionary["cms_words_id"]! as! UInt32) self.handle = dictionary["handle"] as? String self.words = dictionary["words"] as? String } public init(cms_words_id: Int, handle: String, words: String) { self.cms_words_id = cms_words_id self.handle = handle self.words = words } public init(cms_words_id: String, handle: String, words: String) { self.cms_words_id = Int(cms_words_id) self.handle = handle self.words = words } public init(handle: String, words: String) { self.handle = handle self.words = words } public override func getJSONValues() -> [String : Any] { return [ JSONDecoding.objectIdentifierKey:ModelCMSWords.registerName, "cms_words_id": cms_words_id! as Int, "handle": handle! as String, "words": words! as String ] } public static func describeRAML() -> [String] { //TODO / FIXME return ["CMS: ModelCMSWords TODO / FIXME"] } }
f7e5238e036bc2f889d772763af0aa7a
27.86
74
0.612344
false
false
false
false
jasl/RouterX
refs/heads/master
Sources/RouterX/Router.swift
mit
1
import Foundation open class Router<Context> { public typealias MatchedHandler = (MatchResult<Context>) -> Void public typealias UnmatchHandler = ((URL, _ context: Context?) -> Void) private let core: RouterXCore = RouterXCore() private let defaultUnmatchHandler: UnmatchHandler? private var handlerMappings: [PatternIdentifier: MatchedHandler] = [:] public init(defaultUnmatchHandler: UnmatchHandler? = nil) { self.defaultUnmatchHandler = defaultUnmatchHandler } open func register(pattern: String, handler: @escaping MatchedHandler) throws { try core.register(pattern: pattern) handlerMappings[pattern] = handler } @discardableResult open func match(_ url: URL, context: Context? = nil, unmatchHandler: UnmatchHandler? = nil) -> Bool { guard let matchedRoute = core.match(url), let matchHandler = handlerMappings[matchedRoute.patternIdentifier] else { let expectUnmatchHandler = unmatchHandler ?? defaultUnmatchHandler expectUnmatchHandler?(url, context) return false } let result = MatchResult<Context>(url: url, parameters: matchedRoute.parametars, context: context) matchHandler(result) return true } @discardableResult open func match(_ path: String, context: Context? = nil, unmatchHandler: UnmatchHandler? = nil) -> Bool { guard let url = URL(string: path) else { return false } return match(url, context: context, unmatchHandler: unmatchHandler) } } extension Router: CustomDebugStringConvertible, CustomStringConvertible { open var description: String { return self.core.description } open var debugDescription: String { return self.description } }
aefd1751c45f8954f9e8bdbc5f14cac1
34.333333
109
0.68424
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/uidatepicker/ExUIDatePicker/ExUIDatePicker/InputBarController.swift
mit
1
// // InputBarController.swift // ExUIDatePicker // // Created by 黄伯驹 on 28/01/2018. // Copyright © 2018 hsin. All rights reserved. // import UIKit let width = UIScreen.main.bounds.width // https://stackoverflow.com/questions/25816994/changing-the-frame-of-an-inputaccessoryview-in-ios-8 class InputBar: UIView, UITextViewDelegate { lazy var textView: UITextView = { let textView = UITextView() textView.delegate = self textView.layer.borderWidth = 0.5 textView.layer.cornerRadius = 5 textView.layer.borderColor = UIColor.lightGray.cgColor textView.isScrollEnabled = false textView.translatesAutoresizingMaskIntoConstraints = false return textView }() private lazy var visualView: UIVisualEffectView = { let blurEffect = UIBlurEffect(style: .extraLight) let visualView = UIVisualEffectView(effect: blurEffect) visualView.translatesAutoresizingMaskIntoConstraints = false return visualView }() private lazy var emojiButton: UIButton = { let button = InputBar.generateButton(with: "icon_emotion") return button }() private lazy var secondButton: UIButton = { let button = InputBar.generateButton(with: "icon_emotion") return button }() private lazy var thirdButton: UIButton = { let button = InputBar.generateButton(with: "icon_emotion") return button }() static func generateButton(with imageName: String) -> UIButton { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.setImage(UIImage(named: imageName), for: .normal) button.addTarget(self, action: #selector(showEmojiKeyboard), for: .touchUpInside) return button } override init(frame: CGRect) { super.init(frame: frame) autoresizingMask = .flexibleHeight backgroundColor = .red addSubview(visualView) visualView.topAnchor.constraint(equalTo: topAnchor).isActive = true visualView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true visualView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true visualView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true let margin: CGFloat = 8 addSubview(emojiButton) emojiButton.leadingAnchor.constraint(equalTo: leadingAnchor, constant: margin).isActive = true emojiButton.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true addSubview(textView) textView.leadingAnchor.constraint(equalTo: emojiButton.trailingAnchor, constant: margin).isActive = true textView.topAnchor.constraint(equalTo: topAnchor, constant: 6).isActive = true textView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true addSubview(secondButton) secondButton.leadingAnchor.constraint(equalTo: textView.trailingAnchor, constant: margin).isActive = true secondButton.widthAnchor.constraint(equalTo: emojiButton.widthAnchor).isActive = true secondButton.heightAnchor.constraint(equalTo: emojiButton.heightAnchor).isActive = true secondButton.centerYAnchor.constraint(equalTo: emojiButton.centerYAnchor).isActive = true addSubview(thirdButton) thirdButton.leadingAnchor.constraint(equalTo: secondButton.trailingAnchor, constant: margin).isActive = true thirdButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -margin).isActive = true thirdButton.widthAnchor.constraint(equalTo: emojiButton.widthAnchor).isActive = true thirdButton.heightAnchor.constraint(equalTo: emojiButton.heightAnchor).isActive = true thirdButton.centerYAnchor.constraint(equalTo: emojiButton.centerYAnchor).isActive = true } func textViewDidChange(_ textView: UITextView) { invalidateIntrinsicContentSize() } @objc func showEmojiKeyboard(_ sender: UIButton) { sender.isSelected = !sender.isSelected if sender.isSelected { let keyboardView = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 200)) keyboardView.backgroundColor = .red textView.inputView = keyboardView } else { textView.inputView = nil } textView.reloadInputViews() } override var intrinsicContentSize: CGSize { // Calculate intrinsicContentSize that will fit all the text let textSize = textView.contentSize return CGSize(width: bounds.width, height: textSize.height) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class InputBarController: BaseController { let accessoryView = InputBar(frame: CGRect(x: 0, y: 0, width: width, height: 44)) override var inputAccessoryView: UIView? { return accessoryView } override var canBecomeFirstResponder: Bool { return true } override func initSubviews() { } }
6ea8f0a7252bef78cda6a489f29c9652
36.386861
116
0.693089
false
false
false
false
pkx0128/UIKit
refs/heads/master
多页面/多页面/ArticleViewController.swift
mit
1
// // ArticleViewController.swift // 多页面 // // Created by pankx on 2017/9/25. // Copyright © 2017年 pankx. All rights reserved. // import UIKit class ArticleViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.orange let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 40)) button.center = view.center button.setTitle("goBack", for: .normal) button.setTitleColor(UIColor.black, for: .normal) button.addTarget(self, action: #selector(goback), for: .touchUpInside) view.addSubview(button) let goDetail = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 40)) goDetail.center = CGPoint(x: view.bounds.width * 0.5, y: view.bounds.height * 0.6) goDetail.setTitle("goDetail", for: .normal) goDetail.setTitleColor(UIColor.black, for: .normal) goDetail.addTarget(self, action: #selector(gotoDetail), for: .touchUpInside) view.addSubview(goDetail) } @objc func gotoDetail() { self.present(ArticleDetailViewController(), animated: true, completion: nil) } @objc func goback() { self.dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
43fd42a0de997a5ee4535921fb9018b9
31.410714
106
0.647934
false
false
false
false
SoufianeLasri/Sisley
refs/heads/master
Sisley/SharingButton.swift
mit
1
// // SharingButton.swift // Sisley // // Created by Soufiane Lasri on 25/12/2015. // Copyright © 2015 Soufiane Lasri. All rights reserved. // import UIKit class SharingButton: UIButton { init( frame: CGRect, imageName: String ) { super.init( frame: frame ) self.backgroundColor = UIColor.whiteColor() self.layer.cornerRadius = self.frame.width / 2 self.layer.borderWidth = 2.0 self.layer.borderColor = UIColor( red: 0.89, green: 0.81, blue: 0.47, alpha: 1.0 ).CGColor self.alpha = 0 self.frame.origin.y += 5 let imageView = UIImageView( frame: CGRect( x: 0, y: 0, width: self.frame.width, height: self.frame.height ) ) imageView.image = UIImage( named: imageName ) imageView.layer.cornerRadius = self.frame.width / 2 imageView.layer.masksToBounds = true self.addSubview( imageView ) } func toggleButton( openingState: Bool ) { if openingState == true { self.alpha = 1 self.frame.origin.y -= 5 } else { self.alpha = 0 self.frame.origin.y += 5 } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
f0b24bf6ee296551b92b278851316c81
29.069767
118
0.584687
false
false
false
false
ljshj/actor-platform
refs/heads/master
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Ringtones/AARingtonesViewController.swift
mit
1
// // AARingtonesViewController.swift // ActorSDK // // Created by Alexey Galaev on 5/27/16. // Copyright © 2016 Steve Kite. All rights reserved. // import Foundation import UIKit import AVFoundation public class AARingtonesViewController: AATableViewController { var audioPlayer: AVAudioPlayer! var selectedRingtone: String = "" var completion: ((String) -> ())! let rootSoundDirectories: [String] = ["/Library/Ringtones"/*,"/System/Library/Audio/UISounds"*/] var directories: [String] = [] var soundFiles: [(directory: String, files: [String])] = [] init() { super.init(style: UITableViewStyle.Plain) self.title = AALocalized("Ringtones") let cancelButtonItem = UIBarButtonItem(title: AALocalized("NavigationCancel"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("dismiss")) let doneButtonItem = UIBarButtonItem(title: AALocalized("NavigationDone"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("dismiss")) self.navigationItem.setLeftBarButtonItem(cancelButtonItem, animated: false) self.navigationItem.setRightBarButtonItem(doneButtonItem, animated: false) } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func viewDidLoad() { super.viewDidLoad() for directory in rootSoundDirectories { directories.append(directory) let newSoundFile: (directory: String, files: [String]) = (directory, []) soundFiles.append(newSoundFile) } getDirectories() loadSoundFiles() tableView.rowHeight = 44.0 tableView.sectionIndexBackgroundColor = UIColor.clearColor() } override public func viewWillDisappear(animated: Bool) { super.viewWillDisappear(true) if(audioPlayer != nil && audioPlayer.playing){ audioPlayer.stop() } } public override func viewDidDisappear(animated: Bool) { completion(selectedRingtone) } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func getDirectories() { let fileManager: NSFileManager = NSFileManager() for directory in rootSoundDirectories { let directoryURL: NSURL = NSURL(fileURLWithPath: "\(directory)", isDirectory: true) do { if let URLs: [NSURL] = try fileManager.contentsOfDirectoryAtURL(directoryURL, includingPropertiesForKeys: [NSURLIsDirectoryKey], options: NSDirectoryEnumerationOptions()) { var urlIsaDirectory: ObjCBool = ObjCBool(false) for url in URLs { if fileManager.fileExistsAtPath(url.path!, isDirectory: &urlIsaDirectory) { if urlIsaDirectory { let directory: String = "\(url.relativePath!)" let files: [String] = [] let newSoundFile: (directory: String, files: [String]) = (directory, files) directories.append("\(directory)") soundFiles.append(newSoundFile) } } } } } catch { debugPrint("\(error)") } } } func loadSoundFiles() { for i in 0...directories.count-1 { let fileManager: NSFileManager = NSFileManager() let directoryURL: NSURL = NSURL(fileURLWithPath: directories[i], isDirectory: true) do { if let URLs: [NSURL] = try fileManager.contentsOfDirectoryAtURL(directoryURL, includingPropertiesForKeys: [NSURLIsDirectoryKey], options: NSDirectoryEnumerationOptions()) { var urlIsaDirectory: ObjCBool = ObjCBool(false) for url in URLs { if fileManager.fileExistsAtPath(url.path!, isDirectory: &urlIsaDirectory) { if !urlIsaDirectory { soundFiles[i].files.append("\(url.lastPathComponent!)") } } } } } catch { debugPrint("\(error)") } } } override public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return soundFiles[section].files.count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Ringtones" } func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 44 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } override public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let fileName: String = soundFiles[indexPath.section].files[indexPath.row] let cell: AACommonCell = tableView.dequeueCell(indexPath) cell.style = .Normal let name = fileName.componentsSeparatedByString(".m4r") cell.textLabel?.text = name.first return cell } func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { if let cell = tableView.cellForRowAtIndexPath(indexPath) as? AACommonCell { cell.style = .Normal } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let directory: String = soundFiles[indexPath.section].directory let fileName: String = soundFiles[indexPath.section].files[indexPath.row] let fileURL: NSURL = NSURL(fileURLWithPath: "\(directory)/\(fileName)") do { audioPlayer = try AVAudioPlayer(contentsOfURL: fileURL) audioPlayer.play() } catch { debugPrint("\(error)") selectedRingtone = "" } let cell = tableView.cellForRowAtIndexPath(indexPath) as! AACommonCell selectedRingtone = soundFiles[indexPath.section].files[indexPath.row] cell.style = .Checkmark } }
69f00c0cbb9216f1cde10244a2d87d37
38.177515
188
0.606555
false
false
false
false
michael-lehew/swift-corelibs-foundation
refs/heads/master
Foundation/NSSpecialValue.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // internal protocol NSSpecialValueCoding { static func objCType() -> String init(bytes value: UnsafeRawPointer) func encodeWithCoder(_ aCoder: NSCoder) init?(coder aDecoder: NSCoder) func getValue(_ value: UnsafeMutableRawPointer) // Ideally we would make NSSpecialValue a generic class and specialise it for // NSPoint, etc, but then we couldn't implement NSValue.init?(coder:) because // it's not yet possible to specialise classes with a type determined at runtime. // // Nor can we make NSSpecialValueCoding conform to Equatable because it has associated // type requirements. // // So in order to implement equality and hash we have the hack below. func isEqual(_ value: Any) -> Bool var hash: Int { get } var description: String? { get } } internal class NSSpecialValue : NSValue { // Originally these were functions in NSSpecialValueCoding but it's probably // more convenient to keep it as a table here as nothing else really needs to // know about them private static let _specialTypes : Dictionary<Int, NSSpecialValueCoding.Type> = [ 1 : NSPoint.self, 2 : NSSize.self, 3 : NSRect.self, 4 : NSRange.self, 12 : NSEdgeInsets.self ] private static func _typeFromFlags(_ flags: Int) -> NSSpecialValueCoding.Type? { return _specialTypes[flags] } private static func _flagsFromType(_ type: NSSpecialValueCoding.Type) -> Int { for (F, T) in _specialTypes { if T == type { return F } } return 0 } private static func _objCTypeFromType(_ type: NSSpecialValueCoding.Type) -> String? { for (_, T) in _specialTypes { if T == type { return T.objCType() } } return nil } internal static func _typeFromObjCType(_ type: UnsafePointer<Int8>) -> NSSpecialValueCoding.Type? { let objCType = String(cString: type) for (_, T) in _specialTypes { if T.objCType() == objCType { return T } } return nil } internal var _value : NSSpecialValueCoding init(_ value: NSSpecialValueCoding) { self._value = value } required init(bytes value: UnsafeRawPointer, objCType type: UnsafePointer<Int8>) { guard let specialType = NSSpecialValue._typeFromObjCType(type) else { NSUnimplemented() } self._value = specialType.init(bytes: value) } override func getValue(_ value: UnsafeMutableRawPointer) { self._value.getValue(value) } convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } let specialFlags = aDecoder.decodeInteger(forKey: "NS.special") guard let specialType = NSSpecialValue._typeFromFlags(specialFlags) else { return nil } guard let specialValue = specialType.init(coder: aDecoder) else { return nil } self.init(specialValue) } override func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(NSSpecialValue._flagsFromType(type(of: _value)), forKey: "NS.special") _value.encodeWithCoder(aCoder) } override var objCType : UnsafePointer<Int8> { let typeName = NSSpecialValue._objCTypeFromType(type(of: _value)) return typeName!._bridgeToObjectiveC().utf8String! // leaky } override var classForCoder: AnyClass { // for some day when we support class clusters return NSValue.self } override var description : String { if let description = _value.description { return description } else { return super.description } } override func isEqual(_ value: Any?) -> Bool { if let object = value as? NSObject { if self === object { return true } else if let special = object as? NSSpecialValue { return _value.isEqual(special._value) } } return false } override var hash: Int { return _value.hash } }
863da3fd85345605abbf8f46fadff584
31.286667
103
0.611398
false
false
false
false
milk-cocoa/milkcocoa-swift-sdk
refs/heads/master
MilkCocoa/DataStore.swift
mit
1
/* // // DataStore.swift // MilkCocoa // // Created by HIYA SHUHEI on 2015/11/03. // The MIT License (MIT) Copyright (c) 2014 Technical Rockstars, Inc Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation public class DataStore { private var milkcocoa : MilkCocoa private var path : String private var send_callback : ((DataElement)->Void)? private var push_callback : ((DataElement)->Void)? public init(milkcocoa: MilkCocoa, path: String) { self.milkcocoa = milkcocoa; self.path = path; self.send_callback = nil; } public func on(event: String, callback: (DataElement)->Void) { self.milkcocoa.subscribe(self.path, event: event) if(event == "send") { self.send_callback = callback }else if(event == "push"){ self.push_callback = callback } } public func send(params : [String: AnyObject]) { self.milkcocoa.publish(self.path, event: "send", params: [ "params":params]) } public func push(params : [String: AnyObject]) { self.milkcocoa.publish(self.path, event: "push", params: [ "params":params]) } public func _fire_send(params : DataElement) { if let _send_cb = self.send_callback { _send_cb(params) } } public func _fire_push(params : DataElement) { if let _send_cb = self.push_callback { _send_cb(params) } } public func history()->History { return History(datastore: self) } } public class DataElement { private var _data : [String: AnyObject]; public init(_data : [String: AnyObject]) { self._data = Dictionary(); self.fromRaw(_data); } public func fromRaw(rawdata : [String: AnyObject]) { self._data["id"] = rawdata["id"] do { if(rawdata["params"] != nil) { //in case of on let params = rawdata["params"] self._data["value"] = params }else if(rawdata["value"] != nil) { //in case of query let valueJSON = rawdata["value"] as! String let valueJSON_data = valueJSON.dataUsingEncoding(NSUTF8StringEncoding) self._data["value"] = try NSJSONSerialization.JSONObjectWithData(valueJSON_data!, options: NSJSONReadingOptions.AllowFragments) as! [String: AnyObject] } } catch let error as NSError { print(error) } } public func getId()->String { return self._data["id"] as! String; } public func getValue()->[String: AnyObject] { return self._data; } public func getValue(key:String)->AnyObject? { return self._data[key]; } } public protocol HistoryDelegate : class { func onData(dataelement: DataElement); func onError(error: NSError); func onEnd(); } public class History { public weak var delegate: HistoryDelegate? private var datastore : DataStore; private var onDataHandler :([DataElement]->Void)? private var onErrorHandler :(NSError->Void)? public init(datastore: DataStore) { self.datastore = datastore self.onDataHandler = nil } public func onData(h:[DataElement]->Void) { self.onDataHandler = h } public func onError(h:NSError->Void) { self.onErrorHandler = h } public func run() { self.datastore.milkcocoa.call("query", params: ["path":self.datastore.path, "limit":"50", "sort":"DESC"], callback: { data -> Void in print(data) /* let content = data["content"] let dataelementlist:[DataElement]? = content!["d"].map({ DataElement(_data: $0 as! [String : AnyObject]) }) self.onDataHandler?(dataelementlist!) */ }, error_handler: { (error) -> Void in self.onErrorHandler?(error) }) } }
61bf9333f22d660c9f41129bde77082a
31.012658
167
0.611507
false
false
false
false
corderoi/Microblast
refs/heads/master
Microblast/Antibody.swift
mit
1
// // Antibody.swift // Microblast // // Created by Ian Cordero on 11/13/14. // Copyright (c) 2014 Ian Cordero. All rights reserved. // import AVFoundation // Antibody ////////////////////////////////////////////////////////////////// class Antibody { init(positionX: Int, positionY: Int = 0, wCell: WhiteBloodCell, direction: CGPoint = CGPoint(x: 0, y: 1), priority: Int = 1) { self.positionX = positionX self.positionY = positionY self.wCell = wCell self.direction = direction speed = 25 self.priority = priority } func die() { } var positionX: Int var positionY: Int var direction: CGPoint var speed: Int var priority: Int var wCell: WhiteBloodCell? } class Piercing: Antibody { init(positionX: Int, positionY: Int = 0, wCell: WhiteBloodCell, direction: CGPoint = CGPoint(x: 0, y: 1)) { super.init(positionX: positionX, positionY: positionY, wCell: wCell, direction: direction, priority: 4) } } class HorizontalLeft: Antibody { init(positionX: Int, positionY: Int = 0, wCell: WhiteBloodCell, direction: CGPoint = CGPoint(x: 0, y: 1)) { super.init(positionX: positionX, positionY: positionY, wCell: wCell, direction: direction, priority: 3) } override func die() { if let whiteBloodCell = wCell { let newAntibody = Piercing(positionX: positionX, positionY: positionY, wCell: whiteBloodCell, direction: CGPoint(x: -1, y: 0)) whiteBloodCell.antibodies.append(newAntibody) whiteBloodCell.field?.game?.delegate?.antibodyDidAppear(whiteBloodCell.field!.game, antibody: newAntibody) } } } class HorizontalRight: Antibody { init(positionX: Int, positionY: Int = 0, wCell: WhiteBloodCell, direction: CGPoint = CGPoint(x: 0, y: 1)) { super.init(positionX: positionX, positionY: positionY, wCell: wCell, direction: direction, priority: 3) } override func die() { if let whiteBloodCell = wCell { let newAntibody = Piercing(positionX: positionX, positionY: positionY, wCell: whiteBloodCell, direction: CGPoint(x: 1, y: 0)) whiteBloodCell.antibodies.append(newAntibody) whiteBloodCell.field?.game?.delegate?.antibodyDidAppear(whiteBloodCell.field!.game, antibody: newAntibody) } } } class DiagonalShot: Antibody { init(positionX: Int, positionY: Int = 0, wCell: WhiteBloodCell, direction: CGPoint = CGPoint(x: 0, y: 1)) { super.init(positionX: positionX, positionY: positionY, wCell: wCell, direction: direction, priority: 3) } override func die() { if let whiteBloodCell = wCell { let newAntibodyLeft = DiagonalSplit(positionX: positionX, positionY: positionY, wCell: whiteBloodCell, direction: CGPoint(x: -1, y: 1)) whiteBloodCell.antibodies.append(newAntibodyLeft) whiteBloodCell.field?.game?.delegate?.antibodyDidAppear(whiteBloodCell.field!.game, antibody: newAntibodyLeft) let newAntibodyRight = DiagonalSplit(positionX: positionX, positionY: positionY, wCell: whiteBloodCell, direction: CGPoint(x: 1, y: 1)) whiteBloodCell.antibodies.append(newAntibodyRight) whiteBloodCell.field?.game?.delegate?.antibodyDidAppear(whiteBloodCell.field!.game, antibody: newAntibodyRight) } } } class DiagonalSplit: Antibody { init(positionX: Int, positionY: Int = 0, wCell: WhiteBloodCell, direction: CGPoint = CGPoint(x: 0, y: 1)) { super.init(positionX: positionX, positionY: positionY, wCell: wCell, direction: direction, priority: 4) } }
ea9a4a6ab314e760b257394792e6b0c0
32.371681
147
0.637931
false
false
false
false
taqun/HBR
refs/heads/master
HBR/Classes/Model/AppConstant.swift
mit
1
// // AppConstant.swift // HBR // // Created by taqun on 2014/11/21. // Copyright (c) 2014年 envoixapp. All rights reserved. // import UIKit class AppConstant: NSObject { } enum EntryExpireInterval: String { case ThreeDays = "3日" case OneWeek = "1週間" case OneMonth = "1ヶ月" case None = "すべて" } enum RestoreTransactionState: String { case Restoreing = "restoreingTransaction" case Complete = "completeRestoreTransaction" case Failed = "failedRestoreTransaction" case None = "notRestoreTransaction" }
9f93cbac0113d1d53a23bb2c520098d5
19.925926
55
0.658407
false
false
false
false
Bartlebys/Bartleby
refs/heads/master
Bartleby.xOS/core/Context.swift
apache-2.0
1
// // Context.swift // BartlebyKit // // Created by Benoit Pereira da silva on 22/10/2016. // // import Foundation public struct Context: Consignable { // A developer set code to provide filtering public var code: Int=Default.MAX_INT // A descriptive string for developper to identify the calling context public var caller: String=Default.NO_NAME public var message: String=Default.NO_MESSAGE public init(code: Int!, caller: String!) { self.code=code self.caller=caller } public init(context: String!) { self.caller=context } }
015453b9b19c9af728ad002d458fcfac
18.966667
74
0.66611
false
false
false
false
burnsra/SquidBar
refs/heads/master
SquidBar/LoginHelper.swift
mit
1
// // LoginHelper.swift // SquidBar // // Created by Robert Burns on 2/11/16. // Copyright © 2016 Robert Burns. All rights reserved. // import Foundation func applicationIsInStartUpItems() -> Bool { return itemReferencesInLoginItems().existingReference != nil } func setLaunchAtStartup(launchOnStartup: Bool) { let itemReferences = itemReferencesInLoginItems() let isNotAlreadySet = (itemReferences.existingReference == nil) let loginItemsRef = LSSharedFileListCreate(nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil).takeRetainedValue() as LSSharedFileListRef? if loginItemsRef != nil { if isNotAlreadySet && launchOnStartup { if let appUrl: CFURLRef = NSURL.fileURLWithPath(NSBundle.mainBundle().bundlePath) { LSSharedFileListInsertItemURL(loginItemsRef, itemReferences.lastReference, nil, nil, appUrl, nil, nil) } } else if !isNotAlreadySet && !launchOnStartup { if let itemRef = itemReferences.existingReference { LSSharedFileListItemRemove(loginItemsRef,itemRef); } } } } func itemReferencesInLoginItems() -> (existingReference: LSSharedFileListItemRef?, lastReference: LSSharedFileListItemRef?) { if let appUrl : NSURL = NSURL.fileURLWithPath(NSBundle.mainBundle().bundlePath) { let loginItemsRef = LSSharedFileListCreate(nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil).takeRetainedValue() as LSSharedFileListRef? if loginItemsRef != nil { let loginItems: NSArray = LSSharedFileListCopySnapshot(loginItemsRef, nil).takeRetainedValue() as NSArray if(loginItems.count > 0) { let lastItemRef: LSSharedFileListItemRef = loginItems.lastObject as! LSSharedFileListItemRef for var i = 0; i < loginItems.count; ++i { let currentItemRef: LSSharedFileListItemRef = loginItems.objectAtIndex(i) as! LSSharedFileListItemRef if let itemURL = LSSharedFileListItemCopyResolvedURL(currentItemRef, 0, nil) { if (itemURL.takeRetainedValue() as NSURL).isEqual(appUrl) { return (currentItemRef, lastItemRef) } } } return (nil, lastItemRef) } else { let addatstart: LSSharedFileListItemRef = kLSSharedFileListItemBeforeFirst.takeRetainedValue() return(nil,addatstart) } } } return (nil, nil) }
f30e639241aa788fe7a65ce8837a6114
42
160
0.65917
false
false
false
false
pristineio/androidtool-mac
refs/heads/master
AndroidTool/DeviceDiscoverer.swift
apache-2.0
3
// // DeviceDiscoverer.swift // AndroidTool // // Created by Morten Just Petersen on 4/22/15. // Copyright (c) 2015 Morten Just Petersen. All rights reserved. // import Cocoa protocol DeviceDiscovererDelegate { func devicesUpdated(deviceList:[Device]) } class DeviceDiscoverer:NSObject { var delegate : DeviceDiscovererDelegate! var previousDevices = [Device]() var updatingSuspended = false var mainTimer : NSTimer! var updateInterval:NSTimeInterval = 3 func getSerials(thenDoThis:(serials:[String]?, gotResults:Bool)->Void, finished:()->Void){ ShellTasker(scriptFile: "getSerials").run() { (output) -> Void in let str = String(output) if count(str.utf16) < 2 { thenDoThis(serials: nil, gotResults: false) finished() return } let serials = split(str) { $0 == ";" } thenDoThis(serials: serials, gotResults:true) finished() } } func getDetailsForSerial(serial:String, complete:(details:[String:String])->Void){ ShellTasker(scriptFile: "getDetailsForSerial").run(arguments: ["\(serial)"], isUserScript: false) { (output) -> Void in var detailsDict = self.getPropsFromString(output as String) complete(details:detailsDict) } } func pollDevices(){ var newDevices = [Device]() if updatingSuspended { return } print("+") getSerials({ (serials, gotResults) -> Void in if gotResults { for serial in serials! { self.getDetailsForSerial(serial, complete: { (details) -> Void in let device = Device(properties: details, adbIdentifier:serial) newDevices.append(device) if serials!.count == newDevices.count { self.delegate.devicesUpdated(newDevices) } }) } } else { self.delegate.devicesUpdated(newDevices) } }, finished: { () -> Void in // not really doing anything here afterall }) mainTimer = NSTimer.scheduledTimerWithTimeInterval(updateInterval, target: self, selector: "pollDevices", userInfo: nil, repeats: false) } func suspend(){ // some activites will break an open connection, an example is screen recording. updatingSuspended = true } func unSuspend(){ updatingSuspended = false } func start(){ NSNotificationCenter.defaultCenter().addObserver(self, selector: "suspend", name: "suspendAdb", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "unSuspend", name: "unSuspendAdb", object: nil) mainTimer = NSTimer.scheduledTimerWithTimeInterval(updateInterval, target: self, selector: "pollDevices", userInfo: nil, repeats: false) // NSRunLoop.currentRunLoop().addTimer(mainTimer, forMode: NSDefaultRunLoopMode) mainTimer.fire() } func stop(){} func getPropsFromString(string:String) -> [String:String] { let re = NSRegularExpression(pattern: "\\[(.+?)\\]: \\[(.+?)\\]", options: nil, error: nil)! let matches = re.matchesInString(string, options: nil, range: NSRange(location: 0, length: count(string.utf16))) var propDict = [String:String]() for match in matches as! [NSTextCheckingResult] { let key = (string as NSString).substringWithRange(match.rangeAtIndex(1)) let value = (string as NSString).substringWithRange(match.rangeAtIndex(2)) propDict[key] = value } return propDict } }
23dd139cf43e1e6334656e48dda7fa44
34.054545
144
0.588174
false
false
false
false
rplankenhorn/BrightFreddy
refs/heads/master
Pod/Classes/Service+Freddy.swift
mit
1
// // Service.swift // Pods // // Created by Robbie Plankenhorn on 3/10/16. // // import Foundation import BrightFutures import Freddy import Result extension Service { // MARK: Get JSON Object public class func getJSONObject(path: String, headers: [String : String] = [:], dotPath: String? = nil) -> Future<JSON, NSError> { return get(fullURLWithPath(path), headers: headers).flatMap { response -> Result<JSON, NSError> in do { let json = try response.bodyJSON() if let dotPath = dotPath, let jsonDotPathObject = json[dotPath] { return Result.Success(jsonDotPathObject) } else { return Result.Success(json) } } catch { return Result.Failure(NSError(domain: "", code: 0, userInfo: nil)) } } } // MARK: Get Object public class func getObject<T: JSONDecodable>(type: T.Type, path: String, headers: [String : String] = [:], dotPath: String? = nil) -> Future<T, NSError> { return getJSONObject(path, headers: headers, dotPath: dotPath).flatMap { json -> Result<T, NSError> in do { let object = try T(json: json) return Result.Success(object) } catch { return Result.Failure(NSError(domain: "", code: 0, userInfo: nil)) } } } // MARK: Get Objects public class func getObjects<T: JSONDecodable>(type: T.Type, path: String, headers: [String : String] = [:], dotPath: String? = nil) -> Future<[T], NSError> { return getJSONObject(path, headers: headers).flatMap { json -> Result<[T], NSError> in do { if case .Array(let jsonObjects) = json { var objects = [T]() for jsonObject in jsonObjects { objects.append(try T(json: jsonObject)) } return Result.Success(objects) } } catch { } return Result.Failure(NSError(domain: "", code: 0, userInfo: nil)) } } } extension Service { // MARK: Post JSON Object public class func postJSONObject(object: JSON, path: String, headers: [String : String] = [:]) -> Future<JSON, NSError> { do { let body = try object.serialize() return post(fullURLWithPath(path), body: body, headers: headers).flatMap { response -> Result<JSON, NSError> in do { let json = try response.bodyJSON() return Result.Success(json) } catch { return Result.Failure(NSError(domain: "", code: 0, userInfo: nil)) } } } catch { return Promise<JSON, NSError>().completeWith(NSError(domain: "", code: 0, userInfo: nil)).future } } // MARK: Post Object public class func postObject<T: JSONEncodable, D: JSONDecodable>(object: T, path: String, headers: [String : String] = [:]) -> Future<D, NSError> { return postJSONObject(object.toJSON(), path: path, headers: headers).flatMap { json -> Result<D, NSError> in do { let object = try D(json: json) return Result.Success(object) } catch { return Result.Failure(NSError(domain: "", code: 0, userInfo: nil)) } } } }
ccd9b50d7b35f40e3c1ae99ebd26c588
33.826923
162
0.516984
false
false
false
false
iamchiwon/HologramVideoPlayer
refs/heads/master
iOSPlayer/HologramPlayer/ViewControllers/VideoPlayerViewController.swift
mit
1
// // VideoPlayerViewController.swift // HologramPlayer // // Created by Ryan Song on 2017. 4. 16.. // Copyright © 2017년 makecube. All rights reserved. // import UIKit import Photos import AVKit import AVFoundation class VideoPlayerViewController: UIViewController { @IBOutlet weak var bottomControlBox: UIVisualEffectView! @IBOutlet weak var bottomBoxBottomConstrains: NSLayoutConstraint! @IBOutlet weak var player1: UIView! @IBOutlet weak var player2: UIView! @IBOutlet weak var player3: UIView! @IBOutlet weak var player4: UIView! var layer1: AVPlayerLayer! var layer2: AVPlayerLayer! var layer3: AVPlayerLayer! var layer4: AVPlayerLayer! var videoAsset: PHAsset! var videoPlayer: AVPlayer! = nil var standupVideo: Bool = true override func viewDidLoad() { super.viewDidLoad() flipVideo() let tapper = UITapGestureRecognizer(target: self, action: #selector(onTap)) self.view.addGestureRecognizer(tapper) bottomControlBox.isHidden = true } override var prefersStatusBarHidden: Bool { return true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.isNavigationBarHidden = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) prepareVideo() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) videoPlayer.pause() } func flipVideo() { if standupVideo { player1.transform = CGAffineTransform(scaleX: 1, y: -1) player2.transform = CGAffineTransform(rotationAngle: 0.5 * .pi) player3.transform = CGAffineTransform(scaleX: 1, y: -1).rotated(by: -0.5 * .pi) player4.transform = CGAffineTransform(scaleX: 1, y: 1) } else { player1.transform = CGAffineTransform(scaleX: -1, y: 1) player2.transform = CGAffineTransform(rotationAngle: -0.5 * .pi) player3.transform = CGAffineTransform(scaleX: 1, y: -1).rotated(by: 0.5 * .pi) player4.transform = CGAffineTransform(rotationAngle: 1.0 * .pi) } } func prepareVideo() { let options: PHVideoRequestOptions = PHVideoRequestOptions() PHImageManager.default().requestAVAsset(forVideo: videoAsset, options: options) { (asset, mix, info) in if let urlAsset = asset as? AVURLAsset { let localVideoUrl = urlAsset.url DispatchQueue.main.async { self.videoPlayer = AVPlayer(url: localVideoUrl) self.prepareVideoLayer() self.playVideo() } } } } func prepareVideoLayer() { self.layer1 = AVPlayerLayer(player: self.videoPlayer) self.layer2 = AVPlayerLayer(player: self.videoPlayer) self.layer3 = AVPlayerLayer(player: self.videoPlayer) self.layer4 = AVPlayerLayer(player: self.videoPlayer) self.layer1.frame = self.player1.bounds self.layer2.frame = self.player2.bounds self.layer3.frame = self.player3.bounds self.layer4.frame = self.player4.bounds self.player1.layer.addSublayer(self.layer1) self.player2.layer.addSublayer(self.layer2) self.player3.layer.addSublayer(self.layer3) self.player4.layer.addSublayer(self.layer4) } func playVideo() { self.videoPlayer.play() NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.videoPlayer.currentItem, queue: nil, using: { (_) in DispatchQueue.main.async { self.videoPlayer?.seek(to: kCMTimeZero) self.videoPlayer?.play() } }) } func onTap() { bottomControlBox.isHidden = !bottomControlBox.isHidden } @IBAction func onClose(_ sender: Any) { navigationController?.popViewController(animated: true) } @IBAction func onFlip(_ sender: Any) { standupVideo = !standupVideo flipVideo() } @IBAction func onPause(_ sender: UIButton) { if sender.title(for: .normal) == "Pause" { videoPlayer.pause() sender.setTitle("Play", for: .normal) } else { videoPlayer.play() sender.setTitle("Pause", for: .normal) } } @IBAction func onMute(_ sender: Any) { videoPlayer.isMuted = !videoPlayer.isMuted } }
9568ee5e2441cce18898ea91aff3c27d
27.675862
148
0.695527
false
false
false
false
IngmarStein/swift
refs/heads/master
validation-test/compiler_crashers_fixed/01297-swift-type-walk.swift
apache-2.0
11
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse func ^(r: l, k) -> k { ? { h (s : t?) q u { g let d = s { } } e} let u : [Int?] = [n{ c v: j t.v == m>(n: o<t>) { } } class a<f : g, g : g where f.f == g> { } protocol g { typealias f } struct c<h : g> : g { typealias e = a<c<h>, f> func r<t>() { f f { } } struct i<o : u> { } func r<o>() -> [i<o>] { } class g<t : g> { } class g: g { } class n : h { } func i() -> l func o() -> m { } class d<c>: NSObject { } func c<b:c
f8199037fe9cc819d212a788491b9c00
17.088889
78
0.58231
false
false
false
false
relayr/apple-iot-smartphone
refs/heads/master
IoT/ios/sources/GraphView.swift
mit
1
import UIKit import Metal import simd import Utilities import ReactiveCocoa class GraphView : UIView { // MARK: Definitions /// Stores the state of the uniforms of the graph view. private class Uniforms { /// Uniform related to the whole graph view. struct ViewUniform { /// The size of the view. var size : float2 /// The size of the left text column. var leftColumnSize : float2 /// The size of the actual graph (mesh). var meshSize : float2 /// The size of the right text column. var rightColumnSize : float2 /// The time (in seconds) that the graph will show. var timeWindow : Float /// The current time ("now") express on the graph. var time : Float init(currentTime time: Float, timeWindow: Float = 5, size: CGSize = CGSize(width: 100, height: 100), graphWidthMultipler mult: Float = 0.8, lineWidth: Float = 1) { (self.time, self.timeWindow) = (time, timeWindow) self.size = float2(Float(size.width), Float(size.height)) self.meshSize = float2(mult*self.size.x, self.size.y - lineWidth) self.leftColumnSize = float2(0.5*(self.size.x-self.meshSize.x), self.meshSize.y) self.rightColumnSize = self.leftColumnSize } } /// Uniform referencing axis data. struct AxisUniform { /// The number of horizontal and vertical lines (in that order). var numLines : float2 /// The line width on view coordinates. var lineWidth : Float } /// Uniform referencing samples data. struct SamplesUniform { /// The limits being displayed on the y axis of the graph [min, max]. var boundaries : float2 /// The radius of the triangle on view coordinates (not normalized): outter, inner var dotRadius : float2 /// The union-line width. var lineWidth : Float /// The number of triangles that the dot is made of. var trianglesPerDot : UInt16 /// The number of float values per sample (not including the timestamp) var valuesPerSample : UInt16 } /// Controls whether a frame should be rendered. let renderSemaphore : dispatch_semaphore_t /// The amount of concurrent renders (and thus the amount of uniform instances) that this view has. let concurrentRenders : Int /// The current index for uniforms (depends on the concurrent renders number). var currentIndex : Int /// The uniform data related to the whole graph view. var view : ViewUniform /// The uniform data related to the axis of the graph. var axis : AxisUniform /// The uniform data related to how samples are displayed. var samples : SamplesUniform /// Creates the uniform information data holder. /// - parameter currentTime: The value for time now! (in seconds) /// - parameter numAxisLInes: The number of axis lines that the graph should display. /// - parameter numRenders: The number of concurrent renders that can be calculated on the GPU. /// - parameter valueLimits: The limits that the *Y* axis will be bound to. init(withCurrentTime currentTime: Float, numAxisLines: (horizontal: Float, vertical: Float), concurrentRenders numRenders : Int = 3, valueLimits: (min: Float, max: Float) = (-1, 1)) { renderSemaphore = dispatch_semaphore_create(numRenders) concurrentRenders = numRenders currentIndex = -1 view = ViewUniform(currentTime: currentTime) axis = AxisUniform(numLines: float2(numAxisLines.horizontal, numAxisLines.vertical), lineWidth: 1) samples = SamplesUniform(boundaries: float2(valueLimits.min, valueLimits.max), dotRadius: [1, 0.9], lineWidth: 1, trianglesPerDot: 20, valuesPerSample: 1) } /// Updates the values stored by this instance and returns boolean flags specifying whether the values had changed (and thus the rendering system should update its values too). func update(withSize viewSize: CGSize, scaleFactor: Float) { let time = GraphRenderData.timeNow let needsResize = Float(viewSize.width) != view.size.x || Float(viewSize.height) != view.size.y if needsResize { let lineWidth : Float = 1 axis.lineWidth = lineWidth * scaleFactor view = ViewUniform(currentTime: time, timeWindow: 5, size: viewSize, graphWidthMultipler: 0.8, lineWidth: axis.lineWidth) let outterRadius = 6 * lineWidth * scaleFactor samples.dotRadius = [outterRadius, 0.9*outterRadius] samples.lineWidth = axis.lineWidth } else { view.time = time } currentIndex = (currentIndex+1) % concurrentRenders } } override static func layerClass() -> AnyClass { return CAMetalLayer.self } // MARK: Properties /// CPU Uniforms storing the information used by the shaders. private var uniforms = Uniforms(withCurrentTime: GraphRenderData.timeNow, numAxisLines: (11, 10)) /// GPU Uniforms storing the information used by the shaders. private var buffers : (view : MTLBuffer, axis : MTLBuffer, samples : MTLBuffer, colors : MTLBuffer)! /// Textures containing the labels for the vertical axis (they will contain the number of horizontal lines minus 2). private var textures : [MTLTexture?]? /// If it exists, there is a block trying to generate all the texture labels private var textureGenerator : dispatch_block_t? /// ReactiveCocoa disposable to stop the *display refresher*. private var refreshDisposable : Disposable? /// The associated data needed for rendering. private var data : (sampler: SystemSampler, meaning: GraphMeaning, state: GraphRenderState)? /// Convenience access to the `CAMetalLayer`. private var metalLayer : CAMetalLayer { return layer as! CAMetalLayer } /// The time window (in seconds) that the graph shows. var timeWindow : Int { get { return Int(uniforms.view.timeWindow) } set { guard newValue > 0 else { return } uniforms.view.timeWindow = Float(timeWindow) } } /// Sets the render variables needed for displaying this graph view. /// - parameter renderState: Render state shared with other graph views. /// - parameter samplerType: The type of data being displayed. /// - parameter graphMeaning: The buffers containing the data to be displayed. func renderData(withState renderState: GraphRenderState, samplerType: SystemSampler, graphMeaning: GraphMeaning) { // Check whether the shared render state has changed and new buffers needs to be generated. if data == nil || data!.state != renderState { refreshDisposable?.dispose() (metalLayer.device, metalLayer.pixelFormat) = (renderState.device, .BGRA8Unorm) let concurrentRenders = uniforms.concurrentRenders let viewBuf = renderState.device.newBufferWithLength(concurrentRenders*strideofValue(uniforms.view), options: .CPUCacheModeWriteCombined) viewBuf.label = "Graph: View Uniforms" let axisBuf = renderState.device.newBufferWithLength(concurrentRenders*strideofValue(uniforms.axis), options: .CPUCacheModeWriteCombined) axisBuf.label = "Graph: Axis Uniforms" let samplesBuf = renderState.device.newBufferWithLength(concurrentRenders*strideofValue(uniforms.samples), options: .CPUCacheModeWriteCombined) samplesBuf.label = "Graph: Sample Uniforms" let colors = [Colors.Grid.float4, Colors.Green.float4, Colors.Blue.float4, Colors.Red.float4] let colorsBuf = renderState.device.newBufferWithBytes(colors, length: sizeof(float4)*colors.count, options: .CPUCacheModeWriteCombined) colorsBuf.label = "Graph: Colors Uniforms" buffers = (viewBuf, axisBuf, samplesBuf, colorsBuf) uniforms.samples.trianglesPerDot = renderState.numTrianglesPerDot if let _ = window { refreshDisposable = renderState.displayRefresh.signal.observeNext { [weak self] in self?.render($0) } } else { refreshDisposable = nil } } // Check whether meaning has changed and new texture data need to be generated. if data == nil || data!.meaning != graphMeaning { if let generator = textureGenerator { dispatch_block_cancel(generator) } textures = nil let limits = graphMeaning.limits uniforms.samples.boundaries = float2(limits.min, limits.max) uniforms.samples.valuesPerSample = UInt16(graphMeaning.valuesPerSample) } data = (samplerType, graphMeaning, renderState) } override func didMoveToWindow() { super.didMoveToWindow() guard let window = self.window else { refreshDisposable?.dispose(); if let generator = textureGenerator { dispatch_block_cancel(generator) } return refreshDisposable = nil } metalLayer.contentsScale = window.screen.nativeScale guard let renderData = data else { return } if refreshDisposable == nil { refreshDisposable = renderData.state.displayRefresh.signal.observeNext { [weak self] in self?.render($0) } } } /// It renders a screen *full* of content. /// - warning: This method should always be called from the main thread. /// - parameter refreshData: Variables referencing the time of refresh triggering. func render(refreshData: DisplayRefresh.Value) { let unis = uniforms // Check first if I can get hold of the semaphore; If not, just skip the frame. guard let renderData = self.data where dispatch_semaphore_wait(unis.renderSemaphore, DISPATCH_TIME_NOW) == 0 else { return } // If there are no shared render state or there is no access to a drawable, return without doing any work. guard let drawable = metalLayer.nextDrawable() else { dispatch_semaphore_signal(unis.renderSemaphore); return } let drawableSize = metalLayer.drawableSize let scaleFactor = metalLayer.contentsScale let meaning = renderData.meaning let visibleSamples = meaning.numSamplesSince(unis.view.time - unis.view.timeWindow) ?? 0 let valuesPerSample = Int(unis.samples.valuesPerSample) unis.update(withSize: drawableSize, scaleFactor: Float(scaleFactor)) let unibuffers = self.buffers let size : (view: Int, axis: Int, samples: Int) = (strideofValue(unis.view), strideofValue(unis.axis), strideofValue(unis.samples)) let offset : (view: Int, axis: Int, samples: Int) = (size.view*unis.currentIndex, size.axis * unis.currentIndex, size.samples * unis.currentIndex) memcpy(unibuffers.view.contents() + offset.view, &unis.view, size.view) memcpy(unibuffers.axis.contents() + offset.axis, &unis.axis, size.axis) memcpy(unibuffers.samples.contents() + offset.samples, &unis.samples, size.samples) let renderState = renderData.state dispatch_async(renderState.renderQueue) { [weak self] in let cmdBuffer = renderState.cmdQueue.commandBuffer() let parallelEncoder = cmdBuffer.parallelRenderCommandEncoderWithDescriptor(MTLRenderPassDescriptor().then { $0.colorAttachments[0].texture = drawable.texture $0.colorAttachments[0].clearColor = Colors.Background.metal $0.colorAttachments[0].loadAction = .Clear $0.colorAttachments[0].storeAction = .Store }) defer { parallelEncoder.endEncoding() cmdBuffer.presentDrawable(drawable) cmdBuffer.addCompletedHandler { _ in dispatch_semaphore_signal(unis.renderSemaphore) } cmdBuffer.commit() } let horizontalAxisEncoder = parallelEncoder.renderCommandEncoder() horizontalAxisEncoder.setFrontFacingWinding(.CounterClockwise) horizontalAxisEncoder.setCullMode(.Back) horizontalAxisEncoder.setRenderPipelineState(renderState.stateAxisHorizontal) horizontalAxisEncoder.setVertexBuffer(unibuffers.view, offset: offset.view, atIndex: 0) horizontalAxisEncoder.setVertexBuffer(unibuffers.axis, offset: offset.axis, atIndex: 1) horizontalAxisEncoder.setFragmentBuffer(unibuffers.colors, offset: 0, atIndex: 0) horizontalAxisEncoder.drawPrimitives(.TriangleStrip, vertexStart: 0, vertexCount: 4, instanceCount: Int(unis.axis.numLines.x)) horizontalAxisEncoder.endEncoding() let verticalAxisEncoder = parallelEncoder.renderCommandEncoder() verticalAxisEncoder.setFrontFacingWinding(.Clockwise) verticalAxisEncoder.setCullMode(.Back) verticalAxisEncoder.setRenderPipelineState(renderState.stateAxisVertical) verticalAxisEncoder.setVertexBuffer(unibuffers.view, offset: offset.view, atIndex: 0) verticalAxisEncoder.setVertexBuffer(unibuffers.axis, offset: offset.axis, atIndex: 1) verticalAxisEncoder.setFragmentBuffer(unibuffers.colors, offset: 0, atIndex: 0) verticalAxisEncoder.drawPrimitives(.TriangleStrip, vertexStart: 0, vertexCount: 4, instanceCount: Int(unis.axis.numLines.y)) verticalAxisEncoder.endEncoding() guard valuesPerSample > 0 && visibleSamples > 0 else { return } let firstIndex = meaning.numSamples-visibleSamples let sampleEncoder = parallelEncoder.renderCommandEncoder() sampleEncoder.setFrontFacingWinding(.Clockwise) sampleEncoder.setCullMode(.Back) sampleEncoder.setRenderPipelineState(renderState.stateSamples) sampleEncoder.setVertexBuffer(unibuffers.view, offset: offset.view, atIndex: 0) sampleEncoder.setVertexBuffer(unibuffers.samples, offset: offset.samples, atIndex: 1) sampleEncoder.setVertexBuffer(meaning.buffer, offset: firstIndex*meaning.sampleSize, atIndex: 2) sampleEncoder.setVertexBuffer(renderState.verticesDotBuffer, offset: 0, atIndex: 3) sampleEncoder.setFragmentBuffer(unibuffers.colors, offset: sizeof(float4), atIndex: 0) sampleEncoder.drawIndexedPrimitives(.Triangle, indexCount: renderState.indicesDotBuffer.length/sizeof(UInt16), indexType: .UInt16, indexBuffer: renderState.indicesDotBuffer, indexBufferOffset: 0, instanceCount: visibleSamples*valuesPerSample) sampleEncoder.endEncoding() let visibleLines = visibleSamples - 1 guard visibleLines > 0 else { return } let lineEncoder = parallelEncoder.renderCommandEncoder() lineEncoder.setRenderPipelineState(renderState.stateUnionLines) lineEncoder.setVertexBuffer(unibuffers.view, offset: offset.view, atIndex: 0) lineEncoder.setVertexBuffer(unibuffers.samples, offset: offset.samples, atIndex: 1) lineEncoder.setVertexBuffer(meaning.buffer, offset: firstIndex*meaning.sampleSize, atIndex: 2) lineEncoder.setFragmentBuffer(unibuffers.colors, offset: sizeof(float4), atIndex: 0) lineEncoder.drawPrimitives(.TriangleStrip, vertexStart: 0, vertexCount: 4, instanceCount: visibleLines*valuesPerSample) lineEncoder.endEncoding() guard let textures = self?.textures else { guard let graph = self where graph.textureGenerator == nil else { return } graph.textureGenerator = GraphLabels.texturesBlock(withDevice: renderData.state.device, columnSize: unis.view.leftColumnSize, numLines: Int(unis.axis.numLines.x), boundaries: unis.samples.boundaries) { [weak graph] (textures) in graph?.textureGenerator = nil graph?.textures = textures } return dispatch_async(renderData.state.textureQueue, graph.textureGenerator!) } let labelsEncoder = parallelEncoder.renderCommandEncoder() labelsEncoder.setFrontFacingWinding(.Clockwise) labelsEncoder.setCullMode(.Back) labelsEncoder.setRenderPipelineState(renderState.stateLabels) labelsEncoder.setVertexBuffer(unibuffers.view, offset: offset.view, atIndex: 0) labelsEncoder.setVertexBuffer(unibuffers.axis, offset: offset.axis, atIndex: 1) for case let (index, texture as MTLTexture) in textures.enumerate() { labelsEncoder.setVertexTexture(texture, atIndex: 0) labelsEncoder.setFragmentTexture(texture, atIndex: 0) labelsEncoder.drawPrimitives(.TriangleStrip, vertexStart: 0, vertexCount: 4, instanceCount: 1, baseInstance: index) } labelsEncoder.endEncoding() } } }
3df1a26eea9764355f544234f397ce64
54.205607
254
0.651035
false
false
false
false
yotao/YunkuSwiftSDKTEST
refs/heads/master
YunkuSwiftSDK/YunkuSwiftSDK/Class/EntFileManager.swift
mit
1
// // Created by Brandon on 15/6/1. // Copyright (c) 2015 goukuai. All rights reserved. // import Foundation open class EntFileManager: SignAbility { let uploadLimitSize = 52428800 let urlApiFilelist = HostConfig.libHost + "/1/file/ls" let urlApiUpdateList = HostConfig.libHost + "/1/file/updates" let urlApiFileInfo = HostConfig.libHost + "/1/file/info" let urlApiCreateFolder = HostConfig.libHost + "/1/file/create_folder" let urlApiCreateFile = HostConfig.libHost + "/1/file/create_file" let urlApiDelFile = HostConfig.libHost + "/1/file/del" let urlApiMoveFile = HostConfig.libHost + "/1/file/move" let urlApiLinkFile = HostConfig.libHost + "/1/file/link" let urlApiSendmsg = HostConfig.libHost + "/1/file/sendmsg" let urlApiGetLink = HostConfig.libHost + "/1/file/links" let urlApiUpdateCount = HostConfig.libHost + "/1/file/updates_count" let urlApiGetServerSite = HostConfig.libHost + "/1/file/servers" let urlApiCreateFileByUrl = HostConfig.libHost + "/1/file/create_file_by_url" let urlApiUploadSevers = HostConfig.libHost + "/1/file/upload_servers" var _orgClientId = "" let queue = DispatchQueue(label: "YunkuSwiftSDKQueue", attributes: []) public init(orgClientId: String, orgClientSecret: String) { super.init() _orgClientId = orgClientId _clientSecret = orgClientSecret } //MARK:获取文件列表 open func getFileList(_ start: Int, fullPath: String) -> Dictionary<String, AnyObject> { let method = "GET" let url = urlApiFilelist var params = Dictionary<String, String?>() params["org_client_id"] = _orgClientId params["dateline"] = String(Utils.getUnixDateline()) params["start"] = String(start) params["fullpath"] = fullPath params["sign"] = generateSign(params) return NetConnection.sendRequest(url, method: method, params: params, headParams: nil) } //MARK:获取更新列表 open func getUpdateList(_ isCompare: Bool, fetchDateline: Int) -> Dictionary<String, AnyObject> { let method = "GET" let url = urlApiUpdateCount var params = Dictionary<String, String?>() params["org_client_id"] = _orgClientId params["dateline"] = String(Utils.getUnixDateline()) if isCompare { params["mode"] = "compare" } params["fetch_dateline"] = String(fetchDateline) params["sign"] = generateSign(params) return NetConnection.sendRequest(url, method: method, params: params, headParams: nil) } //MARK:获取文件信息 open func getFileInfo(_ fullPath: String, type: NetType) -> Dictionary<String, AnyObject> { let method = "GET" let url = urlApiFileInfo var params = Dictionary<String, String?>() params["org_client_id"] = _orgClientId params["dateline"] = String(Utils.getUnixDateline()) params["fullpath"] = fullPath switch (type) { case .default: () case .in: params["net"] = type.description } params["sign"] = generateSign(params) return NetConnection.sendRequest(url, method: method, params: params, headParams: nil) } //MARK:创建文件夹 open func createFolder(_ fullPath: String, opName: String) -> Dictionary<String, AnyObject> { let method = "POST" let url = urlApiCreateFolder var params = Dictionary<String, String?>() params["org_client_id"] = _orgClientId params["dateline"] = String(Utils.getUnixDateline()) params["fullpath"] = fullPath params["op_name"] = opName params["sign"] = generateSign(params) return NetConnection.sendRequest(url, method: method, params: params, headParams: nil) } //MARK:文件分块上传 open func uploadByBlock(_ localPath: String, fullPath: String, opName: String, opId: Int, overwrite: Bool, delegate: UploadCallBack) -> UploadManager { let uploadManager = UploadManager(apiUrl: self.urlApiCreateFile, localPath: localPath, fullPath: fullPath, opName: opName, opId: opId, orgClientId: self._orgClientId, dateline: Utils.getUnixDateline(), clientSecret: self._clientSecret, overWirte: overwrite) uploadManager.delegate = delegate self.queue.async(execute: { () -> Void in uploadManager.doUpload() }) return uploadManager } //MARK:将文件数据上传至 open func createFile(_ fullPath: String, opName: String, data: Data) -> Dictionary<String, AnyObject> { if data.count > uploadLimitSize { LogPrint.error("The file more than 50 MB is not be allowed") return Dictionary<String, AnyObject>() } var parameters = Dictionary<String, String?>(); parameters["org_client_id"] = _orgClientId parameters["dateline"] = String(Utils.getUnixDateline()) parameters["fullpath"] = fullPath parameters["op_name"] = opName parameters["filefield"] = "file" let uniqueId = ProcessInfo.processInfo.globallyUniqueString let postBody: NSMutableData = NSMutableData() var postData: String = String() let boundary: String = "------WebKitFormBoundary\(uniqueId)" let filename = (fullPath as NSString).lastPathComponent //添加参数 postData += "--\(boundary)\r\n" for (key, value) in parameters { postData += "--\(boundary)\r\n" postData += "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n" postData += "\(value!)\r\n" } //添加签名 postData += "--\(boundary)\r\n" postData += "Content-Disposition: form-data; name=\"sign\"\r\n\r\n" postData += "\(generateSign(parameters))\r\n" //添加文件数据 postData += "--\(boundary)\r\n" postData += "Content-Disposition: form-data; name=\"file\"; filename=\"\(filename).jpg\"\r\n" postData += "Content-Type: image/png\r\n\r\n" postBody.append(postData.data(using: String.Encoding.utf8)!) postBody.append(data) postData = String() postData += "\r\n" postData += "\r\n--\(boundary)--\r\n" postBody.append(postData.data(using: String.Encoding.utf8)!) let url = URL(string: urlApiCreateFile) let request: NSMutableURLRequest = NSMutableURLRequest(url: url!, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 10) let content: String = "multipart/form-data; boundary=\(boundary)" request.setValue(content, forHTTPHeaderField: "Content-Type") request.setValue("\(postBody.length)", forHTTPHeaderField: "Content-Length") request.httpBody = postBody as Data request.httpMethod = "POST" return NetConnection.sendRequest(request) } //MARK: 删除文件 open func del(_ fullPaths: String, opName: String) -> Dictionary<String, AnyObject> { let method = "POST" let url = urlApiDelFile var params = Dictionary<String, String?>() params["org_client_id"] = _orgClientId params["dateline"] = String(Utils.getUnixDateline()) params["fullpaths"] = fullPaths params["op_name"] = opName params["sign"] = generateSign(params) return NetConnection.sendRequest(url, method: method, params: params, headParams: nil) } //MARK:移动文件 open func move(_ fullPath: String, destFullPath: String, opName: String) -> Dictionary<String, AnyObject> { let method = "POST" let url = urlApiMoveFile var params = Dictionary<String, String?>() params["org_client_id"] = _orgClientId params["dateline"] = String(Utils.getUnixDateline()) params["fullpath"] = fullPath params["dest_fullpath"] = destFullPath params["op_name"] = opName params["sign"] = generateSign(params) return NetConnection.sendRequest(url, method: method, params: params, headParams: nil) } //MARK:获取文件链接 open func link(_ fullPath: String, deadline: Int, authType: AuthType, password: String?) -> Dictionary<String, AnyObject> { let method = "POST" let url = urlApiLinkFile var params = Dictionary<String, String?>() params["org_client_id"] = _orgClientId params["dateline"] = String(Utils.getUnixDateline()) params["fullpath"] = fullPath if deadline != 0 { params["deadline"] = String(deadline) } if authType != AuthType.default { params["auth"] = authType.description } params["password"] = password params["sign"] = generateSign(params) return NetConnection.sendRequest(url, method: method, params: params, headParams: nil) } //MARK:发送消息 open func sendmsg(_ title: String, text: String, image: String?, linkUrl: String?, opName: String) -> Dictionary<String, AnyObject> { let method = "POST" let url = urlApiSendmsg var params = Dictionary<String, String?>() params["org_client_id"] = _orgClientId params["dateline"] = String(Utils.getUnixDateline()) params["title"] = title params["text"] = text params["image"] = image params["url"] = linkUrl params["op_name"] = opName params["sign"] = generateSign(params) return NetConnection.sendRequest(url, method: method, params: params, headParams: nil) } //MARK:获取当前库所有外链 open func links(_ fileOnly: Bool) -> Dictionary<String, AnyObject> { let method = "GET" let url = urlApiGetLink var params = Dictionary<String, String?>() params["org_client_id"] = _orgClientId params["dateline"] = String(Utils.getUnixDateline()) if fileOnly { params["file"] = "1" } params["sign"] = generateSign(params) return NetConnection.sendRequest(url, method: method, params: params, headParams: nil) } //MARK:文件更新数量 open func getUpdateCounts(_ beginDateline: Int, endDateline: Int, showDelete: Bool) -> Dictionary<String, AnyObject> { let method = "GET" let url = urlApiUpdateCount var params = Dictionary<String, String?>() params["org_client_id"] = _orgClientId params["dateline"] = String(Utils.getUnixDateline()) params["begin_dateline"] = String(beginDateline) params["end_dateline"] = String(endDateline) params["showdel"] = String(showDelete ? 1 : 0) params["sign"] = generateSign(params) return NetConnection.sendRequest(url, method: method, params: params, headParams: nil) } //MARK:通过链接上传文件 open func createFileByUrl(_ fullPath: String, opId: Int, opName: String!, overwrite: Bool, fileUrl: String) -> Dictionary<String, AnyObject> { let method = "POST" let url = urlApiCreateFileByUrl var params = Dictionary<String, String?>() params["org_client_id"] = _orgClientId params["fullpath"] = fullPath params["dateline"] = String(Utils.getUnixDateline()) if opId > 0 { params["op_id"] = String(opId) } else { params["op_name"] = opName } params["overwrite"] = String(overwrite ? 1 : 0) params["url"] = fileUrl params["sign"] = generateSign(params) return NetConnection.sendRequest(url, method: method, params: params, headParams: nil) } //MARK:获取上传地址 open func getUploadServers() -> Dictionary<String, AnyObject> { let method = "GET" let url = urlApiUploadSevers var params = Dictionary<String, String?>() params["org_client_id"] = _orgClientId params["dateline"] = String(Utils.getUnixDateline()) params["sign"] = generateSign(params) return NetConnection.sendRequest(url, method: method, params: params, headParams: nil) } open func getServerSite(_ type: String) -> Dictionary<String, AnyObject> { let method = "POST" let url = urlApiUpdateCount var params = Dictionary<String, String?>() params["org_client_id"] = _orgClientId params["type"] = type params["dateline"] = String(Utils.getUnixDateline()) params["sign"] = generateSign(params) return NetConnection.sendRequest(url, method: method, params: params, headParams: nil) } //MARK:复制一个EntFileManager open func clone() -> EntFileManager { return EntFileManager(orgClientId: _orgClientId, orgClientSecret: _clientSecret) } }
77c34c38cd1a1f49e7756472cca096b9
39.421222
265
0.63026
false
false
false
false
JosephNK/SwiftyIamport
refs/heads/master
SwiftyIamportDemo/Controller/WKNiceViewController.swift
mit
1
// // WKNiceViewController.swift // SwiftyIamportDemo // // Created by JosephNK on 23/11/2018. // Copyright © 2018 JosephNK. All rights reserved. // import UIKit import SwiftyIamport import WebKit class WKNiceViewController: UIViewController { lazy var wkWebView: WKWebView = { var view = WKWebView() view.backgroundColor = UIColor.clear view.navigationDelegate = self //view.uiDelegate = self return view }() override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(wkWebView) self.wkWebView.frame = self.view.bounds // 결제 환경 설정 IAMPortPay.sharedInstance.configure(scheme: "iamporttest", // info.plist에 설정한 scheme storeIdentifier: "imp84043725") // iamport 에서 부여받은 가맹점 식별코드 IAMPortPay.sharedInstance .setPGType(.nice) // PG사 타입 .setIdName(nil) // 상점아이디 ({PG사명}.{상점아이디}으로 생성시 사용) .setPayMethod(.card) // 결제 형식 .setWKWebView(self.wkWebView) // 현재 Controller에 있는 WebView 지정 .setRedirectUrl(nil) // m_redirect_url 주소 // 결제 정보 데이타 let parameters: IAMPortParameters = [ "merchant_uid": String(format: "merchant_%@", String(Int(NSDate().timeIntervalSince1970 * 1000))), "name": "결제테스트", "amount": "1004", "buyer_email": "[email protected]", "buyer_name": "구매자", "buyer_tel": "010-1234-5678", "buyer_addr": "서울특별시 강남구 삼성동", "buyer_postcode": "123-456", "custom_data": ["A1": 123, "B1": "Hello"] //"custom_data": "24" ] IAMPortPay.sharedInstance.setParameters(parameters).commit() // ISP 취소시 이벤트 (NicePay만 가능) IAMPortPay.sharedInstance.setCancelListenerForNicePay { [weak self] in DispatchQueue.main.async { let alert = UIAlertController(title: nil, message: "ISP 결제 취소", preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)) self?.present(alert, animated: true, completion: nil) } } // 결제 웹페이지(Local) 파일 호출 if let url = IAMPortPay.sharedInstance.urlFromLocalHtmlFile() { let request = URLRequest(url: url) self.wkWebView.load(request) } } } extension WKNiceViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { let request = navigationAction.request IAMPortPay.sharedInstance.requestRedirectUrl(for: request, parser: { (data, response, error) -> Any? in // Background Thread 처리 var resultData: [String: Any]? if let httpResponse = response as? HTTPURLResponse { let statusCode = httpResponse.statusCode switch statusCode { case 200: resultData = [ "isSuccess": "OK" ] break default: break } } return resultData }) { (pasingData) in // Main Thread 처리 } let result = IAMPortPay.sharedInstance.requestAction(for: request) decisionHandler(result ? .allow : .cancel) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { // 결제 환경으로 설정에 의한 웹페이지(Local) 호출 결과 IAMPortPay.sharedInstance.requestIAMPortPayWKWebViewDidFinishLoad(webView) { (error) in if error != nil { switch error! { case .custom(let reason): print("error: \(reason)") break } }else { print("OK") } } } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { print("didFail") } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { print("didFailProvisionalNavigation \(error.localizedDescription)") } } //extension WKNiceViewController: WKUIDelegate { // func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { // guard let url = navigationAction.request.url else { // return nil // } // guard let targetFrame = navigationAction.targetFrame, targetFrame.isMainFrame else { // webView.load(NSURLRequest.init(url: url) as URLRequest) // return nil // } // return nil // } //}
599c57844f58253c3b7450aae3704571
35.604317
189
0.567414
false
false
false
false
watson-developer-cloud/ios-sdk
refs/heads/master
Sources/AssistantV1/Models/DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe.swift
apache-2.0
1
/** * (C) Copyright IBM Corp. 2022. * * 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 /** DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe. Enums with an associated value of DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe: DialogNodeOutputGeneric */ public struct DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe: Codable, Equatable { /** The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. */ public var responseType: String /** The `https:` URL of the embeddable content. */ public var source: String /** An optional title to show before the response. */ public var title: String? /** An optional description to show with the response. */ public var description: String? /** The URL of an image that shows a preview of the embedded content. */ public var imageURL: String? /** An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. */ public var channels: [ResponseGenericChannel]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case responseType = "response_type" case source = "source" case title = "title" case description = "description" case imageURL = "image_url" case channels = "channels" } /** Initialize a `DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe` with member variables. - parameter responseType: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - parameter source: The `https:` URL of the embeddable content. - parameter title: An optional title to show before the response. - parameter description: An optional description to show with the response. - parameter imageURL: The URL of an image that shows a preview of the embedded content. - parameter channels: An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - returns: An initialized `DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe`. */ public init( responseType: String, source: String, title: String? = nil, description: String? = nil, imageURL: String? = nil, channels: [ResponseGenericChannel]? = nil ) { self.responseType = responseType self.source = source self.title = title self.description = description self.imageURL = imageURL self.channels = channels } }
f742cd4bb13b54be3284fd61633c16e9
34.138614
120
0.69428
false
false
false
false
derpue/pecunia-client
refs/heads/master
Source/NSString+PecuniaAdditions.swift
gpl-2.0
1
/** * Copyright (c) 2014, 2015, Pecunia Project. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; version 2 of the * License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ import Foundation extension NSString { /** * Processes the content of the receiver and creates a new string with a more natural appearance, if possible. * This mostly involves truecasing words. * This process depends on a large word library, so it's an optional feature. If the user decided * to disable it we do a simple capitalization. */ public func stringWithNaturalText() -> NSString { if !WordMapping.wordMappingsAvailable { // While our word list is being loaded return a simple capitalized string. return self.capitalizedStringWithLocale(NSLocale.currentLocale()); } let context = MOAssistant.sharedAssistant().context; let request = NSFetchRequest(); request.entity = NSEntityDescription.entityForName("WordMapping", inManagedObjectContext: context); let result = NSMutableString(); let range = NSMakeRange(0, self.length); self.enumerateLinguisticTagsInRange(range, scheme: NSLinguisticTagSchemeLexicalClass, options: NSLinguisticTaggerOptions(rawValue: 0), orthography: nil, usingBlock: { (tag: String, tokenRange: NSRange, sentenceRange: NSRange, stop: UnsafeMutablePointer<ObjCBool>) -> () in let item : NSString = self.substringWithRange(tokenRange); if tag == NSLinguisticTagOtherWhitespace { // Copy over any whitespace. if result.length > 0 { result.appendString(item as String); } } else { // Not a whitespace. See if that is a known word. // TODO: needs localization. let key = item.stringWithNormalizedGermanChars().lowercaseString; let predicate = NSPredicate(format: "wordKey = '\(key)'"); request.predicate = predicate; do { let mappings = try context.executeFetchRequest(request); if (mappings.count > 0) { let mapping = mappings[0] as! WordMapping; let word: NSString = mapping.translated; // If the original word contains lower case characters then it was probably // already in true case. We only use the lookup then for replacing diacritics/sharp-s. if item.rangeOfCharacterFromSet(NSCharacterSet.lowercaseLetterCharacterSet()).length > 0 { result.appendString(item.substringToIndex(1)); result.appendString(word.substringFromIndex(1)); } else { // Make the first letter upper case if it is the first entry. // Don't touch the other letters, though! if result.length == 0 { let firstLetter: NSString = word.substringToIndex(1); result.appendString(firstLetter.capitalizedString); result.appendString(word.substringFromIndex(1)); } else { result.appendString(word as String); } } } else { result.appendString(item as String); } } catch { // Do nothing in case of an error. Should never happen, but just in case. } } } ); return result; } /** * Converts umlauts and ß in the receiver to a decomposed form. */ public func stringWithNormalizedGermanChars() -> NSString { var result = self.decomposedStringWithCanonicalMapping; result = result.stringByReplacingOccurrencesOfString("ß", withString: "ss"); return result.stringByReplacingOccurrencesOfString("\u{0308}", withString: "e"); // Combining diaresis. } }
cbf844e4d4989eab2daef6eaf582bc83
48.787879
119
0.574559
false
false
false
false
zhanggaoqiang/SwiftLearn
refs/heads/master
Swift语法/Swift类/Swift类/main.swift
mit
1
// // main.swift // Swift类 // // Created by zgq on 16/4/21. // Copyright © 2016年 zgq. All rights reserved. // import Foundation //Swift类是构建代码所用的一种通用且灵活的构造体 ,Swift并不要求你为自定义类去创建独立的接口和实现文件, //你所要做的是在一个单一文件中定义一个类,系统会自动生成面向其它代码的外部接口 //与结构体相比类还有如下附加功能 //1,继承允许一个类继承另一个类的特征2.类型转换允许在运行时检查和解释一个类实例的类型3.解构器允许一个类实例释放任何其所分配的资源 4引用计数允许对一个类的多次引用 //类定义 class student { var studname :String = "" var mark:Int = 0 var mark2:Int = 0 } let studrecord = student() class MarksStruct { var mark :Int = 0 init(mark:Int){ self.mark=mark } } class studentMarks { var marks = 300 } let marks = studentMarks(); print("成绩为\(marks.marks)") //作为引用类型访问类属性 类的属性可以通过.来访问。格式为:实例化类名.属性名 class studentMarks1 { var marks1 = 300 var marks2 = 400 var marks3 = 900 } let marks1 = studentMarks1() print("Makrs1 is \(marks1.marks1)") //恒等运算符 //因为类是引用类型,有可能有多个常量和变量在后台同时引用某一个类实例 //为了能够判定两个常量或者变量是否引用同一个类实例,Swift内建了两个恒等运算符 class SampleClass { let myProperty:String init(s:String){ myProperty=s } } func ==(lhs:SampleClass,rhs:SampleClass) -> Bool { return lhs.myProperty==rhs.myProperty } let spClass1 = SampleClass(s:"Hello") let spClass2 = SampleClass(s:"Hello") if spClass1===spClass2 { print("引用相同的实例 \(spClass1)") } if spClass1 !== spClass2 { print("引用不同的实例 \(spClass1)") }
19caf1e8881bc964cea4960687f2b9ba
11.451327
85
0.658138
false
false
false
false
zhouxinv/SwiftThirdTest
refs/heads/master
SwiftTest/ViewController.swift
mit
1
// // ViewController.swift // SwiftTest // // Created by GeWei on 2016/12/19. // Copyright © 2016年 GeWei. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let snapKitButton: UIButton = UIButton() snapKitButton.tag = 1 snapKitButton.setTitle("SnapKit", for:.normal) snapKitButton.backgroundColor = UIColor.red snapKitButton.addTarget(self, action: #selector(tapped(_:)), for: .touchUpInside) self.view .addSubview(snapKitButton) snapKitButton.snp.makeConstraints { (make) in make.width.equalTo(100) make.height.equalTo(30) make.center.equalTo(self.view) } let kingfisherButton: UIButton = UIButton() kingfisherButton.tag = 2 kingfisherButton.setTitle("Kingfisher", for:.normal) kingfisherButton.backgroundColor = UIColor.red kingfisherButton.addTarget(self, action: #selector(tapped(_:)), for: .touchUpInside) self.view .addSubview(kingfisherButton) kingfisherButton.snp.makeConstraints { (make) in make.width.equalTo(100) make.height.equalTo(30) make.top.equalTo(snapKitButton.snp.bottom).offset(10) make.centerX.equalTo(snapKitButton) } let AlamofireButton: UIButton = UIButton() AlamofireButton.tag = 3 AlamofireButton.setTitle("Alamofire", for:.normal) AlamofireButton.backgroundColor = UIColor.red AlamofireButton.addTarget(self, action: #selector(tapped(_:)), for: .touchUpInside) self.view .addSubview(AlamofireButton) AlamofireButton.snp.makeConstraints { (make) in make.width.equalTo(100) make.height.equalTo(30) make.top.equalTo(kingfisherButton.snp.bottom).offset(10) make.centerX.equalTo(snapKitButton) } } func tapped(_ button: UIButton){ print("tapped") if button.tag == 1 { let snapKitVC = SnapKitTableViewController() navigationController?.pushViewController(snapKitVC, animated: true) } else if button.tag == 2{ let kingfisherVC = KingfisherViewController() navigationController?.pushViewController(kingfisherVC, animated: true) }else if button.tag == 3{ let alamofireVC = AlamofireController() navigationController?.pushViewController(alamofireVC, animated: true); } } }
b65f512a6fd80cadeb598ac55a591f07
33.706667
92
0.629274
false
false
false
false
sarahlee517/Mr-Ride-iOS
refs/heads/master
Mr Ride/Mr Ride/HistoryPageCell/HistoryTableViewCell.swift
mit
1
// // HistoryTableViewCell.swift // Mr Ride // // Created by Sarah on 5/27/16. // Copyright © 2016 AppWorks School Sarah Lee. All rights reserved. // import UIKit class HistoryTableViewCell: UITableViewCell { @IBOutlet weak var lineView: UIView! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var distanceLabel: UILabel! @IBOutlet weak var totalTimeLabel: UILabel! @IBOutlet weak var cellView: UIView! override func awakeFromNib() { super.awakeFromNib() setupCell() } } //MARK: - Setup UI extension HistoryTableViewCell{ func setupCell() { cellView.backgroundColor = UIColor.mrPineGreen85Color() self.backgroundColor = UIColor.clearColor() totalTimeLabel.textColor = UIColor.mrWhiteColor() distanceLabel.textColor = UIColor.mrWhiteColor() dateLabel.textColor = UIColor.mrWhiteColor() layoutMargins = UIEdgeInsetsZero } }
0bc14fe1c770b1b0f722a28bc8a89fdb
23.842105
68
0.689619
false
false
false
false
marcbaldwin/AutoLayoutBuilder
refs/heads/master
AutoLayoutBuilderTests/LayoutGuideRelationTests.swift
mit
1
import UIKit import XCTest @testable import AutoLayoutBuilder class LayoutGuideRelationTests: ALBTestCase { // MARK: UIViewController Extension Tests func testViewControllerLayoutGuidesTopShouldReturnLayoutGuideRelationForTopLayoutGuide() { XCTAssertTrue(viewController.topLayoutGuide === viewController.layoutGuides.top.layoutGuide) } func testViewControllerLayoutGuidesBottomShouldReturnLayoutGuideRelationForBottomLayoutGuide() { XCTAssertTrue(viewController.bottomLayoutGuide === viewController.layoutGuides.bottom.layoutGuide) } }
6b35a5fae76cb18383d7516c24c14168
35
106
0.82087
false
true
false
false
KosyanMedia/Aviasales-iOS-SDK
refs/heads/master
AviasalesSDKTemplate/Source/HotelsSource/UIImage+HLImages.swift
mit
1
// // UIImage+HLImages.swift // HotelLook // // Created by tromg on 19.11.15. // Copyright © 2015 Anton Chebotov. All rights reserved. // import Foundation @objc extension UIImage { class var photoPlaceholder: UIImage { return UIImage(named: "hotelPhotoPlaceholder") ?? UIImage() } // MARK: - Stars class var yellowStar: UIImage { return UIImage(named: "yellowStar") ?? UIImage() } class var yellowStarEmpty: UIImage { return UIImage(named: "yellowStarEmpty") ?? UIImage() } class var whiteStar: UIImage { return UIImage(named: "whiteStar") ?? UIImage() } class var whiteStarEmpty: UIImage { return UIImage(named: "whiteStarEmpty") ?? UIImage() } class var smallWhiteStar: UIImage { return UIImage(named: "smallWhiteStar") ?? UIImage() } class var smallWhiteStarEmpty: UIImage { return UIImage(named: "smallWhiteStarEmpty") ?? UIImage() } // MARK: - Trustyou legend Images class var trustyouLegendGreenImage: UIImage { return UIImage(named: "trustyouLegendGreenImage") ?? UIImage() } class var trustyouLegendYellowImage: UIImage { return UIImage(named: "trustyouLegendYellowImage") ?? UIImage() } class var trustyouLegendRedImage: UIImage { return UIImage(named: "trustyouLegendRedImage") ?? UIImage() } class var peekCheckImage: UIImage { return UIImage(named: "peekCheck") ?? UIImage() } class var peekCheckWarningImage: UIImage { return UIImage(named: "peekCheckWarning") ?? UIImage() } class var peekCheckMissImage: UIImage { return UIImage(named: "peekCheckMiss") ?? UIImage() } class var toastHeartIconImage: UIImage { return UIImage(named: "toastHeartIcon") ?? UIImage() } class var toastCheckMarkIcon: UIImage { return UIImage(named: "toastCheckMarkIcon") ?? UIImage() } class func fixedImageByScore(_ score: Int) -> UIImage { let image: UIImage if score < 65 { image = UIImage.trustyouLegendRedImage } else if score >= 65 && score <= 75 { image = UIImage.trustyouLegendYellowImage } else { image = UIImage.trustyouLegendGreenImage } return image } }
d3626f8c2310dcb190bf6aaf72781344
25.11236
71
0.63296
false
true
false
false
BryanHoke/swift-corelibs-foundation
refs/heads/master
Foundation/NSURLProtectionSpace.swift
apache-2.0
4
// 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 // /*! @const NSURLProtectionSpaceHTTP @abstract The protocol for HTTP */ public let NSURLProtectionSpaceHTTP: String = "NSURLProtectionSpaceHTTP" /*! @const NSURLProtectionSpaceHTTPS @abstract The protocol for HTTPS */ public let NSURLProtectionSpaceHTTPS: String = "NSURLProtectionSpaceHTTPS" /*! @const NSURLProtectionSpaceFTP @abstract The protocol for FTP */ public let NSURLProtectionSpaceFTP: String = "NSURLProtectionSpaceFTP" /*! @const NSURLProtectionSpaceHTTPProxy @abstract The proxy type for http proxies */ public let NSURLProtectionSpaceHTTPProxy: String = "NSURLProtectionSpaceHTTPProxy" /*! @const NSURLProtectionSpaceHTTPSProxy @abstract The proxy type for https proxies */ public let NSURLProtectionSpaceHTTPSProxy: String = "NSURLProtectionSpaceHTTPSProxy" /*! @const NSURLProtectionSpaceFTPProxy @abstract The proxy type for ftp proxies */ public let NSURLProtectionSpaceFTPProxy: String = "NSURLProtectionSpaceFTPProxy" /*! @const NSURLProtectionSpaceSOCKSProxy @abstract The proxy type for SOCKS proxies */ public let NSURLProtectionSpaceSOCKSProxy: String = "NSURLProtectionSpaceSOCKSProxy" /*! @const NSURLAuthenticationMethodDefault @abstract The default authentication method for a protocol */ public let NSURLAuthenticationMethodDefault: String = "NSURLAuthenticationMethodDefault" /*! @const NSURLAuthenticationMethodHTTPBasic @abstract HTTP basic authentication. Equivalent to NSURLAuthenticationMethodDefault for http. */ public let NSURLAuthenticationMethodHTTPBasic: String = "NSURLAuthenticationMethodHTTPBasic" /*! @const NSURLAuthenticationMethodHTTPDigest @abstract HTTP digest authentication. */ public let NSURLAuthenticationMethodHTTPDigest: String = "NSURLAuthenticationMethodHTTPDigest" /*! @const NSURLAuthenticationMethodHTMLForm @abstract HTML form authentication. Applies to any protocol. */ public let NSURLAuthenticationMethodHTMLForm: String = "NSURLAuthenticationMethodHTMLForm" /*! @const NSURLAuthenticationMethodNTLM @abstract NTLM authentication. */ public let NSURLAuthenticationMethodNTLM: String = "NSURLAuthenticationMethodNTLM" /*! @const NSURLAuthenticationMethodNegotiate @abstract Negotiate authentication. */ public let NSURLAuthenticationMethodNegotiate: String = "NSURLAuthenticationMethodNegotiate" /*! @const NSURLAuthenticationMethodClientCertificate @abstract SSL Client certificate. Applies to any protocol. */ public let NSURLAuthenticationMethodClientCertificate: String = "NSURLAuthenticationMethodClientCertificate" /*! @const NSURLAuthenticationMethodServerTrust @abstract SecTrustRef validation required. Applies to any protocol. */ public let NSURLAuthenticationMethodServerTrust: String = "NSURLAuthenticationMethodServerTrust" /*! @class NSURLProtectionSpace @discussion This class represents a protection space requiring authentication. */ public class NSURLProtectionSpace : NSObject, NSSecureCoding, NSCopying { public func copyWithZone(zone: NSZone) -> AnyObject { NSUnimplemented() } public static func supportsSecureCoding() -> Bool { return true } public func encodeWithCoder(aCoder: NSCoder) { NSUnimplemented() } public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } /*! @method initWithHost:port:protocol:realm:authenticationMethod: @abstract Initialize a protection space representing an origin server, or a realm on one @param host The hostname of the server @param port The port for the server @param protocol The sprotocol for this server - e.g. "http", "ftp", "https" @param realm A string indicating a protocol-specific subdivision of a single host. For http and https, this maps to the realm string in http authentication challenges. For many other protocols it is unused. @param authenticationMethod The authentication method to use to access this protection space - valid values include nil (default method), @"digest" and @"form". @result The initialized object. */ public init(host: String, port: Int, `protocol`: String?, realm: String?, authenticationMethod: String?) { NSUnimplemented() } /*! @method initWithProxyHost:port:type:realm:authenticationMethod: @abstract Initialize a protection space representing a proxy server, or a realm on one @param host The hostname of the proxy server @param port The port for the proxy server @param type The type of proxy - e.g. "http", "ftp", "SOCKS" @param realm A string indicating a protocol-specific subdivision of a single host. For http and https, this maps to the realm string in http authentication challenges. For many other protocols it is unused. @param authenticationMethod The authentication method to use to access this protection space - valid values include nil (default method) and @"digest" @result The initialized object. */ public init(proxyHost host: String, port: Int, type: String?, realm: String?, authenticationMethod: String?) { NSUnimplemented() } /*! @method realm @abstract Get the authentication realm for which the protection space that needs authentication @discussion This is generally only available for http authentication, and may be nil otherwise. @result The realm string */ public var realm: String? { NSUnimplemented() } /*! @method receivesCredentialSecurely @abstract Determine if the password for this protection space can be sent securely @result YES if a secure authentication method or protocol will be used, NO otherwise */ public var receivesCredentialSecurely: Bool { NSUnimplemented() } /*! @method isProxy @abstract Determine if this authenticating protection space is a proxy server @result YES if a proxy, NO otherwise */ /*! @method host @abstract Get the proxy host if this is a proxy authentication, or the host from the URL. @result The host for this protection space. */ public var host: String { NSUnimplemented() } /*! @method port @abstract Get the proxy port if this is a proxy authentication, or the port from the URL. @result The port for this protection space, or 0 if not set. */ public var port: Int { NSUnimplemented() } /*! @method proxyType @abstract Get the type of this protection space, if a proxy @result The type string, or nil if not a proxy. */ public var proxyType: String? { NSUnimplemented() } /*! @method protocol @abstract Get the protocol of this protection space, if not a proxy @result The type string, or nil if a proxy. */ public var `protocol`: String? { NSUnimplemented() } /*! @method authenticationMethod @abstract Get the authentication method to be used for this protection space @result The authentication method */ public var authenticationMethod: String { NSUnimplemented() } public override func isProxy() -> Bool { NSUnimplemented() } } extension NSURLProtectionSpace { /*! @method distinguishedNames @abstract Returns an array of acceptable certificate issuing authorities for client certification authentication. Issuers are identified by their distinguished name and returned as a DER encoded data. @result An array of NSData objects. (Nil if the authenticationMethod is not NSURLAuthenticationMethodClientCertificate) */ public var distinguishedNames: [NSData]? { NSUnimplemented() } } // TODO: Currently no implementation of Security.framework /* extension NSURLProtectionSpace { /*! @method serverTrust @abstract Returns a SecTrustRef which represents the state of the servers SSL transaction state @result A SecTrustRef from Security.framework. (Nil if the authenticationMethod is not NSURLAuthenticationMethodServerTrust) */ public var serverTrust: SecTrust? { NSUnimplemented() } } */
10de9cf67bf40cd1c1950765c3280c3c
36.327586
208
0.723672
false
false
false
false
spark/photon-tinker-ios
refs/heads/master
Photon-Tinker/Mesh/StepGetNewDeviceName.swift
apache-2.0
1
// // Created by Raimundas Sakalauskas on 2019-03-07. // Copyright (c) 2019 Particle. All rights reserved. // import Foundation class StepGetNewDeviceName : Gen3SetupStep { override func start() { guard let context = self.context else { return } context.delegate.gen3SetupDidRequestToEnterDeviceName(self) } func setDeviceName(name: String, onComplete:@escaping (Gen3SetupFlowError?) -> ()) { guard let context = self.context else { onComplete(nil) return } guard self.validateDeviceName(name) else { onComplete(.NameTooShort) return } ParticleCloud.sharedInstance().getDevice(context.targetDevice.deviceId!) { [weak self, weak context] device, error in guard let self = self, let context = context, !context.canceled else { return } if (error == nil) { device!.rename(name) { error in if error == nil { context.targetDevice.name = name onComplete(nil) self.stepCompleted() } else { onComplete(.UnableToRenameDevice) return } } } else { onComplete(.UnableToRenameDevice) return } } } private func validateDeviceName(_ name: String) -> Bool { return name.count > 0 } }
cf66302bdb6b158bb7c56b84d2202e59
26.892857
125
0.516645
false
false
false
false
bitjammer/swift
refs/heads/master
test/SILGen/cf.swift
apache-2.0
1
// RUN: %target-swift-frontend -import-cf-types -sdk %S/Inputs %s -emit-silgen -o - | %FileCheck %s // REQUIRES: objc_interop import CoreCooling // CHECK: sil hidden @_T02cf8useEmAllySo16CCMagnetismModelCF : // CHECK: bb0([[ARG:%.*]] : $CCMagnetismModel): func useEmAll(_ model: CCMagnetismModel) { // CHECK: function_ref @CCPowerSupplyGetDefault : $@convention(c) () -> @autoreleased Optional<CCPowerSupply> let power = CCPowerSupplyGetDefault() // CHECK: function_ref @CCRefrigeratorCreate : $@convention(c) (Optional<CCPowerSupply>) -> Optional<Unmanaged<CCRefrigerator>> let unmanagedFridge = CCRefrigeratorCreate(power) // CHECK: function_ref @CCRefrigeratorSpawn : $@convention(c) (Optional<CCPowerSupply>) -> @owned Optional<CCRefrigerator> let managedFridge = CCRefrigeratorSpawn(power) // CHECK: function_ref @CCRefrigeratorOpen : $@convention(c) (Optional<CCRefrigerator>) -> () CCRefrigeratorOpen(managedFridge) // CHECK: function_ref @CCRefrigeratorCopy : $@convention(c) (Optional<CCRefrigerator>) -> @owned Optional<CCRefrigerator> let copy = CCRefrigeratorCopy(managedFridge) // CHECK: function_ref @CCRefrigeratorClone : $@convention(c) (Optional<CCRefrigerator>) -> @autoreleased Optional<CCRefrigerator> let clone = CCRefrigeratorClone(managedFridge) // CHECK: function_ref @CCRefrigeratorDestroy : $@convention(c) (@owned Optional<CCRefrigerator>) -> () CCRefrigeratorDestroy(clone) // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.refrigerator!1.foreign : (CCMagnetismModel) -> () -> Unmanaged<CCRefrigerator>!, $@convention(objc_method) (CCMagnetismModel) -> Optional<Unmanaged<CCRefrigerator>> let f0 = model.refrigerator() // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.getRefrigerator!1.foreign : (CCMagnetismModel) -> () -> CCRefrigerator!, $@convention(objc_method) (CCMagnetismModel) -> @autoreleased Optional<CCRefrigerator> let f1 = model.getRefrigerator() // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.takeRefrigerator!1.foreign : (CCMagnetismModel) -> () -> CCRefrigerator!, $@convention(objc_method) (CCMagnetismModel) -> @owned Optional<CCRefrigerator> let f2 = model.takeRefrigerator() // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.borrowRefrigerator!1.foreign : (CCMagnetismModel) -> () -> CCRefrigerator!, $@convention(objc_method) (CCMagnetismModel) -> @autoreleased Optional<CCRefrigerator> let f3 = model.borrowRefrigerator() // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.setRefrigerator!1.foreign : (CCMagnetismModel) -> (CCRefrigerator!) -> (), $@convention(objc_method) (Optional<CCRefrigerator>, CCMagnetismModel) -> () model.setRefrigerator(copy) // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.giveRefrigerator!1.foreign : (CCMagnetismModel) -> (CCRefrigerator!) -> (), $@convention(objc_method) (@owned Optional<CCRefrigerator>, CCMagnetismModel) -> () model.giveRefrigerator(copy) // rdar://16846555 let prop: CCRefrigerator = model.fridgeProp } // Ensure that accessors are emitted for fields used as protocol witnesses. protocol Impedance { associatedtype Component var real: Component { get } var imag: Component { get } } extension CCImpedance: Impedance {} // CHECK-LABEL: sil hidden [transparent] [fragile] [thunk] @_T0SC11CCImpedanceV2cf9ImpedanceA2cDP4real9ComponentQzfgTW // CHECK-LABEL: sil shared [transparent] [fragile] @_T0SC11CCImpedanceV4realSdfg // CHECK-LABEL: sil hidden [transparent] [fragile] [thunk] @_T0SC11CCImpedanceV2cf9ImpedanceA2cDP4imag9ComponentQzfgTW // CHECK-LABEL: sil shared [transparent] [fragile] @_T0SC11CCImpedanceV4imagSdfg class MyMagnetism : CCMagnetismModel { // CHECK-LABEL: sil hidden [thunk] @_T02cf11MyMagnetismC15getRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @autoreleased CCRefrigerator override func getRefrigerator() -> CCRefrigerator { return super.getRefrigerator() } // CHECK-LABEL: sil hidden [thunk] @_T02cf11MyMagnetismC16takeRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @owned CCRefrigerator override func takeRefrigerator() -> CCRefrigerator { return super.takeRefrigerator() } // CHECK-LABEL: sil hidden [thunk] @_T02cf11MyMagnetismC18borrowRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @autoreleased CCRefrigerator override func borrowRefrigerator() -> CCRefrigerator { return super.borrowRefrigerator() } }
bb7c07461e4a16355f4cfa18c243e75a
55.636364
254
0.739767
false
false
false
false
LucasMW/Headache
refs/heads/master
src/bfide/BrainfuckInterpreter.swift
mit
1
// // BrainfuckInterpreter.swift // Brainfuck_IDE // // Created by Lucas Menezes on 07/03/16. // Copyright © 2016 MWAPPTECH. All rights reserved. // import Cocoa import Foundation class BrainfuckInterpreter { private (set) var program : [CChar] = [CChar]() //C string private (set) var memory : [Int8]! = [Int8]() //8 bit private var mem_idx : Int // equivalent to pointer to memory private var prg_idx : Int // equivalent to pointer to string private var loopStack : [Int] = [Int]() private (set) var output : [CChar] = [CChar]() //stdout equiv private (set) var input : [CChar] = [CChar]() //stdin equiv private (set) var output_s : String = String() private (set) var input_s : String = String() var dbg_messages = true var inputRedirect : Bool! var outputRedirect : Bool! // signal to stop interpreter private var sigStop : Bool! // tells user application that interpreter is waiting private (set) var waitingInput : Bool! // tells user application that interpreter has finished private (set) var finished : Bool! private (set) var crashed : Bool! private (set) var breakpointEnabled : Bool! private var codeWhenOutput : ((_ str : String) -> ())! private var codeWhenInput : (() -> ())! let instructions = [62 : BrainfuckInterpreter.greater, //62 > 60 : BrainfuckInterpreter.lesser ,//60 < 43 : BrainfuckInterpreter.plus , //43 + 45 : BrainfuckInterpreter.minus , //45 - 46 : BrainfuckInterpreter.dot ,//46 . 44 : BrainfuckInterpreter.comma, //44 , 91 : BrainfuckInterpreter.bracketOpen, //91 [ 93 : BrainfuckInterpreter.bracketClose] //93 ] private var benchmark = [Double]() private var longestTime : Double! = 0.0 init(cells : Int) { self.mem_idx = 0 self.prg_idx = 0 memory = [Int8](repeating: 0, count: cells) //zeroed memory self.inputRedirect = true self.outputRedirect = true self.sigStop = false self.waitingInput = false self.crashed = false self.breakpointEnabled = false //self.testEachFuncTime() } /** Sets Program String to the interpreter. This program will run with execute() - parameter program : String. A Swift String with the program instructions. The program must consist of a valid brainfuck program. - attention: Must not have brainfuck instructions inside comments - returns: nothing */ func setProgram(program : String) { dprint(program.count) self.program = program.cString(using: String.Encoding.utf8)! self.prg_idx = 0 //program must be read again dprint(self.program.count) } func setCodeWhenOutput(code : @escaping (_ str : String)->()) { self.codeWhenOutput = code } //MARK: LoopStack private func loopPush(index : Int) { loopStack.append(index) } private func loopPop() { loopStack.removeLast() } private func loopTop() -> Int { return loopStack.last! } private func loopFree() { loopStack.removeAll() } //MARK: Instructions func greater() { self.mem_idx = self.mem_idx &+ 1 //enable overflow if(self.mem_idx >= self.memory.count) { self.stop() self.crashed = true let str = "Access violation, there is no cell \(self.mem_idx)" self.output_s += String(format: "\nbfi: ACCESS VIOLATION. THERE IS NO CELL NUMBER %d\n", self.mem_idx) print(str) return } } func lesser() { self.mem_idx = self.mem_idx &- 1 //enable overflow if(self.mem_idx < 0) { self.stop() self.crashed = true let str = "Access violation, there is no cell \(self.mem_idx)" self.output_s += String(format: "\nbfi: ACCESS VIOLATION. THERE IS NO CELL NUMBER %d\n", self.mem_idx) print(str) return } } func plus() { memory[mem_idx] = memory[mem_idx] &+ 1 //enable overflow } func minus() { memory[mem_idx] = memory[mem_idx] &- 1 //enable overflow } func dot() { if(self.outputRedirect == true) { self.output.append(memory[mem_idx]) //self.output_s.append(c: UnicodeScalar(UInt8(bitPattern: memory[mem_idx]))) let i8 = memory[mem_idx] let ui8 = UInt8(bitPattern: i8) let scalar = UnicodeScalar(ui8) let char = Character(scalar) self.output_s.append(char) //codeWhenOutput(str: cCharToString(memory[mem_idx])) } else { putchar(Int32(memory[mem_idx])) } //this print is a performance killer. Be Warned //print(String(UnicodeScalar(UInt8(bitPattern: memory[mem_idx]))),terminator: "") } func comma() { //let keyboard = FileHandle.standardInput //let inputData = keyboard.availableData //let str = String(data: inputData, encoding:String.Encoding.utf8) //memory[mem_idx] = str?.cStringUsingEncoding(NSUTF8StringEncoding)!.first!.value? if(self.inputRedirect == true) { if(self.input.count <= 0 ) { objc_sync_enter(self) dprint("bfi: INTERPRETER ASKS FOR INPUT") self.waitingInput = true objc_sync_exit(self) } while(self.input.count <= 0) { if(self.sigStop == true) { return } usleep(3000) // make thread wait for it } objc_sync_enter(self) self.waitingInput = false memory[mem_idx] = self.input[0] self.input.removeFirst() //print(self.input) objc_sync_exit(self) } else { memory[mem_idx] = Int8(getchar()) } } func bracketOpen() { if(memory[mem_idx] != 0) { loopPush(index: prg_idx) } else { // skip while sequence //self.evaluateTime({ var internalLoopCount = 0 self.prg_idx += 1 var s = self.program[self.prg_idx] while(!(s == 93 && internalLoopCount == 0)) // while not match stop requirements { if(s == 91) { internalLoopCount += 1; } else if(s == 93) { internalLoopCount -= 1; } self.prg_idx += 1 s = self.program[self.prg_idx] //print("\(s) \(internalLoopCount) \(prg_idx)") //usleep(100) } //}, description: "Skip While") } } func bracketClose() { if(memory[mem_idx] != 0) { prg_idx = loopTop() } else { loopPop() // out of this loop } } //MARK: Execute // func executeInstruction(instruction : String) // { // let char = instruction.cString(using: String.Encoding.utf8)?.first! as! Int // self.instructions[0]() // } func executeStep() { let current = program[prg_idx] switch current { case Int8(62) : greater() //62 > case Int8(60) : lesser()//60 < case Int8(43) : plus() //43 + case Int8(45) : minus() //45 - case Int8(46) : dot() //46 . case Int8(44) : comma() //44 , case Int8(91) : bracketOpen() //91 [ case Int8(93) : bracketClose() //93 ] default: () } prg_idx += 1 } func execute() { self.finished = false dprint("Execute") self.evaluateTime(f: { while(self.prg_idx < self.program.count) { if(self.sigStop == true) { self.stopSequence(); return } // abort execution self.executeStep() } dprint("longestTime was \(self.longestTime!)") }, description: "execution") self.finished = true } func stop() { self.sigStop = true } /** Sends Input to the Interpreter. Thread safe. */ func sendInput(inputStr : String ) { objc_sync_enter(self) self.input_s += inputStr let input = inputStr.cString(using: String.Encoding.utf8) for c in input! { self.input.append(c) } //self.input.append(CChar(-1)) //EOF dprint("input received \(inputStr)") objc_sync_exit(self) } private func stopSequence() { dprint("bfi: EXECUTION ABORTED"); self.finished = true return } //MARK: Auxiliary private class func cCharToString(char : CChar) -> String { return String(UnicodeScalar(UInt8(bitPattern: char))) } private func evaluateTime(f : ()->() , description : String) { dprint(description) let date1 = CFAbsoluteTimeGetCurrent() f() let date2 = CFAbsoluteTimeGetCurrent() let time = date2-date1 self.longestTime = time > longestTime ? time : longestTime dprint("it took \(time)") } private func testEachFuncTime() { evaluateTime(f: {self.greater()},description: "greater") evaluateTime(f: {self.lesser()},description: "lesser") evaluateTime(f: {self.plus()},description: "plus") evaluateTime(f: {self.minus()},description: "minus") evaluateTime(f: {self.dot()},description: "dot") //evaluateTime(f: {sendInput(inputStr: "a"); self.comma()},description: "comma") evaluateTime(f: {self.bracketOpen()}, description: "[") evaluateTime(f: {self.bracketClose()}, description: "]") } private func dprint( _ a : Any){ if(dbg_messages){ print(a) } } }
22a343561095fe148bbc8c968310c1b3
28.19382
114
0.525931
false
false
false
false
sync/NearbyTrams
refs/heads/master
NearbyTramsKit-Tests/Source/FetchedResultsControllerChangeSpec.swift
mit
1
// // Copyright (c) 2014 Dblechoc. All rights reserved. // import Quick import Nimble import NearbyTramsKit class FetchedResultsControllerChangeSpec: QuickSpec { override func spec() { describe("init") { var changedObject: NSObject! var indexPath: NSIndexPath! var changeType: SNRFetchedResultsChangeType! var movedToIndexPath: NSIndexPath! var change: FetchedResultsControllerChange! beforeEach { changedObject = NSObject() indexPath = NSIndexPath(index: 5) changeType = SNRFetchedResultsChangeInsert movedToIndexPath = NSIndexPath(index: 3) change = FetchedResultsControllerChange(changedObject: changedObject, atIndexPath: indexPath, forChangeType: changeType, newIndexPath: movedToIndexPath) } it ("should have a changed object") { var expectedChangedObject = change.changedObject as NSObject expect(expectedChangedObject).to(equal(changedObject)) } it ("should have an index path") { expect(change.indexPath).to(equal(indexPath)) } it ("should have achange type") { expect(change.changeType).to(equal(changeType)) } it ("should have a moved index path") { expect(change.movedToIndexPath).to(equal(movedToIndexPath)) } } } }
1cdf8499e1d113ae411c88a4725cd59b
33.586957
168
0.566939
false
false
false
false
rene-dohan/CS-IOS
refs/heads/master
Renetik/Renetik/Classes/AFNetworking/CSAFClient.swift
mit
1
//// //// CSClient.swift //// Motorkari //// //// Created by Rene Dohan on 1/28/19. //// Copyright © 2019 Renetik Software. All rights reserved. //// // //import AFNetworking //import RenetikObjc // //open class CSAFClient: CSObject { // // public let url: String // public let manager: AFHTTPSessionManager // var defaultParams: Dictionary<String, String> = [:] // public var requestFailMessage = "Request failed" // public var requestCancelMessage = "Request cancelled" // // public init(url: String) { // self.url = url // let configuration = URLSessionConfiguration.default // configuration.httpMaximumConnectionsPerHost = 10 // configuration.timeoutIntervalForRequest = 60 // configuration.timeoutIntervalForResource = 60 // manager = AFHTTPSessionManager(baseURL: URL(string: url), // sessionConfiguration: configuration) // manager.responseSerializer = AFHTTPResponseSerializer() // } // // public func setVagueSecurityPolicy() { // var policy = AFSecurityPolicy(pinningMode: .none) // policy.allowInvalidCertificates = true // policy.validatesDomainName = false // manager.securityPolicy = policy // } // // public func addDefault(params: Dictionary<String, String>) { // defaultParams.add(params) // } // // public func clearDefaultParams() { // defaultParams.removeAll() // } // // public func acceptable(contentTypes: Array<String>) { // manager.responseSerializer.acceptableContentTypes = Set<String>(contentTypes) // } // // public func basicAuthentication(username: String, password: String) { // manager.requestSerializer // .setAuthorizationHeaderFieldWithUsername(username, password: password) // } // // open func get<Data: CSServerData>( // service: String, data: Data, // params: [String: Any?] = [:]) -> CSResponse<Data> { // let request = CSResponse(url, service, data, createParams(params)) // request.requestCancelledMessage = requestCancelMessage // request.type = .get // let response = CSAFResponse(self, request) // later { // self.execute(request, response) // } // return request // } // // open func post<Data: CSServerData>( // service: String, data: Data, // params: [String: String] = [:], // form: @escaping (AFMultipartFormData) -> Void) -> CSResponse<Data> { // let request = CSResponse(url, service, data, createParams(params)) // request.requestCancelledMessage = requestCancelMessage // request.type = .post // request.form = form // let response = CSAFResponse(self, request) //// execute(request, response) // manager.post(service, parameters: request.params, headers: nil, constructingBodyWith: form, // progress: response.onProgress, success: response.onSuccess, // failure: response.onFailure) // return request // } // // open func post<Data: CSServerData>( // service: String, data: Data, // params: [String: String?] = [:]) -> CSResponse<Data> { // let request = CSResponse(url, service, data, createParams(params)) // request.requestCancelledMessage = requestCancelMessage // request.type = .post // let response = CSAFResponse(self, request) // execute(request, response) // return request // } // // private func createParams(_ params: [String: Any?]) -> [String: Any?] { // var newParams: [String: Any?] = ["version": "IOS \(Bundle.shortVersion) \(Bundle.build)"] // newParams.add(defaultParams) // newParams.add(params) // return newParams // } // // func execute<Data: CSServerData>( // _ request: CSResponse<Data>, _ response: CSAFResponse<Data>) { // if request.type == .get { // manager.get(request.service, parameters: request.params, headers: nil, // progress: response.onProgress, success: response.onSuccess, // failure: response.onFailure) // } else { // if request.form.notNil { // manager.post(request.service, parameters: request.params, headers: nil, // constructingBodyWith: request.form!, progress: response.onProgress, // success: response.onSuccess, failure: response.onFailure) // } else { // manager.post(request.service, parameters: request.params, headers: nil, // progress: response.onProgress, success: response.onSuccess, // failure: response.onFailure) // } // } // } //} // //public extension AFMultipartFormData { // // public func appendUnicode(parts: [String: String]) { // logInfo(parts.asJson?.substring(to: 100)) // for (key, value) in parts { // appendPart(withForm: value.data(using: .unicode)!, name: key) // } // } // // public func appendUTF8(parts: [String: Any?]) { // logInfo(parts.asJson?.substring(to: 100)) // for (key, value) in parts { // appendPart(withForm: stringify(value).data(using: .utf8)!, name: key) // } // } // // func appendImage(parts: [UIImage]) { // logInfo(parts) // for index in 0..<parts.count { // appendPart(withFileData: // parts[index].jpegData(compressionQuality: 0.8)!, // name: "images[\(index)]", // fileName: "mobileUpload.jpg", mimeType: "image/jpeg") // } // } //} // //class CSAFResponse<ServerData: CSServerData>: NSObject { // let client: CSAFClient // let request: CSResponse<ServerData> // var retryCount = 0 // // init(_ client: CSAFClient, _ response: CSResponse<ServerData>) { // self.client = client // request = response // } // // func onProgress(_ progress: Progress) { // request.setProgress(progress.fractionCompleted) // } // // func onSuccess(_ task: URLSessionDataTask, _ data: Any?) { // handleResponse(task, data as? Data, error: nil) // } // // func onFailure(_ task: URLSessionDataTask?, _ error: Error) { // handleResponse(task, NSError.cast(error).userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as? Data, error: NSError.cast(error)) // } // // func handleResponse(_ task: URLSessionDataTask?, _ data: Data?, error: NSError?) { // logUrl(task) // let content = data.notNil ? String(data: data!, encoding: .utf8)! : "" // logInfo(content) // request.data!.loadContent(content) // if error.notNil && request.data!.isEmpty { // onHandleResponseError(task?.response, error!, content) // } else if request.data!.success { // request.success(request.data!) // } else { // onRequestFailed() // } // } // // func logUrl(_ task: URLSessionDataTask?) { // let taskRequest = task?.currentRequest // logInfo("from \(taskRequest?.url.asString)") // let requestUrl = "\(request.url)\(request.service)" // if requestUrl != taskRequest?.url?.absoluteString { // logInfo("for \(requestUrl)") // } // } // // func onHandleResponseError(_ httpResponse: URLResponse?, _ error: NSError, _ content: String) { // logWarn("Failed \(String(describing: httpResponse)) \(error.code) \(error.localizedDescription) \(content)") // // Sometimes reciving code -999 canceled // if error.code == -999 && retryCount < 3 { // retryCount += 1 // logInfo("-999 Zruseno Retrying..." + httpResponse.asString) // client.execute(request, self) // } else { // request.failed(message: error.localizedDescription) // } // } // // func onRequestFailed() { // if let message = request.data!.message { // request.failed(message: message) // } else { // request.failed(message: client.requestFailMessage) // } // } //}
515babedcf8b519471f559dadfd86fe1
37.478873
150
0.592362
false
false
false
false
1457792186/JWSwift
refs/heads/master
熊猫TV/XMTV/Classes/Main/Controller/NavigationController.swift
apache-2.0
2
// // NavigationController.swift // XMTV // // Created by Mac on 2017/1/3. // Copyright © 2017年 Mac. All rights reserved. // import UIKit class NavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() // UINavigationBar.appearance().barTintColor = UIColor.white // 设置naviBar背景图片 UINavigationBar.appearance().setBackgroundImage(UIImage.init(named: "navigationbarBackgroundWhite"), for: UIBarMetrics.default) // 设置title的字体 // UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName:UIFont.systemFont(ofSize: 20)] self.interactivePopGestureRecognizer?.delegate = nil } // MARK: - 拦截push控制器 override func pushViewController(_ viewController: UIViewController, animated: Bool) { print(self.viewControllers.count) if self.viewControllers.count < 1 { viewController.navigationItem.rightBarButtonItem = setRightButton() } else { viewController.hidesBottomBarWhenPushed = true viewController.navigationItem.leftBarButtonItem = setBackBarButtonItem() } super.pushViewController(viewController, animated: true) } // MARK: - private method func setBackBarButtonItem() -> UIBarButtonItem { let backButton = UIButton.init(type: .custom) backButton.setImage(UIImage(named: "setting_back"), for: .normal) backButton.sizeToFit() backButton.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0) backButton.addTarget(self, action: #selector(NavigationController.backClick), for: .touchUpInside) return UIBarButtonItem.init(customView: backButton) } /// 设置导航栏右边按钮 func setRightButton() -> UIBarButtonItem { let searchItem = UIButton.init(type: .custom) searchItem.setImage(UIImage(named: "searchbutton_nor"), for: .normal) searchItem.sizeToFit() searchItem.frame.size = CGSize(width: 30, height: 30) searchItem.contentHorizontalAlignment = .right searchItem.addTarget(self, action: #selector(NavigationController.searchClick), for: .touchUpInside) return UIBarButtonItem.init(customView: searchItem) } /// 点击右边的搜索 func searchClick() { let searchvc = SearchVC() self.pushViewController(searchvc, animated: true) } /// 返回 func backClick() { self.popViewController(animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
808689963b6aa6493abba71640768b89
33.792208
135
0.665174
false
false
false
false
brentdax/swift
refs/heads/master
test/SILGen/switch_multiple_entry_address_only.swift
apache-2.0
1
// RUN: %target-swift-emit-silgen -module-name switch_multiple_entry_address_only %s | %FileCheck %s enum E { case a(Any) case b(Any) case c(Any) } // CHECK-LABEL: sil hidden @$s34switch_multiple_entry_address_only8takesAnyyyypF : $@convention(thin) (@in_guaranteed Any) -> () func takesAny(_ x: Any) {} // CHECK-LABEL: sil hidden @$s34switch_multiple_entry_address_only0B9LabelsLet1eyAA1EO_tF : $@convention(thin) (@in_guaranteed E) -> () func multipleLabelsLet(e: E) { // CHECK: bb0 // CHECK: [[X_PHI:%.*]] = alloc_stack $Any // CHECK-NEXT: [[E_COPY:%.*]] = alloc_stack $E // CHECK-NEXT: copy_addr %0 to [initialization] [[E_COPY]] // CHECK-NEXT: switch_enum_addr [[E_COPY]] : $*E, case #E.a!enumelt.1: bb1, case #E.b!enumelt.1: bb2, default bb4 // CHECK: bb1: // CHECK-NEXT: [[E_PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[E_COPY]] : $*E, #E.a!enumelt.1 // CHECK-NEXT: [[ANY_BOX:%.*]] = alloc_stack $Any // CHECK-NEXT: copy_addr [take] [[E_PAYLOAD]] to [initialization] [[ANY_BOX]] // CHECK-NEXT: copy_addr [[ANY_BOX]] to [initialization] [[X_PHI]] // CHECK-NEXT: destroy_addr [[ANY_BOX]] // CHECK-NEXT: dealloc_stack [[ANY_BOX]] // CHECK-NEXT: dealloc_stack [[E_COPY]] // CHECK-NEXT: br bb3 // CHECK: bb2: // CHECK-NEXT: [[E_PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[E_COPY]] : $*E, #E.b!enumelt.1 // CHECK-NEXT: [[ANY_BOX:%.*]] = alloc_stack $Any // CHECK-NEXT: copy_addr [take] [[E_PAYLOAD]] to [initialization] [[ANY_BOX]] // CHECK-NEXT: copy_addr [[ANY_BOX]] to [initialization] [[X_PHI]] // CHECK-NEXT: destroy_addr [[ANY_BOX]] // CHECK-NEXT: dealloc_stack [[ANY_BOX]] // CHECK-NEXT: dealloc_stack [[E_COPY]] // CHECK-NEXT: br bb3 // CHECK: bb3: // CHECK: [[FN:%.*]] = function_ref @$s34switch_multiple_entry_address_only8takesAnyyyypF // CHECK-NEXT: apply [[FN]]([[X_PHI]] // CHECK-NEXT: destroy_addr [[X_PHI]] // CHECK-NEXT: br bb6 // CHECK: bb4: // CHECK-NEXT: br bb5 // CHECK: bb5: // CHECK-NEXT: destroy_addr [[E_COPY]] // CHECK-NEXT: dealloc_stack [[E_COPY]] // CHECK-NEXT: br bb6 // CHECK: bb6: // CHECK-NEXT: dealloc_stack [[X_PHI]] // CHECK-NEXT: tuple () // CHECK-NEXT: return switch e { case .a(let x), .b(let x): takesAny(x) default: break } } // CHECK-LABEL: sil hidden @$s34switch_multiple_entry_address_only0B9LabelsVar1eyAA1EO_tF : $@convention(thin) (@in_guaranteed E) -> () func multipleLabelsVar(e: E) { // CHECK: bb0 // CHECK: [[X_PHI:%.*]] = alloc_stack $Any // CHECK-NEXT: [[E_COPY:%.*]] = alloc_stack $E // CHECK-NEXT: copy_addr %0 to [initialization] [[E_COPY]] // CHECK-NEXT: switch_enum_addr [[E_COPY]] : $*E, case #E.a!enumelt.1: bb1, case #E.b!enumelt.1: bb2, default bb4 // CHECK: bb1: // CHECK-NEXT: [[E_PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[E_COPY]] : $*E, #E.a!enumelt.1 // CHECK-NEXT: [[ANY_BOX:%.*]] = alloc_stack $Any // CHECK-NEXT: copy_addr [take] [[E_PAYLOAD]] to [initialization] [[ANY_BOX]] // CHECK-NEXT: copy_addr [[ANY_BOX]] to [initialization] [[X_PHI]] // CHECK-NEXT: destroy_addr [[ANY_BOX]] // CHECK-NEXT: dealloc_stack [[ANY_BOX]] // CHECK-NEXT: dealloc_stack [[E_COPY]] // CHECK-NEXT: br bb3 // CHECK: bb2: // CHECK-NEXT: [[E_PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[E_COPY]] : $*E, #E.b!enumelt.1 // CHECK-NEXT: [[ANY_BOX:%.*]] = alloc_stack $Any // CHECK-NEXT: copy_addr [take] [[E_PAYLOAD]] to [initialization] [[ANY_BOX]] // CHECK-NEXT: copy_addr [[ANY_BOX]] to [initialization] [[X_PHI]] // CHECK-NEXT: destroy_addr [[ANY_BOX]] // CHECK-NEXT: dealloc_stack [[ANY_BOX]] // CHECK-NEXT: dealloc_stack [[E_COPY]] // CHECK-NEXT: br bb3 // CHECK: bb3: // CHECK-NEXT: [[ANY_BOX:%.*]] = alloc_box ${ var Any }, var, name "x" // CHECK-NEXT: [[BOX_PAYLOAD:%.*]] = project_box [[ANY_BOX]] : ${ var Any }, 0 // CHECK-NEXT: copy_addr [take] [[X_PHI]] to [initialization] [[BOX_PAYLOAD]] // CHECK-NEXT: [[ACCESS:%.*]] = begin_access [read] [unknown] [[BOX_PAYLOAD]] // CHECK-NEXT: [[ANY_STACK:%.*]] = alloc_stack $Any // CHECK-NEXT: copy_addr [[ACCESS]] to [initialization] [[ANY_STACK]] // CHECK-NEXT: end_access [[ACCESS]] // CHECK: [[FN:%.*]] = function_ref @$s34switch_multiple_entry_address_only8takesAnyyyypF // CHECK-NEXT: apply [[FN]]([[ANY_STACK]] // CHECK-NEXT: destroy_addr [[ANY_STACK]] // CHECK-NEXT: dealloc_stack [[ANY_STACK]] // CHECK-NEXT: destroy_value [[ANY_BOX]] // CHECK-NEXT: br bb6 // CHECK: bb4: // CHECK-NEXT: br bb5 // CHECK: bb5: // CHECK-NEXT: destroy_addr [[E_COPY]] // CHECK-NEXT: dealloc_stack [[E_COPY]] // CHECK-NEXT: br bb6 // CHECK: bb6: // CHECK-NEXT: dealloc_stack [[X_PHI]] // CHECK-NEXT: tuple () // CHECK-NEXT: return switch e { case .a(var x), .b(var x): takesAny(x) default: break } } // CHECK-LABEL: sil hidden @$s34switch_multiple_entry_address_only20fallthroughWithValue1eyAA1EO_tF : $@convention(thin) (@in_guaranteed E) -> () func fallthroughWithValue(e: E) { // CHECK: bb0 // CHECK: [[X_PHI:%.*]] = alloc_stack $Any // CHECK-NEXT: [[E_COPY:%.*]] = alloc_stack $E // CHECK-NEXT: copy_addr %0 to [initialization] [[E_COPY]] // CHECK-NEXT: switch_enum_addr [[E_COPY]] : $*E, case #E.a!enumelt.1: bb1, case #E.b!enumelt.1: bb2, default bb4 // CHECK: bb1: // CHECK-NEXT: [[E_PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[E_COPY]] : $*E, #E.a!enumelt.1 // CHECK-NEXT: [[ORIGINAL_ANY_BOX:%.*]] = alloc_stack $Any // CHECK-NEXT: copy_addr [take] [[E_PAYLOAD]] to [initialization] [[ORIGINAL_ANY_BOX]] // CHECK: [[FN1:%.*]] = function_ref @$s34switch_multiple_entry_address_only8takesAnyyyypF // CHECK-NEXT: apply [[FN1]]([[ORIGINAL_ANY_BOX]] // CHECK-NEXT: copy_addr [[ORIGINAL_ANY_BOX]] to [initialization] [[X_PHI]] // CHECK-NEXT: destroy_addr [[ORIGINAL_ANY_BOX]] // CHECK-NEXT: dealloc_stack [[ORIGINAL_ANY_BOX]] // CHECK-NEXT: dealloc_stack [[E_COPY]] // CHECK-NEXT: br bb3 // CHECK: bb2: // CHECK-NEXT: [[E_PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[E_COPY]] : $*E, #E.b!enumelt.1 // CHECK-NEXT: [[ANY_BOX:%.*]] = alloc_stack $Any // CHECK-NEXT: copy_addr [take] [[E_PAYLOAD]] to [initialization] [[ANY_BOX]] // CHECK-NEXT: copy_addr [[ANY_BOX]] to [initialization] [[X_PHI]] // CHECK-NEXT: destroy_addr [[ANY_BOX]] // CHECK-NEXT: dealloc_stack [[ANY_BOX]] // CHECK-NEXT: dealloc_stack [[E_COPY]] // CHECK-NEXT: br bb3 // CHECK: bb3: // CHECK: [[FN2:%.*]] = function_ref @$s34switch_multiple_entry_address_only8takesAnyyyypF // CHECK-NEXT: apply [[FN2]]([[X_PHI]] // CHECK-NEXT: destroy_addr [[X_PHI]] // CHECK-NEXT: br bb6 // CHECK: bb4: // CHECK-NEXT: br bb5 // CHECK: bb5: // CHECK-NEXT: destroy_addr [[E_COPY]] // CHECK-NEXT: dealloc_stack [[E_COPY]] // CHECK-NEXT: br bb6 // CHECK: bb6: // CHECK-NEXT: dealloc_stack [[X_PHI]] // CHECK-NEXT: tuple () // CHECK-NEXT: return switch e { case .a(let x): takesAny(x) fallthrough case .b(let x): takesAny(x) default: break } }
12c866671370ba79cbf00aa57ec47096
36.857895
145
0.595301
false
false
false
false
Eonil/EditorLegacy
refs/heads/master
Modules/Monolith.Swift/Standards/Sources/RFC4627/RFC4627.Extensions.swift
mit
3
// // RFC4627.Extensions.swift // Monolith // // Created by Hoon H. on 10/21/14. // // import Foundation // // Fragment description is missing due to lack of implementation in Cocoa. // We need to implement our own generator and parser. // ///// MARK: //extension RFC4627.Value: Printable { // public var description:Swift.String { // get { // // // switch self { // case let .Object(s): return "{}" // case let .Array(s): return "[]" // case let .String(s): return "\"\"" // case let .Number(s): return "" // case let .Boolean(s): return "" // case let .Null: return "null" // } // //// let d1 = JSON.serialise(self) //// let s2 = NSString(data: d1!, encoding: NSUTF8StringEncoding) as Swift.String //// return s2 // } // } //} //private func escapeString(s:String) -> String { // func shouldEscape(ch1:Character) -> (shouldPrefix:Bool, specifier:Character) { // switch ch1 { // case "\u{0022}": return (true, "\"") // case "\u{005C}": return (true, "\\") // case "\u{002F}": return (true, "/") // case "\u{0008}": return (true, "b") // case "\u{000C}": return (true, "f") // case "\u{000A}": return (true, "n") // case "\u{000D}": return (true, "r") // case "\u{0009}": return (true, "t") // default: return (false, ch1) // } // } // typealias Step = () -> Cursor // enum Cursor { // case None // case Available(Character, Step) // // static func restep(s:String) -> (Character, Step) { // let first = s[s.startIndex] as Character // let rest = s[s.startIndex.successor()..<s.endIndex] // let step = Cursor.restep(rest) // return (first, step) // } // } // // return step1 //}
8ef5eeba8e9cb1bf8a7e60e177a489ad
13.538462
83
0.563786
false
false
false
false
dalu93/Defaults
refs/heads/master
Sources/Defaults.swift
mit
1
// // Defaults.swift // Defaults // // Created by Luca D'Alberti on 9/27/16. // Copyright © 2016 dalu93. All rights reserved. // import Foundation // MARK: - DefaultKey declaration /// The structure define as much as it can the UserDefaults key. /// /// It contains the name and the type informations. public struct DefaultKey<A>: Equatable { public var name: String public init(_ name: String) { self.name = name } } /// The `DefaultKey` structure can be compared with other `DefaultKey` structs. /// /// - Note: Only `DefaultKey` with the same generic type are allowed to be compared /// - parameter lhs: A `DefaultKey` /// - parameter rhs: Other `DefaultKey` /// /// - returns: `true` if the generic type and the name are the same, /// otherwise `false`. public func ==<T>(lhs: DefaultKey<T>, rhs: DefaultKey<T>) -> Bool { return lhs.name == rhs.name } // MARK: - UserDefaults helpers public extension UserDefaults { /// Get a value stored in the `standard` `UserDefaults` /// /// - parameter key: The key /// /// - returns: The stored value, if there is, otherwise `nil` public func get<T>(for key: DefaultKey<T>) -> T? { return UserDefaults.standard.value(forKey: key.name) as? T } /// Get a value stored in the `standard` `UserDefaults` or a default value /// /// - parameter key: The key /// - parameter defaultValue: A default value /// /// - returns: The stored value, if there is, otherwise the default one public func get<T>(for key: DefaultKey<T>, or defaultValue: T) -> T { return (UserDefaults.standard.value(forKey: key.name) as? T) ?? defaultValue } /// Set a new value in the `standard` `UserDefaults`. /// /// If the new value is `nil`, the value will be removed from the storage /// /// - parameter value: The value. It can be `nil` /// - parameter key: The key public func set<T>(_ value: T?, for key: DefaultKey<T>) { if let value = value { UserDefaults.standard.setValue(value, forKey: key.name) UserDefaults.standard.synchronize() } else { UserDefaults.standard.removeValue(for: key) } } /// Remove a value in the `standard` `UserDefaults` for the specific key /// /// - parameter key: The key public func removeValue<T>(for key: DefaultKey<T>) { UserDefaults.standard.removeObject(forKey: key.name) UserDefaults.standard.synchronize() } }
ffd2115d8d4b3b0f7e0528174c0ddde7
30.469136
84
0.621812
false
false
false
false
cheyongzi/MGTV-Swift
refs/heads/master
MGTV-Swift/Search/ViewSource/SearchSuggestViewSource.swift
mit
1
// // SearchSuggestViewSource.swift // MGTV-Swift // // Created by Che Yongzi on 2016/12/14. // Copyright © 2016年 Che Yongzi. All rights reserved. // import UIKit class SearchSuggestTableViewSource: TableViewModel<SearchSuggestItem> { weak var delegate: SearchViewSourceDelegate? override var cellHeight: CGFloat { return 44 } override func cellConfig(_ view: UITableView, datas: [[SearchSuggestItem]], indexPath: IndexPath) -> UITableViewCell { let cell = view.dequeueReusableCell(withIdentifier: "SearchSuggestCell", for: indexPath) if let suggestCell = cell as? SearchSuggestCell { suggestCell.nameLabel.text = datas[indexPath.section][indexPath.row].name } return cell } //MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let item = datas[indexPath.section][indexPath.row] guard let name = item.name else { return } delegate?.startSearch(name) } } class SearchSuggestViewSource: NSObject { var suggestDatas: [SearchSuggestItem] = [] { didSet { suggestViewSource.datas = [suggestDatas] tableView.reloadData() } } let suggestViewSource = SearchSuggestTableViewSource([]) lazy var tableView: UITableView = { let tableView = UITableView(frame: CGRect(x: 0, y: 64, width: HNTVDeviceWidth, height: HNTVDeviceHeight-64)) tableView.backgroundColor = UIColor.white tableView.delegate = self.suggestViewSource tableView.dataSource = self.suggestViewSource tableView.separatorStyle = .none tableView.register(UINib.init(nibName: "SearchSuggestCell", bundle: nil), forCellReuseIdentifier: "SearchSuggestCell") return tableView }() //MARK: - Init override init() { super.init() NotificationCenter.default.addObserver(self, selector: #selector(keyboadDidAppear(_:)), name: .UIKeyboardDidShow, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } //MARK: - Keyboard notification func keyboadDidAppear(_ notification: Notification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size { tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0) tableView.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0) } } }
708faacc32967cc874c0459c35bd682c
33.946667
134
0.667303
false
false
false
false
PJayRushton/TeacherTools
refs/heads/master
Pods/BetterSegmentedControl/Pod/Classes/Segments/IconSegment.swift
mit
1
// // IconSegment.swift // BetterSegmentedControl // // Created by George Marmaridis on 10/02/2018. // import Foundation open class IconSegment: BetterSegmentedControlSegment { // MARK: Constants private struct DefaultValues { static let normalBackgroundColor: UIColor = .clear static let selectedBackgroundColor: UIColor = .clear } // MARK: Properties public var icon: UIImage public var iconSize: CGSize public var normalIconTintColor: UIColor public var normalBackgroundColor: UIColor public var selectedIconTintColor: UIColor public var selectedBackgroundColor: UIColor // MARK: Lifecycle public init(icon: UIImage, iconSize: CGSize, normalBackgroundColor: UIColor? = nil, normalIconTintColor: UIColor, selectedBackgroundColor: UIColor? = nil, selectedIconTintColor: UIColor) { self.icon = icon.withRenderingMode(.alwaysTemplate) self.iconSize = iconSize self.normalBackgroundColor = normalBackgroundColor ?? DefaultValues.normalBackgroundColor self.normalIconTintColor = normalIconTintColor self.selectedBackgroundColor = selectedBackgroundColor ?? DefaultValues.selectedBackgroundColor self.selectedIconTintColor = selectedIconTintColor } // MARK: BetterSegmentedControlSegment public lazy var normalView: UIView = { return view(withIcon: icon, iconSize: iconSize, backgroundColor: normalBackgroundColor, iconTintColor: normalIconTintColor) }() public lazy var selectedView: UIView = { return view(withIcon: icon, iconSize: iconSize, backgroundColor: selectedBackgroundColor, iconTintColor: selectedIconTintColor) }() private func view(withIcon icon: UIImage, iconSize: CGSize, backgroundColor: UIColor, iconTintColor: UIColor) -> UIView { let view = UIView() view.backgroundColor = backgroundColor let imageView = UIImageView(image: icon) imageView.frame = CGRect(x: 0, y: 0, width: iconSize.width, height: iconSize.height) imageView.contentMode = .scaleAspectFit imageView.tintColor = iconTintColor imageView.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin] view.addSubview(imageView) return view } } public extension IconSegment { class func segments(withIcons icons: [UIImage], iconSize: CGSize, normalBackgroundColor: UIColor? = nil, normalIconTintColor: UIColor, selectedBackgroundColor: UIColor? = nil, selectedIconTintColor: UIColor) -> [BetterSegmentedControlSegment] { return icons.map { IconSegment(icon: $0, iconSize: iconSize, normalBackgroundColor: normalBackgroundColor, normalIconTintColor: normalIconTintColor, selectedBackgroundColor: selectedBackgroundColor, selectedIconTintColor: selectedIconTintColor) } } }
b875071c713968bc94c7f9377a63b529
37.827957
103
0.590695
false
false
false
false
BlessNeo/ios-charts
refs/heads/master
Charts/Classes/Data/LineRadarChartDataSet.swift
apache-2.0
20
// // LineRadarChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 26/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class LineRadarChartDataSet: BarLineScatterCandleChartDataSet { public var fillColor = UIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0) public var fillAlpha = CGFloat(0.33) private var _lineWidth = CGFloat(1.0) public var drawFilledEnabled = false /// line width of the chart (min = 0.2, max = 10) /// :default: 1 public var lineWidth: CGFloat { get { return _lineWidth } set { _lineWidth = newValue if (_lineWidth < 0.2) { _lineWidth = 0.5 } if (_lineWidth > 10.0) { _lineWidth = 10.0 } } } public var isDrawFilledEnabled: Bool { return drawFilledEnabled } // MARK: NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { var copy = super.copyWithZone(zone) as! LineRadarChartDataSet copy.fillColor = fillColor copy._lineWidth = _lineWidth copy.drawFilledEnabled = drawFilledEnabled return copy } }
2bcb39573e673c8c3323baf0112f5fdc
23.080645
103
0.58205
false
false
false
false
InfyOmLabs/SwiftExtension
refs/heads/master
Pod/Classes/IntExtension.swift
mit
1
// // IntExtension.swift // SwiftExtension // // Created by Mitul Golakiya on 01/04/16. // Copyright © 2016 Dhvl Golakiya. All rights reserved. // import Foundation import UIKit extension Int { // Check is even public var isEven: Bool { return self % 2 == 0 } // Check is odd public var isOdd: Bool { return !self.isEven } // Check is Positive public var isPositive: Bool { return self >= 0 } // Check is Negative public var isNegative: Bool { return !self.isPositive } // Get Digit public func digit() -> [Int] { return String(self).compactMap{ Int(String($0)) } } // Get Digit count public var digitCount: Int { return self.digit().count } // Convert to Float public var toFloat: Float { return Float(self) } // Convert to CGFloat public var toCGFloat: CGFloat { return CGFloat(self) } // Convert to String public var toString: String { return String(self) } // Convert to Int64 public var toInt64: Int64 { return Int64(self) } // Convert to Double public var toDouble : Double { return Double(self) } // Convert to UInt public var toUInt : UInt { return UInt(self) } // Return Factorial public func factorial() -> Int { return self == 0 ? 1 : self * (self - 1).factorial() } } extension UInt { // Convert UInt to Int public var toInt: Int { return Int(self) } }
31653540f68d70cbe823b0241cf55476
17.418605
60
0.561869
false
false
false
false
Catteno/ChronometerKit
refs/heads/master
ChronometerKit/NSTimeInterval+TimeComponents.swift
mit
1
// // NSTimeInterval+TimeComponents.swift // Chronometer // // Created by Rafael Veronezi on 8/21/14. // Copyright (c) 2014 Syligo. All rights reserved. // import Foundation /// /// Extends the Time Interval Type to add time components /// extension NSTimeInterval { // // MARK: - Properties /// Get the total amount of hours that this Time Interval instance holds var hours: Int { return Int(floor(((self / 60.0) / 60.0))) } /// Get the hour component, up to 23 hours var hourComponent: Int { return self.hours % 24 } /// Get the total amount of minutes that this Time Interval instance holds var minutes: Int { return Int(floor(self / 60.0)) } /// Get the minutes component, up to 59 minutes var minuteComponent: Int { return minutes - (hours * 60) } /// Get the total amount of seconds that this Time Interval instance holds var seconds: Int { return Int(floor(self)) } /// Get the seconds component, up to 59 seconds public var secondComponent: Int { return seconds - (minutes * 60) } /// Get the total amount of miliseconds that this Time Interval instance holds var miliseconds: Int64 { return Int64((seconds * 1000) + milisecondComponent) } /// Get the miliseconds component public var milisecondComponent: Int { let (_, fracPart) = modf(self) return Int(fracPart * 100) } // // MARK: - Public Methods /// /// Get this NSTimeInterval instance as a formatted string /// - parameter useFraction: Optionally appends the miliseconds to the string /// public func getFormattedInterval(miliseconds useFraction: Bool) -> String { let hoursStr = hourComponent < 10 ? "0" + String(hourComponent) : String(hourComponent) let minutesStr = minuteComponent < 10 ? "0" + String(minuteComponent) : String(minuteComponent) let secondsStr = secondComponent < 10 ? "0" + String(secondComponent) : String(secondComponent) var counter = "\(hoursStr):\(minutesStr):\(secondsStr)" if useFraction { let milisecondsStr = milisecondComponent < 10 ? "0" + String(milisecondComponent) : String(milisecondComponent) counter += ".\(milisecondsStr)" } return counter } }
eb5a758025719d74d91648de8d176b6d
31.589041
123
0.631623
false
false
false
false
kz56cd/ios_sandbox_animate
refs/heads/master
IosSandboxAnimate/Views/Root/RootCell.swift
mit
1
// // RootCell.swift // IosSandboxAnimate // // Created by msano on 2016/03/12. // Copyright © 2016年 msano. All rights reserved. // import UIKit class RootCell: UITableViewCell { @IBOutlet private weak var cellNumLabel: UILabel! @IBOutlet private weak var titleLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func fillWithCell(num: Int, title: String) { let numStr = "\(num)" cellNumLabel.text = numStr.characters.count == 1 ? "0\(numStr)" : numStr titleLabel.text = title } }
a25770e45c63a800442f52e4fe8f48f1
23.034483
80
0.648494
false
false
false
false
KrishMunot/swift
refs/heads/master
test/SILOptimizer/definite_init_failable_initializers_diagnostics.swift
apache-2.0
6
// RUN: %target-swift-frontend -emit-sil -disable-objc-attr-requires-foundation-module -verify %s // High-level tests that DI rejects certain invalid idioms for early // return from initializers. // <rdar://problem/19267795> failable initializers that call noreturn function produces bogus diagnostics class FailableInitThatFailsReallyHard { init?() { // no diagnostics generated. fatalError("bad") } } class BaseClass {} final class DerivedClass : BaseClass { init(x : ()) { fatalError("bad") // no diagnostics. } } func something(_ x: Int) {} func something(_ x: inout Int) {} func something(_ x: AnyObject) {} func something(_ x: Any.Type) {} // <rdar://problem/22946400> DI needs to diagnose self usages in error block // // FIXME: crappy QoI class ErrantBaseClass { init() throws {} } class ErrantClass : ErrantBaseClass { let x: Int var y: Int override init() throws { x = 10 y = 10 try super.init() } init(invalidEscapeDesignated: ()) { x = 10 y = 10 do { try super.init() } catch {} } // expected-error {{'self' used inside 'catch' block reachable from super.init call}} convenience init(invalidEscapeConvenience: ()) { do { try self.init() } catch {} } // expected-error {{'self' used inside 'catch' block reachable from self.init call}} init(noEscapeDesignated: ()) throws { x = 10 y = 10 do { try super.init() } catch let e { throw e // ok } } convenience init(noEscapeConvenience: ()) throws { do { try self.init() } catch let e { throw e // ok } } convenience init(invalidAccess: ()) throws { do { try self.init() } catch let e { something(x) // expected-error {{'self' used inside 'catch' block reachable from self.init call}} something(self.x) // expected-error {{'self' used inside 'catch' block reachable from self.init call}} something(y) // expected-error {{'self' used inside 'catch' block reachable from self.init call}} something(self.y) // expected-error {{'self' used inside 'catch' block reachable from self.init call}} something(&y) // expected-error {{'self' used inside 'catch' block reachable from self.init call}} something(&self.y) // expected-error {{'self' used inside 'catch' block reachable from self.init call}} something(self) // expected-error {{'self' used inside 'catch' block reachable from self.init call}} // FIXME: not diagnosed something(self.dynamicType) throw e } } }
342609e2e34c2d88c8fe87eea273f2f5
24.949495
109
0.641105
false
false
false
false
kswaldemar/rewind-viewer
refs/heads/master
clients/old_version/swift/RewindClient.swift
mit
1
/** * Class for interaction with rewind-viewer from your own startegy class * * Implemented using CActiveSocket, which is shipped with swift-cgdk * For each frame (game tick) rewind-viewer expect "end" command at frame end * All objects should be represented as json string, * and will be decoded at viewer side to corresponding structures * * Every object has mandatory field "type" and arbitrary number of additional fields * For example end will looks like * {"type": "end"} * * For available types see enum PrimitveType in <path to primitives here> * * In order to provide support for your own primitives: * - add type with name of your choice to PrimitiveType in <path to primitives here> * - add structure with field description in file mentioned above * (you don't need to be expert in c++ to do that, just use already defined types as reference) * - add function for desirialisation from json in same file (see defined types in <path to primitives here>) * - send json string with your object instance description * * Note: All command only affect currently rendering frame and will not appear in next frame * Currently you should send object each frame to display it in viewer */ public class RewindClient { public static let instance = RewindClient(host: "127.0.0.1", port: 9111)! public enum Color: UInt32 { case red = 0xFF0000 case green = 0x00FF00 case blue = 0x0000FF case gray = 0x273142 } fileprivate let tc: TCPClient // просто для короткой запись, ибо писал в блокноте ///Should be send on end of move function ///all turn primitives can be rendered after that point public func endFrame() { send("{\"type\":\"end\"}") } public func circle(x: Double, y: Double, r: Double, color: UInt32) { send("{\"type\": \"circle\", \"x\": \(x), \"y\": \(y), \"r\": \(r), \"color\": \(color)}") } public func rect(x1: Double, y1: Double, x2: Double, y2: Double, color: UInt32) { send("{\"type\": \"rectangle\", \"x1\": \(x1), \"y1\": \(y1), \"x2\": \(x2), \"y2\": \(y2), \"color\": \(color)}") } public func line(x1: Double, y1: Double, x2: Double, y2: Double, color: UInt32) { send("{\"type\": \"line\", \"x1\": \(x1), \"y1\": \(y1), \"x2\": \(x2), \"y2\": \(y2), \"color\": \(color)}") } ///Living unit - circle with HP bar ///x, y, r - same as for circle ///hp, max_hp - current life level and maximum level respectively ///enemy - 3 state variable: 1 - for enemy; -1 - for friend; 0 - neutral. ///course - parameter needed only to properly rotate textures (it unused by untextured units) ///unit_type - define used texture, value 0 means 'no texture'. For supported textures see enum UnitType in Frame.h public func livingUnit(x: Double, y: Double, r: Double, hp: Int, maxHP: Int, enemy: Int, course: Double = 0, utype: Int = 0) { send("{\"type\": \"unit\", \"x\": \(x), \"y\": \(y), \"r\": \(r), \"hp\": \(hp), \"max_hp\": \(maxHP), \"enemy\": \(enemy), \"unit_type\": \(utype), \"course\": \(course)}") } public func message(_ msg: String) { send("{\"type\": \"message\", \"message\": \(msg)}") } init?(host: String, port: Int) { tc = TCPClient(address: host, port: Int32(port)) if !tc.connect() { print("Can't connect to host: \(host) port: \(port)") return nil } } private func send(_ str: String) { tc.write(bytes: str.utf8.map{ Byte(bitPattern: $0) }) } }
baac80b369dea62f45c7913ce2b91b9e
42.209877
177
0.626286
false
false
false
false
codeforgreenville/trolley-tracker-ios-client
refs/heads/master
TrolleyTracker/Controllers/UI/MapContainer/MapController.swift
mit
1
// // MapController.swift // TrolleyTracker // // Created by Austin Younts on 7/30/17. // Copyright © 2017 Code For Greenville. All rights reserved. // import UIKit import MapKit protocol MapControllerDelegate: class { func annotationSelected(_ annotation: MKAnnotationView?, userLocation: MKUserLocation?) func handleNoTrolleysUpdate(_ trolleysPresent: Bool) } class MapController: FunctionController { typealias Dependencies = HasModelController weak var delegate: MapControllerDelegate? private let viewController: MapViewController private let dependencies: Dependencies private let locationManager = CLLocationManager() private let mapDelegate = TrolleyMapViewDelegate() private let refreshTimer = RefreshTimer(interval: 60) private var modelController: ModelController { return dependencies.modelController } init(dependencies: Dependencies) { self.dependencies = dependencies self.viewController = MapViewController() } func prepare() -> UIViewController { viewController.delegate = self locationManager.requestWhenInUseAuthorization() modelController.trolleyObservers.add(handleTrolleyUpdate(_:)) viewController.mapView.showsUserLocation = true viewController.mapView.setRegionToDowntownGreenville() viewController.mapView.delegate = mapDelegate mapDelegate.annotationSelectionAction = { view in self.undimAllItems() let user = self.viewController.mapView.userLocation self.delegate?.annotationSelected(view, userLocation: user) self.dimItemsNotRelated(toView: view) } mapDelegate.annotationDeselectionAction = { view in self.delegate?.annotationSelected(nil, userLocation: nil) self.undimAllItems() } refreshTimer.action = loadRoutes return viewController } private func handleTrolleyUpdate(_ trolleys: [Trolley]) { viewController.mapView.addOrUpdateTrolley(trolleys) delegate?.handleNoTrolleysUpdate(!trolleys.isEmpty) } private func loadRoutes() { modelController.loadTrolleyRoutes { routes in self.viewController.mapView.replaceCurrentRoutes(with: routes) } } private func dimItemsNotRelated(toView view: MKAnnotationView) { guard let trolleyView = view as? TrolleyAnnotationView, let trolley = trolleyView.annotation as? Trolley, let route = modelController.route(for: trolley) else { return } mapDelegate.highlightedTrolley = trolley mapDelegate.highlightedRoute = route mapDelegate.shouldDimStops = true viewController.mapView.setStops(faded: true) viewController.mapView.reloadRouteOverlays() viewController.dimTrolleysOtherThan(trolley) } private func undimAllItems() { mapDelegate.highlightedTrolley = nil mapDelegate.highlightedRoute = nil mapDelegate.shouldDimStops = false viewController.mapView.undimAllTrolleyAnnotations() viewController.mapView.reloadRouteOverlays() viewController.mapView.setStops(faded: false) } func unobscure(_ view: UIView) { guard let annotationView = view as? MKAnnotationView, let annotation = annotationView.annotation else { return } viewController.mapView.setCenter(annotation.coordinate, animated: true) } } extension MapController: MapVCDelegate { func locateMeButtonTapped() { viewController.mapView.centerOnUser(context: viewController) } func annotationSelected(_ annotation: MKAnnotationView?, userLocation: MKUserLocation?) { delegate?.annotationSelected(annotation, userLocation: userLocation) } func viewAppeared() { loadRoutes() modelController.startTrackingTrolleys() refreshTimer.start() } func viewDisappeared() { refreshTimer.stop() modelController.stopTrackingTrolleys() } }
107fed02d66f38900f7c6fcd56a422c5
30.148148
79
0.679667
false
false
false
false
rudkx/swift
refs/heads/main
test/IDE/complete_ambiguous.swift
apache-2.0
1
// RUN: %empty-directory(%t) // RUN: %target-swift-ide-test -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t struct A { func doAThings() -> A { return self } } struct B { func doBThings() {} } func overloadedReturn() -> A { return A() } func overloadedReturn() -> B { return B() } overloadedReturn().#^SIMPLE^# overloadedReturn(1).#^SIMPLE_EXTRAARG?check=SIMPLE^# struct HasMembers { func overloadedReturn() -> A { return A() } func overloadedReturn() -> B { return B() } } HasMembers().overloadedReturn().#^SIMPLE_MEMBERS?check=SIMPLE^# func givenErrorExpr(_ a: String) -> A {} func givenErrorExpr(_ b: Int) -> B {} func arrayWrapper<T>(a: T) -> [T] arrayWrapper(overloadedReturn()).#^SKIP_DUPLICATES^# // SKIP_DUPLICATES: Begin completions // SKIP_DUPLICATES-NOT: count[#Int#] // SKIP_DUPLICATES-NOT: formIndex({#(i): &Int#}, {#offsetBy: Int#})[#Void#] // SKIP_DUPLICATES: Decl[InstanceVar]/CurrNominal/IsSystem: count[#Int#]{{; name=.+$}} // SKIP_DUPLICATES: Decl[InstanceMethod]/Super/IsSystem: formIndex({#(i): &Int#}, {#offsetBy: Int#})[#Void#]{{; name=.+$}} // SKIP_DUPLICATES-NOT: count[#Int#] // SKIP_DUPLICATES-NOT: formIndex({#(i): &Int#}, {#offsetBy: Int#})[#Void#] // SKIP_DUPLICATES: End completions let x: (inout Int, Int) -> () = arrayWrapper(overloadedReturn()).#^SKIP_COMPOUND_DUPLICATES^# // SKIP_COMPOUND_DUPLICATES: Begin completions // SKIP_COMPOUND_DUPLICATES: Decl[InstanceMethod]/Super/IsSystem/TypeRelation[Identical]: formIndex(_:offsetBy:)[#(inout Int, Int) -> ()#]{{; name=.+$}} // SKIP_COMPOUND_DUPLICATES-NOT: formIndex(_:offsetBy:)[#(inout Int, Int) -> ()#] // SKIP_COMPOUND_DUPLICATES: End completions func testCallAsFunctionDeduplication() { struct Test<T> { func callAsFunction(x: Int) {} } func overloaded() -> Test<A> { fatalError() } func overloaded() -> Test<B> { fatalError() } overloaded()#^SKIP_CALLASFUNCTION_DUPLICATES^# } // FIXME: Update this to check the callAsFunction pattern only appears once when PostfixExpr completion is migrated to the solver-based implementation (which handles ambiguity). // SKIP_CALLASFUNCTION_DUPLICATES-NOT: Begin completions givenErrorExpr(undefined).#^ERROR_IN_BASE?check=SIMPLE^# // SIMPLE: Begin completions, 4 items // SIMPLE-DAG: Keyword[self]/CurrNominal: self[#A#]{{; name=.+$}} // SIMPLE-DAG: Decl[InstanceMethod]/CurrNominal: doAThings()[#A#]{{; name=.+$}} // SIMPLE-DAG: Keyword[self]/CurrNominal: self[#B#]{{; name=.+$}} // SIMPLE-DAG: Decl[InstanceMethod]/CurrNominal: doBThings()[#Void#]{{; name=.+$}} // SIMPLE: End completions let x: A = overloadedReturn().#^RELATED^# let x: A = overloadedReturn(1).#^RELATED_EXTRAARG?check=RELATED^# // RELATED: Begin completions, 4 items // RELATED-DAG: Keyword[self]/CurrNominal: self[#A#]{{; name=.+$}} // RELATED-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: doAThings()[#A#]{{; name=.+$}} // RELATED-DAG: Keyword[self]/CurrNominal: self[#B#]{{; name=.+$}} // RELATED-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: doBThings()[#Void#]{{; name=.+$}} // RELATED: End completions func takesClosureGivingA(_ callback: () -> A) -> B {} func takesB(_ item: B) {} takesB((takesClosureGivingA { return overloadedReturn().#^RELATED_INERROREXPR?check=RELATED^# }).) func overloadedArg(_ arg: A) -> A {} func overloadedArg(_ arg: B) -> B {} overloadedArg(.#^UNRESOLVED_AMBIGUOUS^#) // UNRESOLVED_AMBIGUOUS: Begin completions, 4 items // UNRESOLVED_AMBIGUOUS-DAG: Decl[InstanceMethod]/CurrNominal: doAThings({#(self): A#})[#() -> A#]{{; name=.+$}} // UNRESOLVED_AMBIGUOUS-DAG: Decl[Constructor]/CurrNominal/TypeRelation[Identical]: init()[#A#]{{; name=.+$}} // UNRESOLVED_AMBIGUOUS-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: doBThings({#(self): B#})[#() -> Void#]{{; name=.+$}} // UNRESOLVED_AMBIGUOUS-DAG: Decl[Constructor]/CurrNominal/TypeRelation[Identical]: init()[#B#]{{; name=.+$}} // UNRESOLVED_AMBIGUOUS: End completions // Make sure we still offer A and B members as the user may intend to add a member on the end of the overloadedArg call later that has type B. takesB(overloadedArg(.#^UNRESOLVED_STILLAMBIGUOUS?check=UNRESOLVED_AMBIGUOUS^#)) func overloadedArg2(_ arg: A) -> Void {} func overloadedArg2(_ arg: A) -> Never {} func overloadedArg2(_ arg: B) -> B {} takesB(overloadedArg2(.#^UNRESOLVED_UNAMBIGUOUS^#)) // UNRESOLVED_UNAMBIGUOUS: Begin completions, 2 items // UNRESOLVED_UNAMBIGUOUS-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: doBThings({#(self): B#})[#() -> Void#]{{; name=.+$}} // UNRESOLVED_UNAMBIGUOUS-DAG: Decl[Constructor]/CurrNominal/TypeRelation[Identical]: init()[#B#]{{; name=.+$}} // UNRESOLVED_UNAMBIGUOUS: End completions switch undefined { case takesClosureGivingA { return overloadedReturn().#^NOCALLBACK_FALLBACK?check=RELATED^# }: break } func takesClosureA(_ arg: (A) -> ()) {} func takesClosureB(_ arg: (B) -> ()) {} takesClosureA { arg in takesClosureB { arg in arg.#^MULTICLOSURE_FALLBACK^# } print() + 10 } + 10 // MULTICLOSURE_FALLBACK: Begin completions, 2 items // MULTICLOSURE_FALLBACK-DAG: Keyword[self]/CurrNominal: self[#B#]{{; name=.+$}} // MULTICLOSURE_FALLBACK-DAG: Decl[InstanceMethod]/CurrNominal: doBThings()[#Void#]{{; name=.+$}} // MULTICLOSURE_FALLBACK: End completions func takesAnonClosure(_ x: (A) -> A) { return A() } func takesAnonClosure(_ x: (B, A) -> B { return B() } func takesAnonClosure(_ x: () -> (A, B) { return (A(), B()) } struct TestRelations { static let a = A() static let b = B() static let ab = (A(), B()) } // test we consider both overloads as $0 or $1 may have just not been written yet takesAnonClosure { $1.#^UNAMBIGUOUSCLOSURE_ARG^# } // UNAMBIGUOUSCLOSURE_ARG: Begin completions, 2 items // UNAMBIGUOUSCLOSURE_ARG-DAG: Keyword[self]/CurrNominal: self[#A#]{{; name=.+$}} // UNAMBIGUOUSCLOSURE_ARG-DAG: Decl[InstanceMethod]/CurrNominal: doAThings()[#A#]{{; name=.+$}} // UNAMBIGUOUSCLOSURE_ARG: End completions takesAnonClosure { $0.#^AMBIGUOUSCLOSURE_ARG^# } // AMBIGUOUSCLOSURE_ARG: Begin completions, 4 items // AMBIGUOUSCLOSURE_ARG-DAG: Keyword[self]/CurrNominal: self[#A#]{{; name=.+$}} // AMBIGUOUSCLOSURE_ARG-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: doAThings()[#A#]{{; name=.+$}} // AMBIGUOUSCLOSURE_ARG-DAG: Keyword[self]/CurrNominal: self[#B#]{{; name=.+$}} // AMBIGUOUSCLOSURE_ARG-DAG: Decl[InstanceMethod]/CurrNominal: doBThings()[#Void#]{{; name=.+$}} // AMBIGUOUSCLOSURE_ARG: End completions takesAnonClosure { TestRelations.#^AMBIGUOUSCLOSURE_ARG_RETURN^# } // AMBIGUOUSCLOSURE_ARG_RETURN: Begin completions, 6 items // AMBIGUOUSCLOSURE_ARG_RETURN-DAG: Keyword[self]/CurrNominal: self[#TestRelations.Type#]{{; name=.+$}} // AMBIGUOUSCLOSURE_ARG_RETURN-DAG: Keyword/CurrNominal: Type[#TestRelations.Type#]{{; name=.+$}} // AMBIGUOUSCLOSURE_ARG_RETURN-DAG: Decl[StaticVar]/CurrNominal/TypeRelation[Identical]: a[#A#]{{; name=.+$}} // AMBIGUOUSCLOSURE_ARG_RETURN-DAG: Decl[StaticVar]/CurrNominal/TypeRelation[Identical]: b[#B#]{{; name=.+$}} // AMBIGUOUSCLOSURE_ARG_RETURN-DAG: Decl[StaticVar]/CurrNominal/TypeRelation[Identical]: ab[#(A, B)#]{{; name=.+$}} // AMBIGUOUSCLOSURE_ARG_RETURN-DAG: Decl[Constructor]/CurrNominal: init()[#TestRelations#]{{; name=.+$}} // AMBIGUOUSCLOSURE_ARG_RETURN: End completions func takesDictAB(_ x: [A: B]) {} func takesOptDictAB(_ x: [A: B]?) {} func overloadedGivesAorB(_ x: A) -> A {} func overloadedGivesAorB(_ x: B) -> B {} var assignDict: [A : B] = [:] let _: [A : B] = [TestRelations.#^PARSED_AS_ARRAY?check=PARSED_AS_ARRAY_KEY^#] let _: [A : B]? = [TestRelations.#^PARSED_AS_ARRAY_OPTIONAL?check=PARSED_AS_ARRAY_KEY^#] let _: [[A : B]] = [[TestRelations.#^PARSED_AS_ARRAY_NESTED?check=PARSED_AS_ARRAY_KEY^#]] assignDict = [TestRelations.#^PARSED_AS_ARRAY_ASSIGN?check=PARSED_AS_ARRAY_KEY^#] let _: [A: B] = [overloadedGivesAorB(TestRelations.#^PARSED_AS_ARRAY_INDIRECT?check=PARSED_AS_ARRAY_KEY^#)] let _: [[A: B]] = [[overloadedGivesAorB(TestRelations.#^PARSED_AS_ARRAY_INDIRECT_NESTED?check=PARSED_AS_ARRAY_KEY^#)]] takesDictAB([overloadedGivesAorB(TestRelations.#^PARSED_AS_ARRAY_INDIRECT_CALL?check=PARSED_AS_ARRAY_KEY^#)]); takesOptDictAB([overloadedGivesAorB(TestRelations.#^PARSED_AS_ARRAY_INDIRECT_CALL_OPT?check=PARSED_AS_ARRAY_KEY^#)]); func testReturnLiteralMismatch() -> [A: B] { return [overloadedGivesAorB(TestRelations.#^PARSED_AS_ARRAY_INDIRECT_RETURN?check=PARSED_AS_ARRAY_KEY^#)] } func arrayLiteralDictionaryMismatch<T>(a: inout T) where T: ExpressibleByDictionaryLiteral, T.Key == A, T.Value == B { a = [TestRelations.#^PARSED_AS_ARRAY_GENERIC?check=PARSED_AS_ARRAY_KEY^#] } // PARSED_AS_ARRAY_KEY: Begin completions, 6 items // PARSED_AS_ARRAY_KEY-DAG: Keyword[self]/CurrNominal: self[#TestRelations.Type#]{{; name=.+$}} // PARSED_AS_ARRAY_KEY-DAG: Keyword/CurrNominal: Type[#TestRelations.Type#]{{; name=.+$}} // PARSED_AS_ARRAY_KEY-DAG: Decl[StaticVar]/CurrNominal/TypeRelation[Identical]: a[#A#]{{; name=.+$}} // PARSED_AS_ARRAY_KEY-DAG: Decl[StaticVar]/CurrNominal: b[#B#]{{; name=.+$}} // PARSED_AS_ARRAY_KEY-DAG: Decl[StaticVar]/CurrNominal: ab[#(A, B)#]{{; name=.+$}} // PARSED_AS_ARRAY_KEY-DAG: Decl[Constructor]/CurrNominal: init()[#TestRelations#]{{; name=.+$}} // PARSED_AS_ARRAY_KEY: End completions let _: [(A, B) : B] = [TestRelations.#^PARSED_AS_ARRAY_TUPLE^#] let _: [(A, B)] = [TestRelations.#^PARSED_AS_ARRAY_ARRAY?check=PARSED_AS_ARRAY_TUPLE^#] // PARSED_AS_ARRAY_TUPLE: Begin completions, 6 items // PARSED_AS_ARRAY_TUPLE-DAG: Keyword[self]/CurrNominal: self[#TestRelations.Type#]{{; name=.+$}} // PARSED_AS_ARRAY_TUPLE-DAG: Keyword/CurrNominal: Type[#TestRelations.Type#]{{; name=.+$}} // PARSED_AS_ARRAY_TUPLE-DAG: Decl[StaticVar]/CurrNominal: a[#A#]{{; name=.+$}} // PARSED_AS_ARRAY_TUPLE-DAG: Decl[StaticVar]/CurrNominal: b[#B#]{{; name=.+$}} // PARSED_AS_ARRAY_TUPLE-DAG: Decl[StaticVar]/CurrNominal/TypeRelation[Identical]: ab[#(A, B)#]{{; name=.+$}} // PARSED_AS_ARRAY_TUPLE-DAG: Decl[Constructor]/CurrNominal: init()[#TestRelations#]{{; name=.+$}} // PARSED_AS_ARRAY_TUPLE: End completions func testMissingArgs() { enum Foo { case foo } enum Bar { case bar } struct Test { static let foo = Foo.foo static let bar = Bar.bar } func test(foo: Foo) {} func test(bar: Bar) {} func test2(first: Bar, second: Int) {} func test2(first: Foo) {} func test3(skipMe: Int, after: Foo) {} func test3(after: Bar) {} func test4(skipMe: Int, both: Foo, skipMeToo: Int) {} func test4(both: Bar, skipMeTo: Int) {} test(foo: Test.#^OVERLOADEDFUNC_FOO^#) // OVERLOADEDFUNC_FOO: Begin completions, 5 items // OVERLOADEDFUNC_FOO-DAG: Keyword[self]/CurrNominal: self[#Test.Type#]{{; name=.+$}} // OVERLOADEDFUNC_FOO-DAG: Keyword/CurrNominal: Type[#Test.Type#]{{; name=.+$}} // OVERLOADEDFUNC_FOO-DAG: Decl[StaticVar]/CurrNominal/TypeRelation[Identical]: foo[#Foo#]{{; name=.+$}} // OVERLOADEDFUNC_FOO-DAG: Decl[StaticVar]/CurrNominal: bar[#Bar#]{{; name=.+$}} // OVERLOADEDFUNC_FOO-DAG: Decl[Constructor]/CurrNominal: init()[#Test#]{{; name=.+$}} // OVERLOADEDFUNC_FOO: End completions test(bar: Test.#^OVERLOADEDFUNC_BAR^#) // OVERLOADEDFUNC_BAR: Begin completions, 5 items // OVERLOADEDFUNC_BAR-DAG: Keyword[self]/CurrNominal: self[#Test.Type#]{{; name=.+$}} // OVERLOADEDFUNC_BAR-DAG: Keyword/CurrNominal: Type[#Test.Type#]{{; name=.+$}} // OVERLOADEDFUNC_BAR-DAG: Decl[StaticVar]/CurrNominal: foo[#Foo#]{{; name=.+$}} // OVERLOADEDFUNC_BAR-DAG: Decl[StaticVar]/CurrNominal/TypeRelation[Identical]: bar[#Bar#]{{; name=.+$}} // OVERLOADEDFUNC_BAR-DAG: Decl[Constructor]/CurrNominal: init()[#Test#]{{; name=.+$}} // OVERLOADEDFUNC_BAR: End completions test(Test.#^OVERLOADEDFUNC_MISSINGLABEL?check=OVERLOADEDFUNC_BOTH^#, extraArg: 2) test2(first: Test.#^OVERLOADEDFUNC_MISSINGARG_AFTER?check=OVERLOADEDFUNC_BOTH^#) // Also check ambiguous member functions struct TestStruct { func test2(first: Bar, second: Int) {} func test2(first: Foo) {} } TestStruct().test2(first: Test.#^OVERLOADEDMEMBER_MISSINGARG_AFTER?check=OVERLOADEDFUNC_BOTH^#) // TODO: Should we insert the missing label in the completion text for OVERLOADEDFUNC_MISSINGLABEL? // OVERLOADEDFUNC_BOTH: Begin completions, 5 items // OVERLOADEDFUNC_BOTH-DAG: Keyword[self]/CurrNominal: self[#Test.Type#]{{; name=.+$}} // OVERLOADEDFUNC_BOTH-DAG: Keyword/CurrNominal: Type[#Test.Type#]{{; name=.+$}} // OVERLOADEDFUNC_BOTH-DAG: Decl[StaticVar]/CurrNominal/TypeRelation[Identical]: foo[#Foo#]{{; name=.+$}} // OVERLOADEDFUNC_BOTH-DAG: Decl[StaticVar]/CurrNominal/TypeRelation[Identical]: bar[#Bar#]{{; name=.+$}} // OVERLOADEDFUNC_BOTH-DAG: Decl[Constructor]/CurrNominal: init()[#Test#]{{; name=.+$}} // OVERLOADEDFUNC_BOTH: End completions test3(after: Test.#^OVERLOADEDFUNC_MISSINGARG_BEFORE?check=OVERLOADEDFUNC_BAR^#); test4(both: Test.#^OVERLOADEDFUNC_MISSINGARG_BEFOREANDAFTER?check=OVERLOADEDFUNC_BAR^#) enum Bop { case bop } enum Bix { case bix } enum Blu { case blu } enum Baz { case baz } enum Boy { case boy } func trailing(x: Int, _ y: () -> Foo, z: () -> ()) {} func trailing(x: Int, _ y: () -> Bar, z: (() -> ())?) {} func trailing(x: Int, _ y: () -> Bop, z: Any) {} func trailing<T>(x: Int, _ y: () -> Bix, z: T) {} func trailing<T>(x: Int, _ y: () -> Boy, z: T?) {} func trailing<T>(x: Int, _ y: () -> Blu, z: [T]?) {} func trailing(x: Int, _ y: () -> Blu, z: inout Any) {} func trailing(x: Int, _ y: () -> Baz, z: Int) {} trailing(x: 2, { .#^MISSINGARG_INLINE^# }) trailing(x: 2) { .#^MISSINGARG_TRAILING^# } // MISSINGARG_INLINE: Begin completions, 14 items // MISSINGARG_INLINE-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: foo[#Foo#]; name=foo // MISSINGARG_INLINE-DAG: Decl[InstanceMethod]/CurrNominal: hash({#(self): Foo#})[#(into: inout Hasher) -> Void#]; name=hash(:) // MISSINGARG_INLINE-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: bar[#Bar#]; name=bar // MISSINGARG_INLINE-DAG: Decl[InstanceMethod]/CurrNominal: hash({#(self): Bar#})[#(into: inout Hasher) -> Void#]; name=hash(:) // MISSINGARG_INLINE-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: bop[#Bop#]; name=bop // MISSINGARG_INLINE-DAG: Decl[InstanceMethod]/CurrNominal: hash({#(self): Bop#})[#(into: inout Hasher) -> Void#]; name=hash(:) // MISSINGARG_INLINE-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: bix[#Bix#]; name=bix // MISSINGARG_INLINE-DAG: Decl[InstanceMethod]/CurrNominal: hash({#(self): Bix#})[#(into: inout Hasher) -> Void#]; name=hash(:) // MISSINGARG_INLINE-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: boy[#Boy#]; name=boy // MISSINGARG_INLINE-DAG: Decl[InstanceMethod]/CurrNominal: hash({#(self): Boy#})[#(into: inout Hasher) -> Void#]; name=hash(:) // MISSINGARG_INLINE-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: blu[#Blu#]; name=blu // MISSINGARG_INLINE-DAG: Decl[InstanceMethod]/CurrNominal: hash({#(self): Blu#})[#(into: inout Hasher) -> Void#]; name=hash(:) // MISSINGARG_INLINE-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: baz[#Baz#]; name=baz // MISSINGARG_INLINE-DAG: Decl[InstanceMethod]/CurrNominal: hash({#(self): Baz#})[#(into: inout Hasher) -> Void#]; name=hash(:) // MISSINGARG_INLINE: End completions // MISSINGARG_TRAILING: Begin completions, 10 items // MISSINGARG_TRAILING-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: foo[#Foo#]; name=foo // MISSINGARG_TRAILING-DAG: Decl[InstanceMethod]/CurrNominal: hash({#(self): Foo#})[#(into: inout Hasher) -> Void#]; name=hash(:) // MISSINGARG_TRAILING-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: bar[#Bar#]; name=bar // MISSINGARG_TRAILING-DAG: Decl[InstanceMethod]/CurrNominal: hash({#(self): Bar#})[#(into: inout Hasher) -> Void#]; name=hash(:) // MISSINGARG_TRAILING-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: bop[#Bop#]; name=bop // MISSINGARG_TRAILING-DAG: Decl[InstanceMethod]/CurrNominal: hash({#(self): Bop#})[#(into: inout Hasher) -> Void#]; name=hash(:) // MISSINGARG_TRAILING-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: bix[#Bix#]; name=bix // MISSINGARG_TRAILING-DAG: Decl[InstanceMethod]/CurrNominal: hash({#(self): Bix#})[#(into: inout Hasher) -> Void#]; name=hash(:) // MISSINGARG_TRAILING-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: boy[#Boy#]; name=boy // MISSINGARG_TRAILING-DAG: Decl[InstanceMethod]/CurrNominal: hash({#(self): Boy#})[#(into: inout Hasher) -> Void#]; name=hash(:) // MISSINGARG_TRAILING: End completions } protocol C { associatedtype Element func getCElem() -> Element } protocol D { associatedtype Item func getDElem() -> Item } struct CDStruct: C, D { func getDElem() -> A { return A() } func getCElem() -> B { return B() } } func genericReturn<T:C, U>(_ x: T) -> U where U == T.Element { return x.getCElem() } func genericReturn<T:D, U>(_ x: T) -> U where U == T.Item { return x.getDElem() } genericReturn(CDStruct()).#^GENERIC^# // GENERIC: Begin completions, 4 items // GENERIC-DAG: Keyword[self]/CurrNominal: self[#B#]{{; name=.+$}} // GENERIC-DAG: Decl[InstanceMethod]/CurrNominal: doBThings()[#Void#]{{; name=.+$}} // GENERIC-DAG: Keyword[self]/CurrNominal: self[#A#]{{; name=.+$}} // GENERIC-DAG: Decl[InstanceMethod]/CurrNominal: doAThings()[#A#]{{; name=.+$}} // GENERIC: End completions genericReturn().#^GENERIC_MISSINGARG?check=NORESULTS^# // NORESULTS-NOT: Begin completions struct Point { let x: Int let y: Int var magSquared: Int { return x*y } init(_ x: Int, _ y: Int) { self.x = x self.y = y } } // POINT_MEMBER: Begin completions, 4 items // POINT_MEMBER-DAG: Keyword[self]/CurrNominal: self[#Point#]; name=self // POINT_MEMBER-DAG: Decl[InstanceVar]/CurrNominal: x[#Int#]; name=x // POINT_MEMBER-DAG: Decl[InstanceVar]/CurrNominal: y[#Int#]; name=y // POINT_MEMBER-DAG: Decl[InstanceVar]/CurrNominal: magSquared[#Int#]; name=magSquared // POINT_MEMBER: End completions let _ = [Point(1, 4), Point(20, 2), Point(9, -4)] .filter { $0.magSquared > 4 } .min { $0.#^CLOSURE_MISSINGARG?check=POINT_MEMBER^# } protocol SomeProto {} func testing<T: Collection, U: SomeProto>(_ arg1: T, arg2: (T.Element) -> U) {} _ = testing([Point(4, 89)]) { arg in arg.#^CLOSURE_NORETURN?check=POINT_MEMBER^# } struct Thing { init(_ block: (Point) -> Void) {} enum ThingEnum { case first, second } func doStuff(_ x: ThingEnum, _ y: Int) -> Thing { return self } func takesRef(_ ref: () -> ()) -> Thing { return self } } @resultBuilder struct ThingBuilder { static func buildBlock(_ x: Thing...) -> [Thing] { x } } func CreateThings(@ThingBuilder makeThings: () -> [Thing]) {} // In single statement closure CreateThings { Thing { point in point.#^CLOSURE_FUNCBUILDER?check=POINT_MEMBER^# } Thing { _ in } } // In multi-statement closure CreateThings { Thing { point in print("hello") point.#^MULTICLOSURE_FUNCBUILDER?check=POINT_MEMBER^# } Thing { _ in } } // In multi-statement closure with unpropagated errors CreateThings { Thing { point in print("hello") point. // ErrorExpr point.#^MULTICLOSURE_FUNCBUILDER_ERROR?check=POINT_MEMBER^# } Thing { point in print("hello") point. // ErrorExpr } } // FIXME: No results in multi-statement closure with erroreous sibling result builder element CreateThings { Thing { point in print("hello") point.#^MULTICLOSURE_FUNCBUILDER_FIXME?check=NORESULTS^# } Thing. // ErrorExpr } struct TestFuncBodyBuilder { func someFunc() {} @ThingBuilder func foo() -> [Thing] { Thing() .doStuff(.#^FUNCBUILDER_FUNCBODY^#, 3) .takesRef(someFunc) } } // FUNCBUILDER_FUNCBODY: Begin completions, 3 items // FUNCBUILDER_FUNCBODY-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: first[#Thing.ThingEnum#]; // FUNCBUILDER_FUNCBODY-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: second[#Thing.ThingEnum#]; // FUNCBUILDER_FUNCBODY-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): Thing.ThingEnum#})[#(into: inout Hasher) -> Void#]; // FUNCBUILDER_FUNCBODY: End completions func takesClosureOfPoint(_: (Point)->()) {} func overloadedWithDefaulted(_: ()->()) {} func overloadedWithDefaulted(_: ()->(), _ defaulted: Int = 10) {} takesClosureOfPoint { p in overloadedWithDefaulted { if p.#^REGULAR_MULTICLOSURE_APPLIED?check=POINT_MEMBER^# {} } } enum Enum123 { case enumElem } struct Struct123: Equatable { var structMem = Enum123.enumElem } func testBestSolutionFilter() { let a = Struct123(); let b = [Struct123]().first(where: { $0 == a && 1 + 90 * 5 / 8 == 45 * -10 })?.structMem != .#^BEST_SOLUTION_FILTER?xfail=rdar73282163^# let c = min(10.3, 10 / 10.4) < 6 / 7 ? true : Optional(a)?.structMem != .#^BEST_SOLUTION_FILTER2?check=BEST_SOLUTION_FILTER;xfail=rdar73282163^# } // BEST_SOLUTION_FILTER: Begin completions // BEST_SOLUTION_FILTER-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Convertible]: enumElem[#Enum123#]{{; name=.+$}} // BEST_SOLUTION_FILTER-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): Enum123#})[#(into: inout Hasher) -> Void#]{{; name=.+$}} // BEST_SOLUTION_FILTER-DAG: Keyword[nil]/None/Erase[1]/TypeRelation[Identical]: nil[#Enum123?#]{{; name=.+$}} // BEST_SOLUTION_FILTER-DAG: Decl[EnumElement]/CurrNominal/IsSystem/TypeRelation[Identical]: none[#Optional<Enum123>#]{{; name=.+$}} // BEST_SOLUTION_FILTER-DAG: Decl[EnumElement]/CurrNominal/IsSystem/TypeRelation[Identical]: some({#Enum123#})[#Optional<Enum123>#]{{; name=.+$}} // BEST_SOLUTION_FILTER: End completions func testBestSolutionGeneric() { struct Test1 {} func genAndInt(_ x: Int) -> Int { return 1 } func genAndInt<T>(_ x: T) -> Test1 { return Test1() } genAndInt(2).#^BEST_SOLUTION_FILTER_GEN?xfail=rdar73282163^# } // BEST_SOLUTION_FILTER_GEN: Begin completions // BEST_SOLUTION_FILTER_GEN-DAG: Keyword[self]/CurrNominal: self[#Int#]; name=self // BEST_SOLUTION_FILTER_GEN-DAG: Keyword[self]/CurrNominal: self[#Test1#]; name=self // BEST_SOLUTION_FILTER_GEN: End completions func testAmbiguousArgs() { struct A { func someFunc(a: Int, b: Int) -> A { return self } func variadic(y: Int, x: Int...) } struct B { func someFunc(a: Int, c: String = "", d: String = "") {} } func overloaded() -> A { return A() } func overloaded() -> B { return B() } let localInt = 10 let localString = "Hello" overloaded().someFunc(a: 2, #^ARG_NO_LABEL^#) // ARG_NO_LABEL: Begin completions, 3 items // ARG_NO_LABEL-DAG: Pattern/Local/Flair[ArgLabels]: {#b: Int#}[#Int#]; name=b: // ARG_NO_LABEL-DAG: Pattern/Local/Flair[ArgLabels]: {#c: String#}[#String#]; name=c: // ARG_NO_LABEL-DAG: Pattern/Local/Flair[ArgLabels]: {#d: String#}[#String#]; name=d: // ARG_NO_LABEL: End completions overloaded().someFunc(a: 2, b: #^ARG_LABEL^#) // ARG_LABEL: Begin completions // ARG_LABEL-DAG: Decl[LocalVar]/Local: localString[#String#]; name=localString // ARG_LABEL-DAG: Decl[LocalVar]/Local/TypeRelation[Identical]: localInt[#Int#]; name=localInt // ARG_LABEL: End completions overloaded().someFunc(a: 2, c: "Foo", #^ARG_NO_LABEL2^#) // ARG_NO_LABEL2: Begin completions, 1 item // ARG_NO_LABEL2: Pattern/Local/Flair[ArgLabels]: {#d: String#}[#String#]; name=d: // ARG_NO_LABEL2: End completions overloaded().someFunc(a: 2, wrongLabel: "Foo", #^ARG_NO_LABEL_PREV_WRONG^#) // ARG_NO_LABEL_PREV_WRONG: Begin completions, 3 items // ARG_NO_LABEL_PREV_WRONG-DAG: Pattern/Local/Flair[ArgLabels]: {#b: Int#}[#Int#]; name=b: // ARG_NO_LABEL_PREV_WRONG-DAG: Pattern/Local/Flair[ArgLabels]: {#c: String#}[#String#]; name=c: // ARG_NO_LABEL_PREV_WRONG-DAG: Pattern/Local/Flair[ArgLabels]: {#d: String#}[#String#]; name=d: // ARG_NO_LABEL_PREV_WRONG: End completions overloaded().someFunc(a: 2, d: "Foo", #^ARG_NO_LABEL_OUT_OF_ORDER^#) // ARG_NO_LABEL_OUT_OF_ORDER: Begin completions // ARG_NO_LABEL_OUT_OF_ORDER-NOT: name=d: String // ARG_NO_LABEL_OUT_OF_ORDER: Pattern/Local/Flair[ArgLabels]: {#c: String#}[#String#]; name=c: // ARG_NO_LABEL_OUT_OF_ORDER-NOT: name=d: String // ARG_NO_LABEL_OUT_OF_ORDER: End completions func noArgs() {} noArgs(12, #^ARG_EXTRANEOUS^#) // ARG_EXTRANEOUS: Begin completions // ARG_EXTRANEOUS-DAG: localInt // ARG_EXTRANEOUS-DAG: localString // ARG_EXTRANEOUS: End completions overloaded().someFunc(a: 2, #^LATER_ARGS^#, d: "foo") // LATER_ARGS: Begin completions, 2 items // LATER_ARGS-DAG: Pattern/Local/Flair[ArgLabels]: {#b: Int#}[#Int#]; name=b: // LATER_ARGS-DAG: Pattern/Local/Flair[ArgLabels]: {#c: String#}[#String#]; name=c: // LATER_ARGS: End completions overloaded().someFunc(a: 2, #^LATER_ARGS_WRONG^#, k: 4.5) // LATER_ARGS_WRONG: Begin completions, 3 items // LATER_ARGS_WRONG-DAG: Pattern/Local/Flair[ArgLabels]: {#b: Int#}[#Int#]; name=b: // LATER_ARGS_WRONG-DAG: Pattern/Local/Flair[ArgLabels]: {#c: String#}[#String#]; name=c: // LATER_ARGS_WRONG-DAG: Pattern/Local/Flair[ArgLabels]: {#d: String#}[#String#]; name=d: // LATER_ARGS_WRONG-DAG: End completions overloaded().variadic(y: 2, #^INITIAL_VARARG^#, 4) // INITIAL_VARARG: Begin completions, 1 item // INITIAL_VARARG: Pattern/Local/Flair[ArgLabels]: {#x: Int...#}[#Int#]; name=x: // INITIAL VARARG: End completions overloaded().variadic(y: 2, x: 2, #^NONINITIAL_VARARG^#) // NONINITIAL_VARARG: Begin completions // NONINITIAL_VARARG-NOT: name=x: // NONINITIAL_VARARG: Decl[LocalVar]/Local/TypeRelation[Identical]: localInt[#Int#]; name=localInt // NONINITIAL_VARARG-NOT: name=x: // NONINITIAL_VARARG: End completions }
a8a022965efd936d1f0cd2a2799745c6
44.52677
177
0.676062
false
true
false
false
rymir/ConfidoIOS
refs/heads/master
ConfidoIOSTests/KeyPairTests.swift
mit
1
// // KeyPairTests.swift // ExpendSecurity // // Created by Rudolph van Graan on 19/08/2015. // import UIKit import XCTest import ConfidoIOS class KeyPairTests: BaseTests { func testGenerateNamedKeyPair() { do { clearKeychainItems(.Key) var items = try Keychain.keyChainItems(SecurityClass.Key) XCTAssertEqual(items.count,0) let keypairDescriptor = PermanentKeychainKeyPairDescriptor(accessible: Accessible.WhenUnlockedThisDeviceOnly, privateKeyAccessControl: nil, publicKeyAccessControl: nil, keyType: .RSA, keySize: 1024, keyLabel: "AAA", keyAppTag: "BBB", keyAppLabel: "CCC") var keyPair : KeychainKeyPair? keyPair = try KeychainKeyPair.generateKeyPair(keypairDescriptor) XCTAssertNotNil(keyPair) items = try Keychain.keyChainItems(.Key) XCTAssertEqual(items.count,2) let keyDescriptor = KeychainKeyDescriptor(keyLabel: "AAA") var keyItem: KeychainItem? keyItem = try Keychain.fetchItem(matchingDescriptor: keyDescriptor) XCTAssertNotNil(keyItem) XCTAssertEqual(keyPair!.privateKey.keyType, KeyType.RSA) XCTAssertEqual(keyPair!.publicKey.keyType, KeyType.RSA) XCTAssertEqual(keyPair!.privateKey.keySize, 1024) XCTAssertEqual(keyPair!.publicKey.keySize, 1024) XCTAssertNotNil(keyPair!.privateKey.itemLabel) XCTAssertEqual(keyPair!.privateKey.itemLabel!, "AAA") XCTAssertNotNil(keyPair!.privateKey.keyAppTag) XCTAssertEqual(keyPair!.privateKey.keyAppTag!, "BBB") XCTAssertNotNil(keyPair!.privateKey.keyAppLabelString) XCTAssertEqual(keyPair!.privateKey.keyAppLabelString!, "CCC") XCTAssertEqual(keyPair!.publicKey.itemAccessGroup, "") XCTAssertEqual(keyPair!.publicKey.itemAccessible, Accessible.WhenUnlockedThisDeviceOnly) let publicKeyData = keyPair!.publicKey.keyData XCTAssertNotNil(publicKeyData) XCTAssertEqual(publicKeyData!.length,140) } catch let error as NSError { XCTFail("Unexpected Exception \(error)") } } func testGenerateNamedKeyPairNoKeyLabel() { do { clearKeychainItems(.Key) var items = try Keychain.keyChainItems(SecurityClass.Key) XCTAssertEqual(items.count,0) let keypairDescriptor = PermanentKeychainKeyPairDescriptor( accessible: Accessible.AlwaysThisDeviceOnly, privateKeyAccessControl: nil, publicKeyAccessControl: nil, keyType: .RSA, keySize: 1024, keyLabel: "AAA") var keyPair : KeychainKeyPair? keyPair = try KeychainKeyPair.generateKeyPair(keypairDescriptor) XCTAssertNotNil(keyPair) items = try Keychain.keyChainItems(.Key) XCTAssertEqual(items.count,2) let keyDescriptor = KeychainKeyDescriptor(keyLabel: "AAA") var keyItem: KeychainItem? keyItem = try Keychain.fetchItem(matchingDescriptor: keyDescriptor) XCTAssertNotNil(keyItem) XCTAssertEqual(keyPair!.privateKey.keyType, KeyType.RSA) XCTAssertEqual(keyPair!.publicKey.keyType, KeyType.RSA) XCTAssertEqual(keyPair!.privateKey.keySize, 1024) XCTAssertEqual(keyPair!.publicKey.keySize, 1024) XCTAssertNotNil(keyPair!.privateKey.itemLabel) XCTAssertEqual(keyPair!.privateKey.itemLabel!, "AAA") XCTAssertNotNil(keyPair!.privateKey.keyAppTag) XCTAssertEqual(keyPair!.privateKey.keyAppTag!, "") XCTAssertNotNil(keyPair!.privateKey.keyAppLabelData) //The keyAppLabel is equal to the hash of the public key by default let publicKeyData = keyPair!.publicKey.keyData XCTAssertNotNil(publicKeyData) XCTAssertEqual(publicKeyData!.length,140) } catch let error as NSError { XCTFail("Unexpected Exception \(error)") } } func testGenerateUnnamedKeyPair() { do { clearKeychainItems(.Key) var items = try Keychain.keyChainItems(SecurityClass.Key) XCTAssertEqual(items.count,0) let keypairDescriptor = TemporaryKeychainKeyPairDescriptor(keyType: .RSA, keySize: 1024) let keyPair = try KeychainKeyPair.generateKeyPair(keypairDescriptor) XCTAssertNotNil(keyPair) items = try Keychain.keyChainItems(.Key) // Temporary keys are not stored in the keychain XCTAssertEqual(items.count,0) XCTAssertEqual(keyPair.privateKey.keySize, 1024) XCTAssertEqual(keyPair.publicKey.keySize, 1024) // There is no way to extract the data of a key for non-permanent keys let publicKeyData = keyPair.publicKey.keyData XCTAssertNil(publicKeyData) } catch let error as NSError { XCTFail("Unexpected Exception \(error)") } } func testDuplicateKeyPairMatching() { do { clearKeychainItems(.Key) var items = try Keychain.keyChainItems(SecurityClass.Key) XCTAssertEqual(items.count,0) var keypairDescriptor = PermanentKeychainKeyPairDescriptor( accessible: Accessible.AlwaysThisDeviceOnly, privateKeyAccessControl: nil, publicKeyAccessControl: nil, keyType: .RSA, keySize: 1024, keyLabel: "A1", keyAppTag: "BBB", keyAppLabel: "CCC") var keyPair : KeychainKeyPair? = try KeychainKeyPair.generateKeyPair(keypairDescriptor) XCTAssertNotNil(keyPair) items = try Keychain.keyChainItems(.Key) XCTAssertEqual(items.count,2) // Test that labels make the keypair unique do { keyPair = try KeychainKeyPair.generateKeyPair(keypairDescriptor) XCTFail("Expected DuplicateItemError") } catch KeychainStatus.DuplicateItemError { // keySize, keyLabel, keyAppTag, keyAppLabel all the same --> DuplicateItemError } // different keySize keypairDescriptor = PermanentKeychainKeyPairDescriptor( accessible: Accessible.AlwaysThisDeviceOnly, privateKeyAccessControl: nil, publicKeyAccessControl: nil, keyType: .RSA, keySize: 2048, keyLabel: "A1", keyAppTag: "BBB", keyAppLabel: "CCC") keyPair = try KeychainKeyPair.generateKeyPair(keypairDescriptor) XCTAssertNotNil(keyPair) } catch let error { XCTFail("Unexpected Exception \(error)") } } }
ae4aed6af25a2671f203ebb421b68dea
35.222222
121
0.642857
false
false
false
false
kumaw/AMRequestAPI
refs/heads/master
AMRequestAPI/Classes/AMUploadFile.swift
mit
1
// // UploadFile.swift // MiaoCai // // Created by 王 on 2016/12/13. // Copyright © 2016年 iMac. All rights reserved. // import Foundation public class AMUploadFile: NSObject { var data:Data = Data() var mimeType:String = "" var name:String = "" public init(withjpg data:Data,name:String){ self.data = data self.name = name self.mimeType = "image/jpeg" } }
4d8f8109751a5110ab7ad9422dd30a40
20.263158
48
0.616337
false
false
false
false
tejasranade/KinveyHealth
refs/heads/master
SportShop/IDCard.swift
apache-2.0
1
// // IDCard.swift // KinveyHealth // // Created by Tejas on 5/2/17. // Copyright © 2017 Kinvey. All rights reserved. // import Foundation import Kinvey import ObjectMapper import Realm class IDCard: Entity { @objc dynamic var plan: String? @objc dynamic var provider: String? @objc dynamic var groupName: String? @objc dynamic var groupNo: String? @objc dynamic var subscriberName: String? @objc dynamic var subscriberNo: String? @objc dynamic var issueDate: String? @objc dynamic var officeCopay: String? @objc dynamic var specialistCopay: String? @objc dynamic var deductibleTotal: String? @objc dynamic var deductibleRemain: String? @objc dynamic var deductibleFamilyTotal: String? @objc dynamic var deductibleFamilyRemain: String? var individualUsed: Float { if let total = deductibleTotal, let remain = deductibleRemain, let iTotal = Float(total), let iRemain = Float(remain) { return iTotal - iRemain } return 0 } var individualPercentUsed: Float { if let total = deductibleTotal, let remain = deductibleRemain, let fTotal = Float(total), let fRemain = Float(remain){ return (fTotal - fRemain)/fTotal } return 0 } var familyUsed: Float { if let total = deductibleFamilyTotal, let remain = deductibleFamilyRemain, let iTotal = Float(total), let iRemain = Float(remain) { return iTotal - iRemain } return 0 } var familyPercentUsed: Float { if let total = deductibleFamilyTotal, let remain = deductibleFamilyRemain, let fTotal = Float(total), let fRemain = Float(remain){ return (fTotal - fRemain)/fTotal } return 0 } override class func collectionName() -> String { //return the name of the backend collection corresponding to this entity return "idcards" } //Map properties in your backend collection to the members of this entity override func propertyMapping(_ map: Map) { //This maps the "_id", "_kmd" and "_acl" properties super.propertyMapping(map) //Each property in your entity should be mapped using the following scheme: //<member variable> <- ("<backend property>", map["<backend property>"]) plan <- map["plan"] provider <- map["provider"] groupName <- map["groupname"] groupNo <- map["groupnum"] subscriberName <- map["subscriber"] subscriberNo <- map["subscribernum"] issueDate <- map["issuedate"] officeCopay <- map["officecopay"] specialistCopay <- map["speccopay"] deductibleTotal <- map["deductible_individual_total"] deductibleRemain <- map["deductible_individual_remain"] deductibleFamilyTotal <- map["deductible_family_total"] deductibleFamilyRemain <- map["deductible_family_remain"] } }
2da62b4e45b1266cca27bac72c72d9c0
29.585859
83
0.63177
false
false
false
false
LoveAlwaysYoung/EnjoyUniversity
refs/heads/master
EnjoyUniversity/EnjoyUniversity/Classes/View/Profile/Search/EUSearchCommunityController.swift
mit
1
// // EUSearchCommunityController.swift // EnjoyUniversity // // Created by lip on 17/4/24. // Copyright © 2017年 lip. All rights reserved. // import UIKit class EUSearchCommunityController: EUBaseViewController,UISearchBarDelegate { lazy var listviewmodel = CommunityListViewModel() var keyword:String? var isPullUp:Bool = false var SEARCHCOMMUNITYCELL = "SEARCHCOMMUNITYCELL" // 底部刷新指示器 let indicator = UIActivityIndicatorView(activityIndicatorStyle: .white) // 底部说明文本 let indicatorlabel = UILabel() override func viewDidLoad() { super.viewDidLoad() tableview.contentInset = UIEdgeInsetsMake(64, 0, 0, 0) tableview.tableFooterView = UIView() tableview.register(EUCommunityCollectionCell.self, forCellReuseIdentifier: SEARCHCOMMUNITYCELL) tableview.keyboardDismissMode = .onDrag let searchbar = UISearchBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width - 60, height: 30)) searchbar.delegate = self searchbar.searchBarStyle = .minimal searchbar.barTintColor = UIColor.white searchbar.tintColor = UIColor.white let searchBarTextField = searchbar.subviews.first?.subviews.last as? UITextField searchBarTextField?.textColor = UIColor.white if keyword == nil{ searchBarTextField?.attributedPlaceholder = NSAttributedString(string: "搜索大学社团", attributes: [NSForegroundColorAttributeName:UIColor.white]) searchbar.becomeFirstResponder() }else{ searchbar.text = keyword } let titleview = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width - 60, height: 30)) titleview.addSubview(searchbar) navitem.titleView = titleview } override func loadData() { guard let keyword = keyword else { return } refreshControl?.beginRefreshing() listviewmodel.loadSearchedCommunity(keyword: keyword, isPullUp: isPullUp) { (isSuccess, hadData) in self.refreshControl?.endRefreshing() if !isSuccess{ SwiftyProgressHUD.showFaildHUD(text: "网络异常", duration: 1) return } if !hadData{ // 空空如也 } self.tableview.reloadData() } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listviewmodel.searchList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = (tableView.dequeueReusableCell(withIdentifier: SEARCHCOMMUNITYCELL) as? EUCommunityCollectionCell) ?? EUCommunityCollectionCell() cell.viewmodel = listviewmodel.searchList[indexPath.row] return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { guard let keyword = searchBar.text else { SwiftyProgressHUD.showBigFaildHUD(text: "请输入搜索内容", duration: 1) return } self.keyword = keyword refreshControl?.beginRefreshing() listviewmodel.loadSearchedCommunity(keyword: keyword, isPullUp: false) { (isSuccess, hasData) in self.refreshControl?.endRefreshing() if !isSuccess{ SwiftyProgressHUD.showFaildHUD(text: "网络异常", duration: 1) return } if !hasData{ // 显示空空如也 } self.tableview.reloadData() } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { super.tableView(tableView, didSelectRowAt: indexPath) let vc = EUCommunityInfoViewController() vc.viewmodel = listviewmodel.searchList[indexPath.row] navigationController?.pushViewController(vc, animated: true) } // 封装上拉刷新逻辑 func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let section = tableView.numberOfSections - 1 let maxrow = tableView.numberOfRows(inSection: section) let currentrow = indexPath.row // 数据条数非常少时,无需使用上拉加载更多 if maxrow < EUREQUESTCOUNT { indicator.isHidden = true indicatorlabel.isHidden = false return } if (currentrow == maxrow - 1) && !isPullUp && listviewmodel.searchList.count > 0 { isPullUp = true indicator.startAnimating() loadData() } } }
5e8e6b41976537f4c92ed5c02a38796d
32.569444
152
0.627638
false
false
false
false
zhoushumin11/DouYuZB
refs/heads/master
DYZB/DYZB/Classes/Tools/Extension/UIBarButtonItem-Extension.swift
mit
1
// // UIBarButtonItem-Extension.swift // DYZB // // Created by 周书敏 on 2017/3/25. // Copyright © 2017年 周书敏. All rights reserved. // import UIKit extension UIBarButtonItem{ // MARK: 类方法方式 生成item /* class func createItem(imageName: String, highImageName: String, size: CGSize) -> UIBarButtonItem { let btn = UIButton() btn .setImage(UIImage(named: imageName), for: .normal) btn .setImage(UIImage(named: highImageName), for: .highlighted) btn.frame = CGRect(origin:CGPoint.zero , size:size) return UIBarButtonItem(customView:btn) } */ // MARK: 构造函数方式 生成item //便利构造函数 : 1. convenience开头 2. 在构造函数中必须明确调用一个设计的构造函数(self) convenience init(imageName: String, highImageName: String = "", size: CGSize = CGSize.zero) { let btn = UIButton() btn .setImage(UIImage(named: imageName), for: .normal) if highImageName != "" { btn .setImage(UIImage(named: highImageName), for: .highlighted) } if size == CGSize.zero { btn.sizeToFit() }else{ btn.frame = CGRect(origin:CGPoint.zero , size:size) } self.init(customView : btn) } }
fb0b61d6b00643cda910a7e1139e3270
24.68
104
0.573988
false
false
false
false
cubixlabs/SocialGIST
refs/heads/master
Pods/GISTFramework/GISTFramework/Classes/BaseClasses/BaseUITableViewCell.swift
gpl-3.0
1
// // BaseTableViewCell.swift // GISTFramework // // Created by Shoaib Abdul on 14/06/2016. // Copyright © 2016 Social Cubix. All rights reserved. // import UIKit /// BaseUITableViewCell is a subclass of UITableViewCell and implements BaseView. It has some extra proporties and support for SyncEngine. open class BaseUITableViewCell: UITableViewCell, BaseView { //MARK: - Properties /// Flag for whether to resize the values for iPad. @IBInspectable open var sizeForIPad:Bool = GIST_CONFIG.sizeForIPad; /// Background color key from SyncEngine. @IBInspectable open var bgColorStyle:String? = nil { didSet { guard (self.bgColorStyle != oldValue) else { return; } self.backgroundColor = SyncedColors.color(forKey: bgColorStyle); } } // Calculated seperator frame Rect - Overridable open var seperatorFrame:CGRect { get { return CGRect(x: 0, y: (seperatorOnTop ? 0:self.frame.size.height - 0.5), width: self.frame.size.width, height: 0.5); } } //P.E. /// Flag for showing seperator @IBInspectable open var hasSeperator:Bool { get { return !self.seperatorView.isHidden; } set { self.seperatorView.isHidden = !newValue; } } //P.E. /// Seperator Color key from SyncEngine. @IBInspectable open var seperatorColorStyle:String? = nil { didSet { guard (self.seperatorColorStyle != oldValue) else { return; } self.seperatorView.backgroundColor = SyncedColors.color(forKey: seperatorColorStyle); } } //P.E. /// Flag for showing seperator on the top. @IBInspectable open var seperatorOnTop:Bool = false { didSet { self.seperatorView.frame = self.seperatorFrame; } } /// Font name key from Sync Engine. @IBInspectable open var fontName:String? = GIST_CONFIG.fontName { didSet { guard (self.fontName != oldValue) else { return; } self.textLabel?.font = UIFont.font(self.fontName, fontStyle: self.fontStyle, sizedForIPad: sizeForIPad); self.detailTextLabel?.font = UIFont.font(self.fontName, fontStyle: self.fontDetailStyle, sizedForIPad: sizeForIPad); } } /// Font size/ style key from Sync Engine. @IBInspectable open var fontStyle:String? = GIST_CONFIG.fontStyle { didSet { guard (self.fontStyle != oldValue) else { return; } self.textLabel?.font = UIFont.font(self.fontName, fontStyle: self.fontStyle, sizedForIPad: sizeForIPad); } } /// Detail text font name key from SyncEngine. @IBInspectable open var fontDetailStyle:String? = GIST_CONFIG.fontStyle { didSet { guard (self.fontDetailStyle != oldValue) else { return; } self.detailTextLabel?.font = UIFont.font(self.fontName, fontStyle: self.fontDetailStyle, sizedForIPad: sizeForIPad); } } /// Font Color key from SyncEngine. @IBInspectable open var fontColor:String? = nil { didSet { guard (self.fontColor != oldValue) else { return; } self.textLabel?.textColor = UIColor.color(forKey: fontColor); } } /// Detail text font color key from SyncEngine. @IBInspectable open var detailColor:String? = nil { didSet { guard (self.detailColor != oldValue) else { return; } self.detailTextLabel?.textColor = UIColor.color(forKey: detailColor); } } private var _data:Any? /// Holds Table View Cell Data. open var data:Any? { get { return _data; } } //P.E. //Lazy instance for table view seperator view. open lazy var seperatorView:UIView = { let sView = UIView(frame: self.seperatorFrame); sView.isHidden = true; sView.backgroundColor = UIColor.lightGray; self.addSubview(sView); return sView; }() class var cellID : String { return "\(self)ID" } //P.E. //MARK: - Constructor /// Convenience constructor with cell reuseIdentifier - by default style = UITableViewCellStyle.default. /// /// - Parameter reuseIdentifier: Reuse identifier public convenience init(reuseIdentifier: String?) { self.init(style: UITableViewCellStyle.default, reuseIdentifier: reuseIdentifier); } //F.E. /// Overridden constructor to setup/ initialize components. /// /// - Parameters: /// - style: Table View Cell Style /// - reuseIdentifier: Reuse identifier override public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier); self.selectionStyle = UITableViewCellSelectionStyle.none; self.commonInit(); } //F.E. /// Required constructor implemented. required public init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder); } //F.E. //MARK: - Overridden Methods /// Overridden method to setup/ initialize components. override open func awakeFromNib() { super.awakeFromNib(); self.commonInit(); } //F.E. /// Overridden method to receive selected states of table view cell /// /// - Parameters: /// - selected: Flag for Selected State /// - animated: Flag for Animation override open func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated); } //F.E. /// Recursive update of layout and content from Sync Engine. override func updateSyncedData() { super.updateSyncedData(); self.contentView.updateSyncedData(); } //F.E. /// Overridden methed to update layout. override open func layoutSubviews() { super.layoutSubviews(); self.seperatorView.frame = self.seperatorFrame; } //F.E. //MARK: - Methods /// A common initializer to setup/initialize sub components. private func commonInit() { self.selectionStyle = UITableViewCellSelectionStyle.none; self.contentView.backgroundColor = UIColor.clear; self.textLabel?.font = UIFont.font(self.fontName, fontStyle: self.fontStyle, sizedForIPad: sizeForIPad); self.detailTextLabel?.font = UIFont.font(self.fontName, fontStyle: self.fontDetailStyle, sizedForIPad: sizeForIPad); } //F.E. /// Updates layout and contents from SyncEngine. this is a protocol method BaseView that is called when the view is refreshed. func updateView() { if let bgCStyle = self.bgColorStyle { self.bgColorStyle = bgCStyle; } if let sepColorStyle = self.seperatorColorStyle { self.seperatorColorStyle = sepColorStyle; } if let fName = self.fontName { self.fontName = fName; } if let fColor = self.fontColor { self.fontColor = fColor; } if let dColor = self.detailColor { self.detailColor = dColor; } } //F.E. /// This method should be called in cellForRowAt:indexPath. it also must be overriden in all sub classes of BaseUITableViewCell to update the table view cell's content. /// /// - Parameter data: Cell Data open func updateData(_ data:Any?) { _data = data; self.updateSyncedData(); } //F.E. } //CLS END
a8da202da276007a2d1ac36caa3434f3
30.74502
172
0.591365
false
false
false
false
artman/Geometry
refs/heads/master
Geometry/UIView+Geometry.swift
mit
1
// // UIView+Geometry.swift // Geometry // // Created by Tuomas Artman on 7.9.2014. // Copyright (c) 2014 Tuomas Artman. All rights reserved. // import CoreGraphics import Foundation import UIKit /// Extends CGRect with helper properties for positioning and setting dimensions extension CGRect: ExpressibleByStringLiteral { /// The top coordinate of the rect. public var top: CGFloat { get { return origin.y } set(value) { origin.y = value } } // The left-side coordinate of the rect. public var left: CGFloat { get { return origin.x } set(value) { origin.x = value } } // The bottom coordinate of the rect. Setting this will change origin.y of the rect according to // the height of the rect. public var bottom: CGFloat { get { return origin.y + size.height } set(value) { origin.y = value - size.height } } // The right-side coordinate of the rect. Setting this will change origin.x of the rect according to // the width of the rect. public var right: CGFloat { get { return origin.x + size.width } set(value) { origin.x = value - size.width } } // The center x coordinate of the rect. public var centerX: CGFloat { get { return origin.x + size.width / 2 } set (value) { origin.x = value - size.width / 2 } } // The center y coordinate of the rect. public var centerY: CGFloat { get { return origin.y + size.height / 2 } set (value) { origin.y = value - size.height / 2 } } // The center of the rect. public var center: CGPoint { get { return CGPoint(x: centerX, y: centerY) } set (value) { centerX = value.x centerY = value.y } } public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType public init(stringLiteral value: StringLiteralType) { self.init() let rect: CGRect if value[value.startIndex] != "{" { let comp = value.components(separatedBy: ",") if comp.count == 4 { rect = CGRectFromString("{{\(comp[0]),\(comp[1])}, {\(comp[2]), \(comp[3])}}") } else { rect = CGRect.zero } } else { rect = CGRectFromString(value) } self.size = rect.size; self.origin = rect.origin; } public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { self.init(stringLiteral: value) } public typealias UnicodeScalarLiteralType = StringLiteralType public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { self.init(stringLiteral: value) } } extension CGPoint: ExpressibleByStringLiteral { public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType public init(stringLiteral value: StringLiteralType) { self.init() let point:CGPoint; if value[value.startIndex] != "{" { point = CGPointFromString("{\(value)}") } else { point = CGPointFromString(value) } self.x = point.x; self.y = point.y; } public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { self.init(stringLiteral: value) } public typealias UnicodeScalarLiteralType = StringLiteralType public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { self.init(stringLiteral: value) } } extension UIView { /// The top coordinate of the UIView. public var top: CGFloat { get { return frame.top } set(value) { var frame = self.frame frame.top = value self.frame = frame } } /// The left coordinate of the UIView. public var left: CGFloat { get { return frame.left } set(value) { var frame = self.frame frame.left = value self.frame = frame } } /// The bottom coordinate of the UIView. public var bottom: CGFloat { get { return frame.bottom } set(value) { var frame = self.frame frame.bottom = value self.frame = frame } } /// The right coordinate of the UIView. public var right: CGFloat { get { return frame.right } set(value) { var frame = self.frame frame.right = value self.frame = frame } } // The width of the UIView. public var width: CGFloat { get { return frame.width } set(value) { var frame = self.frame frame.size.width = value self.frame = frame } } // The height of the UIView. public var height: CGFloat { get { return frame.height } set(value) { var frame = self.frame frame.size.height = value self.frame = frame } } /// The horizontal center coordinate of the UIView. public var centerX: CGFloat { get { return frame.centerX } set(value) { var frame = self.frame frame.centerX = value self.frame = frame } } /// The vertical center coordinate of the UIView. public var centerY: CGFloat { get { return frame.centerY } set(value) { var frame = self.frame frame.centerY = value self.frame = frame } } }
ee57154bbd95759eedb7927985f3cb09
23.419355
104
0.527081
false
false
false
false
tripleCC/GanHuoCode
refs/heads/master
GanHuo/Util/TPCJSPatchManager.swift
mit
1
// // TPCJSPatchManager.swift // JSPathManager // // Created by tripleCC on 16/4/21. // Copyright © 2016年 tripleCC. All rights reserved. // import UIKit import JSPatch import Alamofire class TPCJSPatchManager: NSObject { struct Static { static let TPCJSPatchManagerAllowMaxCrashTime = 1 static let TPCJSPatchManagerJSVersoinKey = "TPCJSPatchManagerJSVersoinKey" static let TPCJSPatchManagerFetchDateKey = "TPCJSPatchManagerFetchDateKey" static let TPCJSPatchManagerEvaluateJSFailTimeKey = "TPCJSPatchManagerEvaluateJSFailTimeKey" static let TPCJSPatchFileName = "TPCJSPatchHotfix" static let TPCJSPatchFileDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! } private var jsVersion: String { get { return NSUserDefaults.standardUserDefaults().objectForKey(Static.TPCJSPatchManagerJSVersoinKey) as? String ?? "0" } set { NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: Static.TPCJSPatchManagerJSVersoinKey) } } private var evaluateJSFailTime: Int { get { return NSUserDefaults.standardUserDefaults().objectForKey(Static.TPCJSPatchManagerEvaluateJSFailTimeKey) as? Int ?? 0 } set { NSUserDefaults.standardUserDefaults().setInteger(newValue, forKey: Static.TPCJSPatchManagerEvaluateJSFailTimeKey) } } private var fetchDate: NSDate? { get { return NSUserDefaults.standardUserDefaults().objectForKey(Static.TPCJSPatchManagerFetchDateKey) as? NSDate } set { NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: Static.TPCJSPatchManagerFetchDateKey) } } private var jsScriptPath: String { return Static.TPCJSPatchFileDirectory + "/" + Static.TPCJSPatchFileName + ".js" } static let shareManager = TPCJSPatchManager() func start() { guard evaluateJSFailTime < Static.TPCJSPatchManagerAllowMaxCrashTime else { return } startWithJSName(Static.TPCJSPatchFileName) } private func recordFailTimeWithAction(action: (() -> Void)) { objc_sync_enter(self) evaluateJSFailTime += 1 action() evaluateJSFailTime -= 1 objc_sync_exit(self) } private func startWithJSName(name: String) { do { let jsScript = try String(contentsOfFile: jsScriptPath) JPEngine.startEngine() recordFailTimeWithAction { JPEngine.evaluateScript(jsScript) } } catch { print(error) } } func handleJSPatchStatusWithURLString(URLString: String, duration: NSTimeInterval) { let fetchStatusCompletion = { (version: String, jsPath: String) in self.fetchDate = NSDate() debugPrint(version, self.jsVersion) if Float(version) > Float(self.jsVersion) { TPCNetworkUtil.shareInstance.loadJSPatchFileWithURLString(jsPath, completion: { (jsScript) in self.evaluateJSFailTime = 0 self.recordFailTimeWithAction { JPEngine.evaluateScript(jsScript) } do { try jsScript.writeToFile(self.jsScriptPath, atomically: true, encoding: NSUTF8StringEncoding) self.jsVersion = version } catch let error { print(error) } }) } } func fetchJSPatchStatus() { TPCNetworkUtil.shareInstance.loadJSPatchStatusWithURLString(URLString, completion: fetchStatusCompletion) } if let fetchDate = fetchDate { if NSDate().timeIntervalSinceDate(fetchDate) > duration { fetchJSPatchStatus() } } else { fetchJSPatchStatus() } } }
25e88c31340b72af70691f89d100c909
34.80531
130
0.625803
false
false
false
false
HarukaMa/iina
refs/heads/master
iina/OpenURLAccessoryViewController.swift
gpl-3.0
1
// // OpenURLAccessoryViewController.swift // iina // // Created by lhc on 26/3/2017. // Copyright © 2017 lhc. All rights reserved. // import Cocoa class OpenURLAccessoryViewController: NSViewController { @IBOutlet weak var urlField: ShortcutAvailableTextField! @IBOutlet weak var safariLinkBtn: NSButton! @IBOutlet weak var chromeLinkBtn: NSButton! @IBOutlet weak var usernameField: NSTextField! @IBOutlet weak var passwordField: NSSecureTextField! private let safariExtensionLink = "https://github.com/lhc70000/iina/releases/download/v0.0.5/Open_In_IINA.safariextz" private let chromeExtensionLink = "https://chrome.google.com/webstore/detail/open-in-iina/pdnojahnhpgmdhjdhgphgdcecehkbhfo" var url: URL? { get { let username = usernameField.stringValue let password = passwordField.stringValue guard var urlValue = urlField.stringValue.addingPercentEncoding(withAllowedCharacters: .urlAllowed) else { return nil } if URL(string: urlValue)?.host == nil { urlValue = "http://" + urlValue } guard let urlComponents = NSURLComponents(string: urlValue) else { return nil } if !username.isEmpty { urlComponents.user = username if !password.isEmpty { urlComponents.password = password } } return urlComponents.url } } override func viewDidLoad() { super.viewDidLoad() [safariLinkBtn, chromeLinkBtn].forEach { $0!.image = NSImage(named: NSImageNameFollowLinkFreestandingTemplate) } } @IBAction func safariLinkBtnAction(_ sender: AnyObject) { NSWorkspace.shared().open(URL(string: safariExtensionLink)!) } @IBAction func chromeLinkBtnAction(_ sender: AnyObject) { NSWorkspace.shared().open(URL(string: chromeExtensionLink)!) } }
fd3da9a12a4e3ca11507b8cf20341eca
29.25
125
0.706336
false
false
false
false
crossroadlabs/Express
refs/heads/master
Express/View.swift
gpl-3.0
2
//===--- View.swift -------------------------------------------------------===// // //Copyright (c) 2015-2016 Daniel Leping (dileping) // //This file is part of Swift Express. // //Swift Express is free software: you can redistribute it and/or modify //it under the terms of the GNU Lesser General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //Swift Express 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 Lesser General Public License for more details. // //You should have received a copy of the GNU Lesser General Public License //along with Swift Express. If not, see <http://www.gnu.org/licenses/>. // //===----------------------------------------------------------------------===// import Foundation public protocol ViewType { func render<Context>(context:Context?) throws -> FlushableContentType } public protocol NamedViewType : ViewType { var name:String {get} }
a8b47a821290d0df6beabcf21b3fb96b
36.266667
80
0.651746
false
false
false
false
taketo1024/SwiftyAlgebra
refs/heads/develop
Sources/SwmCore/Matrix/Matrix.swift
cc0-1.0
1
// // Matrix.swift // // // Created by Taketo Sano on 2021/05/14. // // MEMO: // The implementation of a matrix-type can be changed by replacing the type parameter `Impl` of `MatrixIF`. // The default implementation works over any ring, but is not useful for high-speed computation. public typealias Matrix<R: Ring, n: SizeType, m: SizeType> = MatrixIF<DefaultMatrixImpl<R>, n, m> public typealias Matrix1x1<R: Ring> = Matrix<R, _1, _1> public typealias Matrix2x2<R: Ring> = Matrix<R, _2, _2> public typealias Matrix3x3<R: Ring> = Matrix<R, _3, _3> public typealias Matrix4x4<R: Ring> = Matrix<R, _4, _4> public typealias ColVector<R: Ring, n: SizeType> = Matrix<R, n, _1> public typealias RowVector<R: Ring, m: SizeType> = Matrix<R, _1, m> public typealias Vector1<R: Ring> = ColVector<R, _1> public typealias Vector2<R: Ring> = ColVector<R, _2> public typealias Vector3<R: Ring> = ColVector<R, _3> public typealias Vector4<R: Ring> = ColVector<R, _4> public typealias AnySizeMatrix<R: Ring> = Matrix<R, anySize, anySize> public typealias AnySizeVector<R: Ring> = ColVector<R, anySize> public typealias MatrixSize = (rows: Int, cols: Int) public typealias MatrixEntry<R: Ring> = (row: Int, col: Int, value: R) public typealias RowEntry<R> = (col: Int, value: R) public typealias ColEntry<R> = (row: Int, value: R)
95e5b9b67349c8170a4d3ad1da30f4e4
40.40625
107
0.707925
false
false
false
false
horizon-institute/babyface-ios
refs/heads/master
src/view controllers/UploadViewController.swift
gpl-3.0
1
// // UploadViewController.swift // babyface // // Created by Kevin Glover on 21/04/2015. // Copyright (c) 2015 Horizon. All rights reserved. // import Foundation import UIKit import CoreTelephony extension NSMutableData { func append(value: String) { if let data = value.dataUsingEncoding(NSUTF8StringEncoding) { appendData(data) } } } class UploadViewController: PageViewController { @IBOutlet weak var uploadActivity: UIActivityIndicatorView! @IBOutlet weak var uploadProgress: UIProgressView! @IBOutlet weak var uploadButton: UIButton! @IBOutlet weak var statusText: UILabel! @IBOutlet weak var errorText: UILabel! @IBOutlet weak var shareButton: UIButton! var uploadStarted = false init() { super.init(nib: "UploadView") } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override var prevPage: Bool { return !uploadStarted } override var trim: Bool { return !uploadStarted } @IBAction func share(sender: UIButton) { let shareText = "We’ve just helped @GestStudy in their research to automatically calculate the gestational age of premature babies. You can help, too!" if let shareURL = NSURL(string: "http://tinyurl.com/gestationalage-estimation") { let objectsToShare = [shareText, shareURL] let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) self.presentViewController(activityVC, animated: true, completion: nil) } } @IBAction func startUpload(sender: AnyObject) { uploadStarted = true pageController?.update() pageController?.parameters["country"] = getCountry() let urlRequest = urlRequestWithComponents("http://www.cs.nott.ac.uk/babyface/upload.php", parameters: pageController!.parameters) statusText.hidden = true uploadActivity.alpha = 0 uploadActivity.hidden = false uploadProgress.progress = 0 uploadProgress.alpha = 0 uploadProgress.hidden = false uploadButton.hidden = true statusText.hidden = false statusText.text = "Uploading" UIView.animateWithDuration(1, animations: { self.uploadActivity.alpha = 1 self.uploadProgress.alpha = 1 }) UIApplication.sharedApplication().networkActivityIndicatorVisible = true upload(urlRequest.0, data: urlRequest.1) .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in NSLog("\(totalBytesWritten) / \(totalBytesExpectedToWrite)") self.uploadProgress.progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite) } .response { (request, response, JSON, error) in print("REQUEST \(request)") print("RESPONSE \(response)") print("JSON \(JSON)") print("ERROR \(error)") // TODO Handle error/ self.uploadProgress.hidden = true self.uploadActivity.hidden = true self.uploadActivity.stopAnimating() UIApplication.sharedApplication().networkActivityIndicatorVisible = false if let errorValue = error as? NSError { self.statusText.text = "Error uploading" self.errorText.text = errorValue.localizedDescription self.errorText.hidden = false self.uploadButton.hidden = false self.uploadButton.setTitle("Retry Upload", forState: .Normal) } else if response?.statusCode != 200 { self.statusText.text = "Error uploading" self.errorText.hidden = false self.uploadButton.hidden = false self.uploadButton.setTitle("Retry Upload", forState: .Normal) } else { self.statusText.text = "Thank you for helping!" self.shareButton.hidden = false } } } func getCountry() -> String { let networkInfo = CTTelephonyNetworkInfo() let carrier = networkInfo.subscriberCellularProvider // Get carrier name var country = carrier!.isoCountryCode if country != nil { return country! } country = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as? String if country != nil { return country! } return "" } func urlRequestWithComponents(urlString:String, parameters:NSDictionary) -> (URLRequestConvertible, NSData) { let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!) let boundaryConstant = "NET-POST-boundary-\(arc4random())-\(arc4random())" mutableURLRequest.HTTPMethod = Method.POST.rawValue mutableURLRequest.setValue("multipart/form-data;boundary="+boundaryConstant, forHTTPHeaderField: "Content-Type") let uploadData = NSMutableData() for (key, value) in parameters { uploadData.append("\r\n--\(boundaryConstant)\r\n") if let postData = value as? NSData { uploadData.append("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(key).jpg\"\r\n") uploadData.append("Content-Type: image/jpeg)\r\n\r\n") uploadData.appendData(postData) } else { NSLog("\(key) = \(value)") uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!) } } uploadData.append("\r\n--\(boundaryConstant)--\r\n") return (ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData) } }
10b3d707742740f74f7aedadc788ef52
27.076503
153
0.716955
false
false
false
false
merlos/iOS-Open-GPX-Tracker
refs/heads/master
OpenGpxTracker/Date+timeAgo.swift
gpl-3.0
1
// // Date+timeAgo.swift // OpenGpxTracker // // Created by merlos on 23/09/2018. // // Localized by nitricware on 19/08/19. // // Based on this discussion: https://gist.github.com/minorbug/468790060810e0d29545 // If future dates are needed at some point. This other implementation may help: // https://gist.github.com/jinthagerman/009c85b7bbd0a40dcbba747e89a501bf // import Foundation extension Date { /// /// Provides a humanified date. For instance: 1 minute, 1 week ago, 3 months ago /// /// - Parameters: /// - numericDates: Set it to true to get "1 year ago", "1 month ago" or false if you prefer "Last year", "Last month" /// func timeAgo(numericDates: Bool) -> String { let calendar = Calendar.current let now = Date() let earliest = self < now ? self : now let latest = self > now ? self : now let unitFlags: Set<Calendar.Component> = [.minute, .hour, .day, .weekOfMonth, .month, .year, .second] let components: DateComponents = calendar.dateComponents(unitFlags, from: earliest, to: latest) if let year = components.year { if year >= 2 { return String(format: NSLocalizedString("T_YEARS_AGO", comment: ""), year) } else if year >= 1 { return numericDates ? NSLocalizedString("T_YEAR_AGO", comment: "") : NSLocalizedString("T_LAST_YEAR", comment: "") } } if let month = components.month { if month >= 2 { return String(format: NSLocalizedString("T_MONTHS_AGO", comment: ""), month) } else if month >= 1 { let monthAgo = NSLocalizedString("T_MONTH_AGO", comment: "") let lastMonth = NSLocalizedString("T_LAST_MONTH", comment: "") return numericDates ? monthAgo : lastMonth } } if let weekOfMonth = components.weekOfMonth { if weekOfMonth >= 2 { return String(format: NSLocalizedString("T_WEEKS_AGO", comment: ""), weekOfMonth) } else if weekOfMonth >= 1 { return numericDates ? NSLocalizedString("T_WEEK_AGO", comment: "") : NSLocalizedString("T_LAST_WEEK", comment: "") } } if let day = components.day { if day >= 2 { return String(format: NSLocalizedString("T_DAYS_AGO", comment: ""), day) } else if day >= 1 { return numericDates ? NSLocalizedString("T_DAY_AGO", comment: "") : NSLocalizedString("T_YESTERDAY", comment: "") } } if let hour = components.hour { if hour >= 2 { return String(format: NSLocalizedString("T_HOURS_AGO", comment: ""), hour) } else if hour >= 1 { return numericDates ? NSLocalizedString("T_HOUR_AGO", comment: "") : NSLocalizedString("T_LAST_HOUR", comment: "") } } if let minute = components.minute { if minute >= 2 { return String(format: NSLocalizedString("T_MINUTES_AGO", comment: ""), minute) } else if minute >= 1 { return numericDates ? NSLocalizedString("T_MINUTE_AGO", comment: "") : NSLocalizedString("T_LAST_MINUTE", comment: "") } } if let second = components.second { if second >= 3 { return String(format: NSLocalizedString("T_SECONDS_AGO", comment: ""), second) } } return NSLocalizedString("T_JUST_NOW", comment: "") } }
2b6b71cad319968201998e1db04327f1
42.156627
134
0.563931
false
false
false
false
el-hoshino/NotAutoLayout
refs/heads/master
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/BottomRightTop.Individual.swift
apache-2.0
1
// // BottomRightTop.Individual.swift // NotAutoLayout // // Created by 史翔新 on 2017/06/20. // Copyright © 2017年 史翔新. All rights reserved. // import Foundation extension IndividualProperty { public struct BottomRightTop { let bottomRight: LayoutElement.Point let top: LayoutElement.Vertical } } // MARK: - Make Frame extension IndividualProperty.BottomRightTop { private func makeFrame(bottomRight: Point, top: Float, width: Float) -> Rect { let x = bottomRight.x - width let y = top let height = bottomRight.y - top let frame = Rect(x: x, y: y, width: width, height: height) return frame } } // MARK: - Set A Length - // MARK: Width extension IndividualProperty.BottomRightTop: LayoutPropertyCanStoreWidthToEvaluateFrameType { public func evaluateFrame(width: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect { let bottomRight = self.bottomRight.evaluated(from: parameters) let top = self.top.evaluated(from: parameters) let height = bottomRight.y - top let width = width.evaluated(from: parameters, withTheOtherAxis: .height(height)) return self.makeFrame(bottomRight: bottomRight, top: top, width: width) } }
e825ce7e5458928861355e180007ff0b
21.574074
115
0.721083
false
false
false
false
ccwuzhou/WWZSwift
refs/heads/master
Source/WWZHeader.swift
mit
1
// // WWZHeader.swift // wwz_swift // // Created by wwz on 17/2/24. // Copyright © 2017年 tijio. All rights reserved. // import UIKit public typealias JSONDictionary = [String: Any] public let WWZ_APP_WINDOW = UIApplication.shared.keyWindow // 屏幕宽度 public let WWZ_SCREEN_HEIGHT = UIScreen.main.bounds.height // 屏幕高度 public let WWZ_SCREEN_WIDTH = UIScreen.main.bounds.width public let WWZ_NAVBAR_HEIGHT : CGFloat = 64.0 public let WWZ_TABBAR_HEIGHT : CGFloat = 49.0 public let WWZ_CELL_IDENTIFIER = "WWZ_CELL_IDENTIFIER" // 系统 public let WWZ_SYSTEM_VERSION = UIDevice.current.systemVersion public let WWZ_IsIOS7Later = WWZ_SYSTEM_VERSION.compare("7.0") != ComparisonResult.orderedAscending public let WWZ_IsIOS8Later = WWZ_SYSTEM_VERSION.compare("8.0") != ComparisonResult.orderedAscending public let WWZ_IsIOS9Later = WWZ_SYSTEM_VERSION.compare("9.0") != ComparisonResult.orderedAscending public let WWZ_IsIOS10Later = WWZ_SYSTEM_VERSION.compare("10.0") != ComparisonResult.orderedAscending // 型号 public let WWZ_IsIPhone35Inch = UIScreen.main.currentMode?.size.equalTo(CGSize(width: 640, height: 960)) public let WWZ_IsIPhone4Inch = UIScreen.main.currentMode?.size.equalTo(CGSize(width: 640, height: 1136)) public let WWZ_IsIPhone47Inch = UIScreen.main.currentMode?.size.equalTo(CGSize(width: 750, height: 1334)) public let WWZ_IsIPhone55Inch = UIScreen.main.currentMode?.size.equalTo(CGSize(width: 1242, height: 2208)) public let WWZ_IsPhone = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.phone public let WWZ_IsPad = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad // 打印 public var WWZ_DEBUG_ENABLED = false public func WWZLog<T>(_ message: T,file: String = #file, function: String = #function, line: Int = #line){ guard WWZ_DEBUG_ENABLED else { return } print("\(Date().wwz_dateFormatString(dateFormat: "yyyy-MM-dd HH:mm:ss.SSS")) \((file as NSString).lastPathComponent)【\(function)】\(message)") } public func WWZ_MAIN_ASYNC(after deadline: TimeInterval, execute: @escaping ()->()) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+deadline, execute: execute) } public func WWZ_BACK_ASYNC(execute: @escaping ()->()) { DispatchQueue.global().async(execute: execute) }
622f0b7462850f56e5f59f731ca8f10e
28.454545
145
0.735891
false
false
false
false
AlanEnjoy/Live
refs/heads/master
Live/Live/Classes/Main/Controller/AmuseMenuView.swift
mit
1
// // AmuseMenuView.swift // Live // // Created by Alan's Macbook on 2017/7/26. // Copyright © 2017年 zhushuai. All rights reserved. // import UIKit fileprivate let kMenuCellID = "kMenuCellID" class AmuseMenuView: UIView { //MARK:- 定义属性 var groups : [AnchorGroup]? { didSet { collectionView.reloadData() } } @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! //MARK:- 从xib中加载出来 override func awakeFromNib() { super.awakeFromNib() collectionView.register(UINib(nibName: "AmuseMenuViewCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID) } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size } } //MARK:- 提供快速创建的类方法 extension AmuseMenuView { class func amuseMenuView() -> AmuseMenuView { return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as! AmuseMenuView } } extension AmuseMenuView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if groups == nil { return 0 } let PageNum = (groups!.count - 1) / 8 + 1 pageControl.numberOfPages = PageNum if PageNum == 1 { pageControl.isHidden = true } return PageNum } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //1.取出cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! AmuseMenuViewCell //2.给cell设置数据 setupCellIDDataWithCell(cell: cell, indexPath: indexPath) return cell } private func setupCellIDDataWithCell(cell : AmuseMenuViewCell , indexPath : IndexPath) { // 0页: 0-7 1页:8-15 2页:15-23 //1.取出起始位置和终止位置 let startIndex = indexPath.item * 8 var endIndex = (indexPath.item + 1) * 8 - 1 //2.判断越界问题 if endIndex > groups!.count - 1 { endIndex = groups!.count - 1 } //3.取出数据,并赋值给cell cell.clipsToBounds = true cell.groups = Array(groups![startIndex...endIndex]) } } extension AmuseMenuView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { pageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width) } }
ea6b65fee1dbbce37d165a17fd12446a
26.227723
125
0.626182
false
false
false
false
IngmarStein/swift
refs/heads/master
test/expr/cast/precedence.swift
apache-2.0
24
// RUN: %target-parse-verify-swift let x: Bool = 3/4 as Float > 1/2 as Float func testInIf(a: Any) { if a as? Float {} // expected-error {{cannot be used as a boolean}} {{6-6=((}} {{17-17=) != nil)}} let _: Float = a as? Float // expected-error {{value of optional type 'Float?' not unwrapped; did you mean to use '!' or '?'?}} {{18-18=(}} {{29-29=)!}} }
a3649218fa2fa69dd4b58b499c579a19
44.125
154
0.584488
false
true
false
false
zhha/RPiProjects-iOS
refs/heads/master
RPiProject/CarViewController.swift
mit
1
// // CarViewController.swift // RPiProject // // Created by wonderworld on 16/8/25. // Copyright © 2016年 haozhang. All rights reserved. // import UIKit class CarViewController: UIViewController { @IBOutlet weak var videoContainer: UIView! let mediaPlayer = VLCMediaPlayer() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let url = NSURL(string: "http://haozhang.win:8090/") // mediaPlayer.setMedia(VLCMedia(URL: url)) mediaPlayer.media = VLCMedia(URL: url) // mediaPlayer.delegate = self mediaPlayer.drawable = videoContainer } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: true) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) mediaPlayer.play() } @IBAction func back(sender: AnyObject) { navigationController?.popViewControllerAnimated(true) } @IBAction func move(sender: UIButton) { switch sender.tag { case 1001: // forward Client.shared.sendMessage("forward") case 1002: // back Client.shared.sendMessage("back") case 1003: // turn_left Client.shared.sendMessage("left") case 1004: // turn_right Client.shared.sendMessage("right") default: break } } @IBAction func stop(sender: UIButton) { // stop Client.shared.sendMessage("stop") } }
2cb360a9aee47ced0b2a2b16c331edbe
25.434783
74
0.611842
false
false
false
false
mathewsheets/SwiftLearningExercises
refs/heads/master
Exercise_4.playground/Contents.swift
mit
1
/*: * callout(Exercise): You have to record all the students for your school. Leveraging arrays, dictionaries, and sets, create table like containers for each class. Your classes are Math, Science, English and History with a total of 17 unique students with 7 students in each class. Print out each class roster and experiment with set operations, membership and equality. **Example Output:** - `Math = Obi-Wan Kenobi, Padme Amidala, Han Solo, Count Dooku, Boba Fett, Luke Skywalker, Kylo Ren` - `Science = Chew Bacca, Padme Amidala, Poe Dameron, Count Dooku, Lando Calrissian, Darth Vader, Luke Skywalker` - `Union of Math and Science = Darth Vader, Chew Bacca, Obi-Wan Kenobi, Padme Amidala, Poe Dameron, Han Solo, Count Dooku, Lando Calrissian, Boba Fett, Luke Skywalker, Kylo Ren` **Constraints:** - Use Set Operations - intersection(_:) - symmetricDifference(_:) - union(_:) - subtracting(_:) - Use Set Membership and Equality - is equal - isSubset(of:) - isSuperset(of:) - isStrictSubset(of:) - isStrictSuperset(of:) - isDisjoint(with:) */ // Data var rows = [ ["column_1" : "Obi-Wan", "column_2" : "Kenobi"], ["column_1" : "Darth", "column_2" : "Vader"], ["column_1" : "Anakin", "column_2" : "Skywalker"], ["column_1" : "Darth", "column_2" : "Sidious"], ["column_1" : "Padme", "column_2" : "Amidala"], ["column_1" : "Mace", "column_2" : "Windu"], ["column_1" : "Count", "column_2" : "Dooku"], ["column_1" : "Luke", "column_2" : "Skywalker"], ["column_1" : "Han", "column_2" : "Solo"], ["column_1" : "Leia", "column_2" : "Organa"], ["column_1" : "Chew", "column_2" : "Bacca"], ["column_1" : "Boba", "column_2" : "Fett"], ["column_1" : "Lando", "column_2" : "Calrissian"], ["column_1" : "Kylo", "column_2" : "Ren"], ["column_1" : "Poe", "column_2" : "Dameron"], ["column_1" : "Finn", "column_2" : "FN-2187"], ["column_1" : "Rey", "column_2" : "Rey"] ] // Data Types typealias StudentKey = String typealias StudentValue = String typealias StudentName = String typealias ClassName = String typealias Student = [StudentKey:StudentValue] typealias Students = [Student] typealias Class = Set<StudentName> typealias Classes = [ClassName:Class] // Processing var allStudents = Set<String>() for (index, var student) in rows.enumerated() { let name = "\(student["column_1"]!) \(student["column_2"]!)" student["name"] = name rows[index] = student allStudents.insert(name) } var math = Class() math.insert(rows[8]["name"]!) math.insert(rows[4]["name"]!) math.insert(rows[13]["name"]!) math.insert(rows[11]["name"]!) math.insert(rows[7]["name"]!) math.insert(rows[0]["name"]!) math.insert(rows[6]["name"]!) var science = Class() science.insert(rows[7]["name"]!) science.insert(rows[12]["name"]!) science.insert(rows[10]["name"]!) science.insert(rows[4]["name"]!) science.insert(rows[14]["name"]!) science.insert(rows[6]["name"]!) science.insert(rows[1]["name"]!) var english = Class() english.insert(rows[3]["name"]!) english.insert(rows[5]["name"]!) english.insert(rows[13]["name"]!) english.insert(rows[16]["name"]!) english.insert(rows[6]["name"]!) english.insert(rows[2]["name"]!) english.insert(rows[9]["name"]!) var history = Class() history.insert(rows[7]["name"]!) history.insert(rows[0]["name"]!) history.insert(rows[15]["name"]!) history.insert(rows[2]["name"]!) history.insert(rows[4]["name"]!) history.insert(rows[6]["name"]!) history.insert(rows[5]["name"]!) var classes = Classes() classes["Math"] = math classes["Science"] = science classes["Engligh"] = english classes["History"] = history print("All \(rows.count) students") for student in rows { print("\t\(student["name"]!)") } //let classNames = classes.keys // this causes a runtime error for name in classes.keys { let _class = classes[name]! print("\(_class.count) \(name) Students") for student in _class { print("\t\(student)") } } let mathAndScienceIntersect = math.intersection(science) print("\(mathAndScienceIntersect.count) Intersecting Math & Science Students") for student in mathAndScienceIntersect { print("\t\(student)") } let mathAndScienseExclusiveOr = math.symmetricDifference(science) print("\(mathAndScienseExclusiveOr.count) Symmetric Difference of Math & Science Students") for student in mathAndScienseExclusiveOr { print("\t\(student)") } let mathAndScienceUnion = math.union(science) print("\(mathAndScienceUnion.count) Union of Math & Science Students") for student in mathAndScienceUnion { print("\t\(student)") } let mathAndScienceSubtract = math.subtracting(science) print("\(mathAndScienceSubtract.count) Subtracting Math & Science Students") for student in mathAndScienceSubtract { print("\t\(student)") } if allStudents == math.union(science).union(english).union(history) { print("Unioning all classes equals all the students") } if english.isSubset(of: allStudents) { print("English is a subset of all students") } if !english.isSubset(of: history) { print("English is not a subset of History") } if allStudents.isSuperset(of: history) { print("All students is a superset of History") } var mathBoys = Class() mathBoys.insert(rows[13]["name"]!) mathBoys.insert(rows[0]["name"]!) mathBoys.insert(rows[7]["name"]!) mathBoys.insert(rows[6]["name"]!) mathBoys.insert(rows[4]["name"]!) var mathGirls = Class() mathGirls.insert(rows[11]["name"]!) mathGirls.insert(rows[8]["name"]!) if mathGirls.isStrictSubset(of: math) { print("Math girls is a strict subset of math") } if !mathGirls.union(mathBoys).isStrictSubset(of: math) { print("Math girls & boys is not a strict subset of math") } if !allStudents.isStrictSuperset(of: math.union(science).union(english).union(history)) { print("All classes is not a strict superset of all students") } let stemStudents = math.union(science) if allStudents.isStrictSuperset(of: stemStudents) { print("All students is a strict superset of STEM students") } if mathBoys.isDisjoint(with: mathGirls) { print("Math boys is disjointed w/ math girls") } if !mathGirls.isDisjoint(with: math) { print("Math girls is not disjointed w/ math") }
6dd6abf3edb89eb7cad47b8afe75ce00
32.518519
369
0.661563
false
false
false
false
exyte/Macaw
refs/heads/master
Source/animation/types/PathAnimation.swift
mit
1
// // PathAnimation.swift // Macaw // // Created by Victor Sukochev on 01/01/2018. // import Foundation class PathAnimation: AnimationImpl<Double> { let isEnd: Bool = true convenience init(animatedNode: Shape, isEnd: Bool, startValue: Double, finalValue: Double, animationDuration: Double, delay: Double = 0.0, autostart: Bool = false, fps: UInt = 30) { let interpolationFunc = { (t: Double) -> Double in startValue.interpolate(finalValue, progress: t) } self.init(animatedNode: animatedNode, isEnd: isEnd, valueFunc: interpolationFunc, animationDuration: animationDuration, delay: delay, autostart: autostart, fps: fps) } init(animatedNode: Shape, isEnd: Bool, valueFunc: @escaping (Double) -> Double, animationDuration: Double, delay: Double = 0.0, autostart: Bool = false, fps: UInt = 30) { super.init(observableValue: AnimatableVariable<Double>(isEnd ? animatedNode.strokeVar.end.value : animatedNode.strokeVar.start.value), valueFunc: valueFunc, animationDuration: animationDuration, delay: delay, fps: fps) type = .path node = animatedNode if autostart { self.play() } } init(animatedNode: Shape, isEnd: Bool, factory: @escaping (() -> ((Double) -> Double)), animationDuration: Double, delay: Double = 0.0, autostart: Bool = false, fps: UInt = 30) { super.init(observableValue: AnimatableVariable<Double>(isEnd ? animatedNode.strokeVar.end.value : animatedNode.strokeVar.start.value), factory: factory, animationDuration: animationDuration, delay: delay, fps: fps) type = .path node = animatedNode if autostart { self.play() } } // Pause state not available for discreet animation override public func pause() { stop() } } public typealias PathAnimationDescription = AnimationDescription<Double> open class StrokeAnimatableVariable: AnimatableVariable<Stroke?> { public var end: StrokeSideVariable { return StrokeSideVariable(parentVar: self, isEnd: true) } public var start: StrokeSideVariable { return StrokeSideVariable(parentVar: self, isEnd: false) } } open class StrokeSideVariable { let parentVar: StrokeAnimatableVariable let isEnd: Bool var value: Double = 0 var node: Node? { parentVar.node } init(parentVar: StrokeAnimatableVariable, isEnd: Bool, value: Double = 0) { self.parentVar = parentVar self.isEnd = isEnd self.value = value } public func animate(_ desc: PathAnimationDescription) { _ = PathAnimation(animatedNode: node as! Shape, isEnd: isEnd, valueFunc: desc.valueFunc, animationDuration: desc.duration, delay: desc.delay, autostart: true) } public func animation(_ desc: PathAnimationDescription) -> Animation { return PathAnimation(animatedNode: node as! Shape, isEnd: isEnd, valueFunc: desc.valueFunc, animationDuration: desc.duration, delay: desc.delay, autostart: false) } public func animate(from: Double? = nil, to: Double = 1, during: Double = 1.0, delay: Double = 0.0) { self.animate(((from ?? 0) >> to).t(during, delay: delay)) } public func animation(from: Double? = nil, to: Double = 1, during: Double = 1.0, delay: Double = 0.0) -> Animation { if let safeFrom = from { return self.animation((safeFrom >> to).t(during, delay: delay)) } let origin = Double(0) let factory = { () -> (Double) -> Double in { (t: Double) in origin.interpolate(to, progress: t) } } return PathAnimation(animatedNode: node as! Shape, isEnd: isEnd, factory: factory, animationDuration: during, delay: delay) } public func animation(_ f: @escaping ((Double) -> Double), during: Double = 1.0, delay: Double = 0.0) -> Animation { return PathAnimation(animatedNode: node as! Shape, isEnd: isEnd, valueFunc: f, animationDuration: during, delay: delay) } }
095f74b6727c74d50f351f25a9693d1f
37.625
226
0.664675
false
false
false
false
flypaper0/ethereum-wallet
refs/heads/release/1.1
ethereum-wallet/Classes/BusinessLayer/Services/Pin/State/EnterPinState.swift
gpl-3.0
1
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import Foundation public let PinLockIncorrectPinNotification = "pin.lock.incorrect.pin.notification" struct EnterPinState: PinStateProtocol { let title: String let isCancellableAction: Bool let touchIdReason: String? let isTermsShown: Bool private var inccorectPinAttempts = 0 private var isNotificationSent = false init(allowCancellation: Bool, title: String, touchIdReason: String?) { self.title = title self.touchIdReason = touchIdReason self.isCancellableAction = allowCancellation self.isTermsShown = false } mutating func acceptPin(_ pin: [String], fromLock lock: PinServiceProtocol) { guard let currentPin = lock.repository.pin else { return } if pin == currentPin { lock.delegate?.pinLockDidSucceed(lock, acceptedPin: pin) } else { inccorectPinAttempts += 1 if inccorectPinAttempts >= lock.configuration.maximumInccorectPinAttempts { postNotification() } lock.delegate?.pinLockDidFail(lock) } } private mutating func postNotification() { guard !isNotificationSent else { return } let name = NSNotification.Name(rawValue: PinLockIncorrectPinNotification) NotificationCenter.default.post(name: name, object: nil) isNotificationSent = true } }
a69dec3b40546fdc3a12d4ab6262ebfc
27.6875
82
0.721859
false
false
false
false
luosheng/SwiftSockets
refs/heads/develop
ARISockets/DNS.swift
mit
2
// // DNS.swift // ARISockets // // Created by Helge Hess on 7/3/14. // Copyright (c) 2014 Always Right Institute. All rights reserved. // import Darwin func gethoztbyname<T: SocketAddress> (name : String, flags : Int32 = AI_CANONNAME, cb : ( String, String?, T? ) -> Void) { // Note: I can't just provide a name and a cb, swiftc will complain. var hints = addrinfo() hints.ai_flags = flags // AI_CANONNAME, AI_NUMERICHOST, etc hints.ai_family = T.domain var ptr = UnsafeMutablePointer<addrinfo>(nil) defer { freeaddrinfo(ptr) } /* free OS resources (TBD: works with nil?) */ /* run lookup (synchronously, can be slow!) */ // b3: (cs : CString) doesn't pick up the right overload? let rc = name.withCString { (cs : UnsafePointer<CChar>) -> Int32 in return getaddrinfo(cs, nil, &hints, &ptr) // returns just the block! } guard rc == 0 else { cb(name, nil, nil) return } /* copy results - we just take the first match */ var cn : String? = nil var addr : T? = ptr.memory.address() if rc == 0 && ptr != nil { cn = ptr.memory.canonicalName addr = ptr.memory.address() } /* report results */ cb(name, cn, addr) } /** * This is awkward :-) But it actually works. Though it is not what you want, * the address here should be dynamic depending on the domain of the C struct. * * Whatever, this runs: * let hhost : String = "mail.google.com" // why is this necessary? * gethostzbyname(hhost, flags: Int32(AI_CANONNAME)) { * ( cn: String, infos: [ ( cn: String?, address: sockaddr_in? )]? ) -> Void * in * print("result \(cn): \(infos)") * } * * TBD: The 'flags' has to be provided, otherwise the trailing closure is not * detected right? */ func gethostzbyname<T: SocketAddress> (name : String, flags : Int32 = AI_CANONNAME, cb : ( String, [ ( cn: String?, address: T? ) ]? ) -> Void ) -> Void { // Note: I can't just provide a name and a cb, swiftc will complain. var hints = addrinfo() hints.ai_flags = flags // AI_CANONNAME, AI_NUMERICHOST, etc hints.ai_family = T.domain var ptr = UnsafeMutablePointer<addrinfo>(nil) defer { freeaddrinfo(ptr) } /* free OS resources (TBD: works with nil?) */ /* run lookup (synchronously, can be slow!) */ let rc = name.withCString { (cs : UnsafePointer<CChar>) -> Int32 in return getaddrinfo(cs, nil, &hints, &ptr) // returns just the block! } if rc != 0 { cb(name, nil) return } /* copy results - we just take the first match */ typealias hapair = (cn: String?, address: T?) var results : Array<hapair>! = nil if rc == 0 && ptr != nil { var pairs = Array<hapair>() for info in ptr.memory { let pair : hapair = ( info.canonicalName, info.address() ) pairs.append(pair) } results = pairs } /* report results */ cb(name, results) }
fcccd1ba2e0d45475fa1381019073278
28.55102
80
0.617749
false
false
false
false
banDedo/BDModules
refs/heads/master
BlurView/BlurView.swift
apache-2.0
1
// // BlurView.swift // BDModules // // Created by Patrick Hogan on 11/22/14. // Copyright (c) 2014 bandedo. All rights reserved. // import Snap import UIKit public class BlurView: UIView { private var style: UIBlurEffectStyle private(set) public lazy var blurEffect: UIBlurEffect = { return UIBlurEffect(style: self.style) }() private(set) public lazy var blurView: UIVisualEffectView = { let blurView = UIVisualEffectView(effect: self.blurEffect) return blurView }() private(set) public lazy var vibrancyView: UIVisualEffectView = { let vibrancyEffect = UIVibrancyEffect(forBlurEffect: self.blurEffect) let vibrancyView = UIVisualEffectView(effect: vibrancyEffect) return vibrancyView }() init(style: UIBlurEffectStyle) { self.style = style super.init(frame: CGRectZero) addSubview(blurView) blurView.contentView.addSubview(vibrancyView) blurView.snp_makeConstraints{ make in make.edges.equalTo(UIEdgeInsetsZero) } vibrancyView.snp_makeConstraints{ make in make.edges.equalTo(UIEdgeInsetsZero) } } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
fd2724aa1c20e5ed34d40f512428df75
25.096154
77
0.643331
false
false
false
false
XSega/Words
refs/heads/master
Words/Scenes/Trainings/Old/TrainingRouter.swift
mit
1
// // TrainingRouter.swift // Words // // Created by Sergey Ilyushin on 27/07/2017. // Copyright © 2017 Sergey Ilyushin. All rights reserved. // import UIKit protocol ITrainingRouter: class { weak var viewController: UIViewController? { get set } func presentFinishScreen(mistakes: Int, words: Int) static func assembleSprintModule(meaningIds: [Int], api: API) -> UIViewController } class TrainingRouter: ITrainingRouter { weak var viewController: UIViewController? static func assembleSprintModule(meaningIds: [Int], api: API) -> UIViewController { let view = mainStoryboard.instantiateViewController(withIdentifier: "SprintViewController") as! SprintViewController let interactor = TrainingInteractor() let presenter = SprintTrainingPresenter(); let router = TrainingRouter() view.presenter = presenter presenter.view = view presenter.interactor = interactor presenter.router = router interactor.presenter = presenter let apiDataManager = APIDataManager(api: api) let localDataManager = LocalDataManager() interactor.apiDataManager = apiDataManager interactor.localDataManager = localDataManager interactor.meaningIds = meaningIds view.presenter = presenter router.viewController = view return view } static var mainStoryboard: UIStoryboard { return UIStoryboard(name: "Main", bundle: Bundle.main) } func presentFinishScreen(mistakes: Int, words: Int) { let finishView = FinishTrainingRouter.assembleModule(mistakes: mistakes, words: words) viewController?.navigationController?.pushViewController(finishView, animated: true) } }
2c3baf4e855b582a9d5e4f0aed6abfe2
30.631579
124
0.686633
false
false
false
false
zhiquan911/CHKLineChart
refs/heads/master
CHKLineChart/Example/Example/Demo/DemoSelectViewController.swift
mit
1
// // ViewController.swift // CHKLineChart // // Created by Chance on 16/8/31. // Copyright © 2016年 Chance. All rights reserved. // import UIKit import CHKLineChartKit class DemoSelectViewController: UIViewController { @IBOutlet var tableView: UITableView! let demo: [Int: (String, String, Bool)] = [ 0: ("K线最佳实践例子", "ChartCustomViewController", false), 1: ("K线简单线段例子", "ChartFullViewController", true), 2: ("K线静态图片例子", "ChartImageViewController", true), 3: ("K线列表图表例子", "ChartInTableViewController", true), 4: ("盘口深度图表例子", "DepthChartDemoViewController", true), ] override func viewDidLoad() { super.viewDidLoad() } } extension DemoSelectViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.demo.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "DemoCell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "DemoCell") } cell?.textLabel?.text = self.demo[indexPath.row]!.0 return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if let demoObject = self.demo[indexPath.row] { var vc: UIViewController let className = demoObject.1 let isNIB = demoObject.2 if isNIB { guard let storyboard = self.storyboard else { return } vc = storyboard.instantiateViewController(withIdentifier: className) } else { guard let nameSpage = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else { return } guard let Type = NSClassFromString(nameSpage + "." + className) as? UIViewController.Type else { return //无法获取到该控制器类型 后续代码不用执行 } vc = Type.init() } self.navigationController?.pushViewController(vc, animated: true) } } }
70ecbe8a8c9c2488c007e143e4960b9f
31.064103
112
0.588565
false
false
false
false
apple/swift-tools-support-core
refs/heads/main
Sources/TSCUtility/Hex.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors import Foundation @usableFromInline internal func char(forNibble value: UInt8) -> CChar { switch value { case 0 ..< 10: return CChar(UInt8(ascii: "0") + value) default: precondition(value < 16) return CChar(UInt8(ascii: "a") + value - 10) } } @usableFromInline internal func nibble(forHexChar char: UInt8) -> UInt8? { switch char { case UInt8(ascii: "0")...UInt8(ascii: "9"): return char - UInt8(ascii: "0") case UInt8(ascii: "a")...UInt8(ascii: "f"): return 10 + char - UInt8(ascii: "a") case UInt8(ascii: "A")...UInt8(ascii: "F"): return 10 + char - UInt8(ascii: "a") default: return nil } } @inlinable public func hexEncode<T: Collection>(_ bytes: T) -> [CChar] where T.Element == UInt8, T.Index == Int { var output = [CChar](repeating: 0, count: Int(bytes.count) * 2) for (i, byte) in bytes.enumerated() { output[i*2 + 0] = char(forNibble: (byte >> 4) & 0xF) output[i*2 + 1] = char(forNibble: (byte >> 0) & 0xF) } return output } @inlinable public func hexEncode<T: Collection>(_ bytes: T) -> String where T.Element == UInt8, T.Index == Int { let chars = hexEncode(bytes) as [CChar] return String(tsc_fromUTF8: chars.map{ UInt8($0) }) } extension String { /// Decode the string as a sequence of hex bytes (with no leading 0x prefix). @inlinable public func tsc_hexDecode() -> [UInt8]? { let utf8 = self.utf8 let count = utf8.count let byteCount = count / 2 if count != byteCount * 2 { return nil } var result = [UInt8](repeating: 0, count: byteCount) var seq = utf8.makeIterator() for i in 0 ..< byteCount { guard let hi = nibble(forHexChar: seq.next()!) else { return nil } guard let lo = nibble(forHexChar: seq.next()!) else { return nil } result[i] = (hi << 4) | lo } return result } }
a02f323d95502dc9e35f2b446c87af50
31.43662
102
0.607034
false
false
false
false
domenicosolazzo/practice-swift
refs/heads/master
Apps/Algorhrythm/Algorhrythm/PlaylistDetailViewController.swift
mit
1
// // PlaylistDetailViewController.swift // Algorhrythm // // Created by Domenico on 14/04/16. // Copyright © 2016 Domenico Solazzo. All rights reserved. // import UIKit class PlaylistDetailViewController: UIViewController { var playlist: Playlist? @IBOutlet weak var playlistCoverImage: UIImageView! @IBOutlet weak var playlistTitle: UILabel! @IBOutlet weak var playlistDescription: UILabel! @IBOutlet weak var playlistArtist0: UILabel! @IBOutlet weak var playlistArtist1: UILabel! @IBOutlet weak var playlistArtist2: UILabel! override func viewDidLoad() { super.viewDidLoad() if playlist != nil { playlistCoverImage.image = playlist!.largeIcon playlistCoverImage.backgroundColor = playlist!.backgroundColor playlistTitle.text = playlist!.title playlistDescription.text = playlist!.description playlistArtist0.text = playlist!.artists[0] playlistArtist1.text = playlist!.artists[1] playlistArtist2.text = playlist!.artists[2] } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
4f7ae14ec6ef86d531720c74b6004ff8
28.431818
74
0.657143
false
false
false
false
TwilioDevEd/api-snippets
refs/heads/master
video/rooms/video-constraints/video-constraints.swift
mit
2
// Create camera object let camera = TVICameraCapturer() // Setup the video constraints let videoConstraints = TVIVideoConstraints { (constraints) in constraints.maxSize = TVIVideoConstraintsSize960x540; constraints.minSize = TVIVideoConstraintsSize960x540; constraints.maxFrameRate = TVIVideoConstraintsFrameRateNone; constraints.minFrameRate = TVIVideoConstraintsFrameRateNone; } // Add local video track with camera and video constraints var localVideoTrack = TVILocalVideoTrack.init(capturer: camera!, enabled: true, constraints: videoConstraints) // If the constraints are not satisfied, a nil track will be returned. if (localVideoTrack == nil) { print ("Error: Failed to create a video track using the local camera.") }
ee7201cf4e4fae1863672d9902a91bb4
43.263158
76
0.703924
false
false
false
false
WestlakeAPC/game-off-2016
refs/heads/master
external/Fiber2D/Fiber2D/ActionSequence.swift
apache-2.0
1
// // ActionSequenceContainer.swift // Fiber2D // // Created by Andrey Volodin on 04.09.16. // Copyright © 2016 s1ddok. All rights reserved. // public struct ActionSequenceContainer: ActionContainer, Continous { @inline(__always) mutating public func update(state: Float) { let t = state var found = 0 var new_t: Float = 0.0 if t < split { // action[0] found = 0 if split != 0 { new_t = t / split } else { new_t = 1 } } else { // action[1] found = 1 if split == 1 { new_t = 1 } else { new_t = (t - split) / (1 - split) } } if found == 1 { if last == -1 { // action[0] was skipped, execute it. actions[0].start(with: target) actions[0].update(state: 1.0) actions[0].stop() } else if last == 0 { // switching to action 1. stop action 0. actions[0].update(state: 1.0) actions[0].stop() } } else if found == 0 && last == 1 { // Reverse mode ? // XXX: Bug. this case doesn't contemplate when _last==-1, found=0 and in "reverse mode" // since it will require a hack to know if an action is on reverse mode or not. // "step" should be overriden, and the "reverseMode" value propagated to inner Sequences. actions[1].update(state: 0) actions[1].stop() } // Last action found and it is done. if found == last && actions[found].isDone { return } // New action. Start it. if found != last { actions[found].start(with: target) } actions[found].update(state: new_t) self.last = found } public mutating func start(with target: AnyObject?) { elapsed = 0 self.target = target self.split = actions[0].duration / max(duration, Float.ulpOfOne) self.last = -1 } public mutating func stop() { // Issue #1305 if last != -1 { actions[last].stop() } target = nil } public mutating func step(dt: Time) { elapsed += dt self.update(state: max(0, // needed for rewind. elapsed could be negative min(1, elapsed / max(duration, Float.ulpOfOne)) // division by 0 ) ) } weak var target: AnyObject? = nil public var tag: Int = 0 private(set) public var duration: Time = 0.0 private(set) public var elapsed: Time = 0.0 public var isDone: Bool { return elapsed > duration } private(set) var actions: [ActionContainerFiniteTime] = [] private var split: Float = 0.0 private var last = -1 init(first: ActionContainerFiniteTime, second: ActionContainerFiniteTime) { actions = [first, second] // Force unwrap because it won't work otherwise anyways duration = first.duration + second.duration } } /*extension ActionSequenceContainer { init(actions: ActionContainer...) { guard actions.count > 2 else { assertionFailure("ERROR: Sequence must contain at least 2 actions") return } let first = actions.first! var second: ActionContainer = actions[1] for i in 2..<actions.count { second = ActionSequenceContainer(first: second, second: actions[i]) } self.init(first: first, second: second) } }*/ extension ActionContainer where Self: FiniteTime { public func then(_ next: ActionContainerFiniteTime) -> ActionSequenceContainer { return ActionSequenceContainer(first: self, second: next) } }
1483d86eda24f5a4118a15ecd9657b4c
28.20438
101
0.51962
false
false
false
false
alexanderedge/European-Sports
refs/heads/master
EurosportPlayerTV/Controllers/LoadingViewController.swift
mit
1
// // LoadingViewController.swift // EurosportPlayer // // Created by Alexander Edge on 26/11/2016. import UIKit class LoadingViewController: UIViewController { private var menuPressRecognizer: UITapGestureRecognizer? lazy fileprivate var loadingIndicator: UIActivityIndicatorView = { let activity = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) activity.startAnimating() return activity }() override func viewDidLoad() { super.viewDidLoad() let darkView = UIView(frame: view.bounds) darkView.backgroundColor = UIColor(white: 0, alpha: 0.5) darkView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(darkView) /* let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark)) visualEffectView.frame = view.bounds visualEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(visualEffectView) */ // disable menu button while loading let menuPressRecognizer = UITapGestureRecognizer() menuPressRecognizer.addTarget(self, action: #selector(LoadingViewController.handleMenuButton(gr:))) menuPressRecognizer.allowedPressTypes = [NSNumber(value: UIPressType.menu.hashValue)] menuPressRecognizer.isEnabled = false view.addGestureRecognizer(menuPressRecognizer) self.menuPressRecognizer = menuPressRecognizer view.addSubview(loadingIndicator) loadingIndicator.center = CGPoint(x: view.bounds.width / 2, y: view.bounds.height / 2) view.addConstraint(NSLayoutConstraint(item: loadingIndicator, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: loadingIndicator, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0)) } func handleMenuButton(gr: UITapGestureRecognizer) { } }
5f55b217cf3474d03e18ef17fe42cc40
38.019231
173
0.717595
false
false
false
false
OstKakalo/small-blog
refs/heads/master
DiscoverViewController.swift
gpl-3.0
1
// // DiscoverViewController.swift // SmallBlog // // Created by 胡梦龙 on 2017/4/20. // Copyright © 2017年 胡梦龙. All rights reserved. // import UIKit class DiscoverViewController: BaseViewController { 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 numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
900b575c1d289dcd05e6a9026a79e956
31.757895
136
0.669344
false
false
false
false
rhx/SwiftGtk
refs/heads/main
Sources/Gtk/Radio.swift
bsd-2-clause
1
// // Radio.swift // Gtk // // Created by Rene Hexel on 17/3/19. // Copyright © 2019, 2020 Rene Hexel. All rights reserved. // import CGdk import CGtk import GLib import Gdk public extension RadioButton { /// Create a group of radio buttons with the given array of labels /// /// - Parameter labels: array of labels for the radio buttons /// - Returns: grouped array of radio buttons @inlinable static func groupWith(labels: [String]) -> [RadioButton] { var previousButton: RadioButton? return labels.map { let button: RadioButton if let prev = previousButton { button = RadioButton(group: prev.group, label: $0) } else { button = RadioButton(label: $0) } previousButton = button return button } } /// Create a group of radio buttons with the given labels /// /// - Parameter ls: labels to use for the radio buttons /// - Returns: grouped array of radio buttons @inlinable static func groupLabeled(_ ls: String...) -> [RadioButton] { return groupWith(labels: ls) } /// Create a group of radio buttons with the given labels. /// Underscores in the labels denote the mnemonics for the corresponding buttons. /// /// - Parameter mnemonics: labels to use for the buttons /// - Returns: grouped array of radio buttons @inlinable static func groupWith(mnemonics: [String]) -> [RadioButton] { var previousButton: RadioButton? return mnemonics.map { let button: RadioButton if let prev = previousButton { button = RadioButton(group: prev.group, mnemonic: $0) } else { button = RadioButton(mnemonic: $0) } previousButton = button return button } } /// Create a group of radio buttons with the given labels /// Underscores in the labels denote the mnemonics for the corresponding buttons. /// /// - Parameter ms: labels to use for the buttons /// - Returns: grouped array of radio buttons @inlinable static func groupWithMnemonics(_ ms: String...) -> [RadioButton] { return groupWith(mnemonics: ms) } }
5a31a3c6f388ebf61235f9ed2d8e0c60
33.029851
85
0.609211
false
false
false
false
HongliYu/firefox-ios
refs/heads/master
Storage/RemoteTabs.swift
mpl-2.0
2
/* 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 Deferred public struct ClientAndTabs: Equatable, CustomStringConvertible { public let client: RemoteClient public let tabs: [RemoteTab] public var description: String { return "<Client guid: \(client.guid ?? "nil"), \(tabs.count) tabs.>" } // See notes in RemoteTabsPanel.swift. public func approximateLastSyncTime() -> Timestamp { if tabs.isEmpty { return client.modified } return tabs.reduce(Timestamp(0), { m, tab in return max(m, tab.lastUsed) }) } } public func ==(lhs: ClientAndTabs, rhs: ClientAndTabs) -> Bool { return (lhs.client == rhs.client) && (lhs.tabs == rhs.tabs) } public protocol RemoteClientsAndTabs: SyncCommands { func wipeClients() -> Deferred<Maybe<()>> func wipeRemoteTabs() -> Deferred<Maybe<()>> func wipeTabs() -> Deferred<Maybe<()>> func getClientGUIDs() -> Deferred<Maybe<Set<GUID>>> func getClients() -> Deferred<Maybe<[RemoteClient]>> func getClient(guid: GUID) -> Deferred<Maybe<RemoteClient?>> func getClient(fxaDeviceId: String) -> Deferred<Maybe<RemoteClient?>> func getRemoteDevices() -> Deferred<Maybe<[RemoteDevice]>> func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> func getTabsForClientWithGUID(_ guid: GUID?) -> Deferred<Maybe<[RemoteTab]>> func insertOrUpdateClient(_ client: RemoteClient) -> Deferred<Maybe<Int>> func insertOrUpdateClients(_ clients: [RemoteClient]) -> Deferred<Maybe<Int>> // Returns number of tabs inserted. func insertOrUpdateTabs(_ tabs: [RemoteTab]) -> Deferred<Maybe<Int>> // Insert into the local client. func insertOrUpdateTabsForClientGUID(_ clientGUID: String?, tabs: [RemoteTab]) -> Deferred<Maybe<Int>> func deleteClient(guid: GUID) -> Success } public struct RemoteTab: Equatable { public let clientGUID: String? public let URL: Foundation.URL public let title: String public let history: [Foundation.URL] public let lastUsed: Timestamp public let icon: Foundation.URL? public static func shouldIncludeURL(_ url: Foundation.URL) -> Bool { let scheme = url.scheme if scheme == "about" { return false } if scheme == "javascript" { return false } if let hostname = url.host?.lowercased() { if hostname == "localhost" { return false } return true } return false } public init(clientGUID: String?, URL: Foundation.URL, title: String, history: [Foundation.URL], lastUsed: Timestamp, icon: Foundation.URL?) { self.clientGUID = clientGUID self.URL = URL self.title = title self.history = history self.lastUsed = lastUsed self.icon = icon } public func withClientGUID(_ clientGUID: String?) -> RemoteTab { return RemoteTab(clientGUID: clientGUID, URL: URL, title: title, history: history, lastUsed: lastUsed, icon: icon) } } public func ==(lhs: RemoteTab, rhs: RemoteTab) -> Bool { return lhs.clientGUID == rhs.clientGUID && lhs.URL == rhs.URL && lhs.title == rhs.title && lhs.history == rhs.history && lhs.lastUsed == rhs.lastUsed && lhs.icon == rhs.icon } extension RemoteTab: CustomStringConvertible { public var description: String { return "<RemoteTab clientGUID: \(clientGUID ?? "nil"), URL: \(URL), title: \(title), lastUsed: \(lastUsed)>" } }
fc0218899aa8a02bc1e5a834aa8956fe
33.833333
145
0.640883
false
false
false
false
developerY/Active-Learning-Swift-2.0_DEMO
refs/heads/master
ActiveLearningSwift2.playground/Pages/Optianal Chaining.xcplaygroundpage/Contents.swift
apache-2.0
3
//: [Previous](@previous) // ------------------------------------------------------------------------------------------------ // Things to know: // // * Optional Chaining is the process of safely referencing a series of optionals (which contain // optionals, which contain optionals, etc.) without having to perform the optional unwrapping // checks at each step along the way. // ------------------------------------------------------------------------------------------------ // Consider a case of forced unwrapping like "someOptional!.someProperty". We already know that // this is only safe if we know that the optional will never be nil. For times that we don't know // this, we must check the optional before we can reference it. This can become cumbersome for // situations where many optionals are chained together as properties of properties. Let's create // a series of optionals to show this: class Artist { let name: String init(name: String) { self.name = name } } class Song { let name: String var artist: Artist? init(name: String, artist: Artist?) { self.name = name self.artist = artist } } class MusicPreferences { var favoriteSong: Song? init(favoriteSong: Song?) { self.favoriteSong = favoriteSong } } class Person { let name: String var musicPreferences: MusicPreferences? init (name: String, musicPreferences: MusicPreferences?) { self.name = name self.musicPreferences = musicPreferences } } // Here, we'll create a working chain: var someArtist: Artist? = Artist(name: "Somebody with talent") var favSong: Song? = Song(name: "Something with a beat", artist: someArtist) var musicPrefs: MusicPreferences? = MusicPreferences(favoriteSong: favSong) var person: Person? = Person(name: "Bill", musicPreferences: musicPrefs) // We can access this chain with forced unwrapping. In this controlled environment, this will work // but it's probably not advisable in a real world situation unless you're sure that each member // of the chain is sure to never be nil. person!.musicPreferences!.favoriteSong!.artist! // Let's break the chain, removing the user's music preferences: if var p = person { p.musicPreferences = nil } // With a broken chain, if we try to reference the arist like before, we will get a runtime error. // // The following line will compile, but will crash: // // person!.musicPreferences!.favoriteSong!.artist! // // The solusion here is to use optional chaining, which replaces the forced unwrapping "!" with // a "?" character. If at any point along this chain, any optional is nil, evaluation is aborted // and the entire result becomes nil. // // Let's see this entire chain, one step at a time working backwards. This let's us see exactly // where the optional chain becomes a valid value: person?.musicPreferences?.favoriteSong?.artist person?.musicPreferences?.favoriteSong person?.musicPreferences person // Optional chaining can be mixed with non-optionals as well as forced unwrapping and other // contexts (subcripts, function calls, return values, etc.) We won't bother to create the // series of classes and instances for the following example, but it should serve as a valid // example of how to use optional chaining syntax in various situations. Given the proper context // this line of code would compile and run as expected. // // person?.musicPreferences?[2].getFavoriteSong()?.artist?.name // // This line could be read as: optional person's second optional music preference's favorite song's // optional artist's name. //: [Next](@next)
8e700d02da15ba0a0e3c6e6e1d5ad77e
37.319149
99
0.694892
false
false
false
false
hanhailong/practice-swift
refs/heads/master
playgrounds/Algorithms.playground/section-1.swift
mit
2
// Playground: Algorithms import Cocoa /** ==== Bubble Sort ==== */ var inputArray = Int[]() func swapNumbers(i1: Int, i2: Int){ let temp = inputArray[i1] inputArray[i1] = inputArray[i2] inputArray[i2] = temp } func bubbleSort(inputArray: Int[]){ for var index: Int = inputArray.count-1; index > 1; --index{ for var j:Int = 0; j < index; ++j{ if inputArray[j] > inputArray[j + 1]{ println("Swapping \(inputArray[j]) with \(inputArray[j+1])") swapNumbers(j, j + 1) } } } } // Generate random numbers func generateRandomValues(){ for r in 0..10{ inputArray.append(((Int(arc4random()))%100)) } } generateRandomValues() // call bubblesort println("Before Bubble sort") inputArray bubbleSort(inputArray) println("After Bubble sort") inputArray println("") /** ==== Selection sort ==== */ inputArray = Int[]() var min: Int = 0 func selectionSort(inputArray: Int[]){ println(inputArray) for var index:Int = 0; index < inputArray.count-1; ++index{ min = index for(var j:Int = index+1; j < inputArray.count-1; ++j){ if inputArray[j] < inputArray[min]{ println("Found new min: \(inputArray[j]). Old min: \(inputArray[min])") println(inputArray) min = j } } swapNumbers(index, min) } } generateRandomValues() println("Before Selection Sort") inputArray selectionSort(inputArray) println("After Selection Sort") inputArray println("") println("") /** ==== Binary Search ==== */ func findItem(searchItem: Int)->Int{ var lowerIndex = 0 var upperIndex = inputArray.count - 1 while(true){ var currentIndex = (lowerIndex + upperIndex) / 2 println("Current Index: \(currentIndex), Value: \(inputArray[currentIndex])") if(inputArray[currentIndex] == searchItem){ println("Found the value!") return currentIndex }else if(lowerIndex > upperIndex){ println("Returning the last element!") return inputArray.count }else if(inputArray[currentIndex] > searchItem){ println("The current index is higher than the search item") upperIndex = currentIndex - 1 }else{ println("The current index is lower than the search item") lowerIndex = currentIndex + 1 } } } inputArray = Int[]() generateRandomValues() println("Selection sort...") selectionSort(inputArray) println("\nBefore Binary Search ") findItem(42) println("End Binary Search")
95a70b4804b9194ae335c2243d3a32cd
23.87619
87
0.604135
false
false
false
false
spark/photon-tinker-ios
refs/heads/master
Photon-Tinker/Mesh/StepPublishDeviceSetupDoneEvent.swift
apache-2.0
1
// // Created by Raimundas Sakalauskas on 2019-03-07. // Copyright (c) 2019 Particle. All rights reserved. // import Foundation class StepPublishDeviceSetupDoneEvent : Gen3SetupStep { //MARK: PublishDeviceSetupDoneEvent override func start() { guard let context = self.context else { return } self.log("publishing device setup done") ParticleCloud.sharedInstance().publishEvent(withName: "mesh-device-setup-complete", data: context.targetDevice.deviceId!, isPrivate: true, ttl: 60) { [weak self, weak context] error in guard let self = self, let context = context, !context.canceled else { return } self.log("stepPublishDeviceSetupDoneEvent error: \(error as Optional)") guard error == nil else { self.fail(withReason: .UnableToPublishDeviceSetupEvent, nsError: error) return } self.stepCompleted() } } }
6a7ed6464275c67e3da303a2484e5229
29.545455
157
0.616071
false
false
false
false
sztoth/PodcastChapters
refs/heads/develop
PodcastChaptersTests/Mocks/MediaLibraryMock.swift
mit
1
// // MediaLibraryMock.swift // PodcastChapters // // Created by Szabolcs Toth on 2016. 10. 06.. // Copyright © 2016. Szabolcs Toth. All rights reserved. // import Cocoa import iTunesLibrary @testable import PodcastChapters class MediaLibraryMock: MediaLibraryType { var allMediaItems: [ITLibMediaItem] { allItemsAccessed = true guard let mockMediaItems = mockMediaItems else { return [ITLibMediaItem]() } return mockMediaItems } var mockMediaItems: [ITLibMediaItemMock]? var mockReloadResponse = true fileprivate(set) var allItemsAccessed = false fileprivate(set) var reloadCalled = false init() { mockMediaItems = [1, 2, 3].map({ ITLibMediaItemMock(identifier: $0) }) } } extension MediaLibraryMock { func reloadData() -> Bool { return mockReloadResponse } }
e943ef35ef2597ade43ec165b2bc62c5
23.314286
84
0.689777
false
false
false
false
A752575700/HOMEWORK
refs/heads/master
CookieCrunch-Swift-Part1/CookieCrunch/GameScene.swift
mit
1
// // GameScene.swift // CookieCrunch // // Created by Matthijs on 19-06-14. // Copyright (c) 2014 Razeware LLC. All rights reserved. // import SpriteKit class GameScene: SKScene { // This is marked as ! because it will not initially have a value, but pretty // soon after the GameScene is created it will be given a Level object, and // from then on it will always have one (it will never be nil again). var level: Level! // The scene handles touches. If it recognizes that the user makes a swipe, // it will call this swipe handler. This is how it communicates back to the // ViewController that a swap needs to take place. You could also use a // delegate for this. var swipeHandler: ((Swap) -> ())? let TileWidth: CGFloat = 32.0 let TileHeight: CGFloat = 36.0 let gameLayer = SKNode() let cookiesLayer = SKNode() let tilesLayer = SKNode() // The column and row numbers of the cookie that the player first touched // when he started his swipe movement. These are marked ? because they may // become nil (meaning no swipe is in progress). var swipeFromColumn: Int? var swipeFromRow: Int? // Sprite that is drawn on top of the cookie that the player is trying to swap. var selectionSprite = SKSpriteNode() // Pre-load the resources let swapSound = SKAction.playSoundFileNamed("Chomp.wav", waitForCompletion: false) let invalidSwapSound = SKAction.playSoundFileNamed("Error.wav", waitForCompletion: false) let matchSound = SKAction.playSoundFileNamed("Ka-Ching.wav", waitForCompletion: false) let fallingCookieSound = SKAction.playSoundFileNamed("Scrape.wav", waitForCompletion: false) let addCookieSound = SKAction.playSoundFileNamed("Drip.wav", waitForCompletion: false) // MARK: Game Setup required init?(coder aDecoder: NSCoder) { fatalError("init(coder) is not used in this app") } override init(size: CGSize) { super.init(size: size) //原始为图片绕左下角点 改为以中心点为中点 anchorPoint = CGPoint(x: 0.5, y: 0.5) // Put an image on the background. Because the scene's anchorPoint is // (0.5, 0.5), the background image will always be centered on the screen. let background = SKSpriteNode(imageNamed: "Background") addChild(background) // Add a new node that is the container for all other layers on the playing // field. This gameLayer is also centered in the screen. addChild(gameLayer) let layerPosition = CGPoint( x: -TileWidth * CGFloat(NumColumns) / 2, y: -TileHeight * CGFloat(NumRows) / 2) // The tiles layer represents the shape of the level. It contains a sprite // node for each square that is filled in. tilesLayer.position = layerPosition gameLayer.addChild(tilesLayer) // This layer holds the Cookie sprites. The positions of these sprites // are relative to the cookiesLayer's bottom-left corner. cookiesLayer.position = layerPosition gameLayer.addChild(cookiesLayer) // nil means that these properties have invalid values. swipeFromColumn = nil swipeFromRow = nil } func addSpritesForCookies(cookies: Set<Cookie>) { for cookie in cookies { // Create a new sprite for the cookie and add it to the cookiesLayer. let sprite = SKSpriteNode(imageNamed: cookie.cookieType.spriteName) sprite.position = pointForColumn(cookie.column, row:cookie.row) cookiesLayer.addChild(sprite) cookie.sprite = sprite } } func addTiles() { for row in 0..<NumRows { for column in 0..<NumColumns { // If there is a tile at this position, then create a new tile // sprite and add it to the mask layer. if let tile = level.tileAtColumn(column, row: row) { let tileNode = SKSpriteNode(imageNamed: "Tile") tileNode.position = pointForColumn(column, row: row) tilesLayer.addChild(tileNode) } } } } // MARK: Conversion Routines // Converts a column,row pair into a CGPoint that is relative to the cookieLayer. func pointForColumn(column: Int, row: Int) -> CGPoint { return CGPoint( x: CGFloat(column)*TileWidth + TileWidth/2, y: CGFloat(row)*TileHeight + TileHeight/2) } // Converts a point relative to the cookieLayer into column and row numbers. func convertPoint(point: CGPoint) -> (success: Bool, column: Int, row: Int) { // Is this a valid location within the cookies layer? If yes, // calculate the corresponding row and column numbers. if point.x >= 0 && point.x < CGFloat(NumColumns)*TileWidth && point.y >= 0 && point.y < CGFloat(NumRows)*TileHeight { return (true, Int(point.x / TileWidth), Int(point.y / TileHeight)) } else { return (false, 0, 0) // invalid location } } // MARK: Detecting Swipes override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { // Convert the touch location to a point relative to the cookiesLayer. let touch = touches.first as! UITouch let location = touch.locationInNode(cookiesLayer) // If the touch is inside a square, then this might be the start of a // swipe motion. let (success, column, row) = convertPoint(location) if success { // The touch must be on a cookie, not on an empty tile. if let cookie = level.cookieAtColumn(column, row: row) { // Remember in which column and row the swipe started, so we can compare // them later to find the direction of the swipe. This is also the first // cookie that will be swapped. swipeFromColumn = column swipeFromRow = row println(swipeFromColumn) showSelectionIndicatorForCookie(cookie) } } } override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { // If swipeFromColumn is nil then either the swipe began outside // the valid area or the game has already swapped the cookies and we need // to ignore the rest of the motion. if swipeFromColumn == nil { return } let touch = touches.first as! UITouch let location = touch.locationInNode(cookiesLayer) let (success, column, row) = convertPoint(location) if success { // Figure out in which direction the player swiped. Diagonal swipes // are not allowed. var horzDelta = 0, vertDelta = 0 if column < swipeFromColumn! { // swipe left horzDelta = -1 } else if column > swipeFromColumn! { // swipe right horzDelta = 1 } else if row < swipeFromRow! { // swipe down vertDelta = -1 } else if row > swipeFromRow! { // swipe up vertDelta = 1 } // Only try swapping when the user swiped into a new square. if horzDelta != 0 || vertDelta != 0 { trySwapHorizontal(horzDelta, vertical: vertDelta) hideSelectionIndicator() // Ignore the rest of this swipe motion from now on. swipeFromColumn = nil } } } // We get here after the user performs a swipe. This sets in motion a whole // chain of events: 1) swap the cookies, 2) remove the matching lines, 3) // drop new cookies into the screen, 4) check if they create new matches, // and so on. func trySwapHorizontal(horzDelta: Int, vertical vertDelta: Int) { let toColumn = swipeFromColumn! + horzDelta let toRow = swipeFromRow! + vertDelta // Going outside the bounds of the array? This happens when the user swipes // over the edge of the grid. We should ignore such swipes. if toColumn < 0 || toColumn >= NumColumns { return } if toRow < 0 || toRow >= NumRows { return } // Can't swap if there is no cookie to swap with. This happens when the user // swipes into a gap where there is no tile. if let toCookie = level.cookieAtColumn(toColumn, row: toRow), let fromCookie = level.cookieAtColumn(swipeFromColumn!, row: swipeFromRow!), let handler = swipeHandler { // Communicate this swap request back to the ViewController. let swap = Swap(cookieA: fromCookie, cookieB: toCookie) handler(swap) } } override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { // Remove the selection indicator with a fade-out. We only need to do this // when the player didn't actually swipe. if selectionSprite.parent != nil && swipeFromColumn != nil { hideSelectionIndicator() } // If the gesture ended, regardless of whether if was a valid swipe or not, // reset the starting column and row numbers. swipeFromColumn = nil swipeFromRow = nil } override func touchesCancelled(touches: Set<NSObject>, withEvent event: UIEvent) { touchesEnded(touches, withEvent: event) } // MARK: Animations func animateSwap(swap: Swap, completion: () -> ()) { let spriteA = swap.cookieA.sprite! let spriteB = swap.cookieB.sprite! // Put the cookie you started with on top. spriteA.zPosition = 100 spriteB.zPosition = 90 let Duration: NSTimeInterval = 0.3 let moveA = SKAction.moveTo(spriteB.position, duration: Duration) moveA.timingMode = .EaseOut spriteA.runAction(moveA, completion: completion) let moveB = SKAction.moveTo(spriteA.position, duration: Duration) moveB.timingMode = .EaseOut spriteB.runAction(moveB) runAction(swapSound) } func animateInvalidSwap(swap: Swap, completion: () -> ()) { let spriteA = swap.cookieA.sprite! let spriteB = swap.cookieB.sprite! spriteA.zPosition = 100 spriteB.zPosition = 90 let Duration: NSTimeInterval = 0.2 let moveA = SKAction.moveTo(spriteB.position, duration: Duration) moveA.timingMode = .EaseOut let moveB = SKAction.moveTo(spriteA.position, duration: Duration) moveB.timingMode = .EaseOut spriteA.runAction(SKAction.sequence([moveA, moveB]), completion: completion) spriteB.runAction(SKAction.sequence([moveB, moveA])) runAction(invalidSwapSound) } // MARK: Selection Indicator func showSelectionIndicatorForCookie(cookie: Cookie) { // If the selection indicator is still visible, then first remove it. if selectionSprite.parent != nil { selectionSprite.removeFromParent() } // Add the selection indicator as a child to the cookie that the player // tapped on and fade it in. Note: simply setting the texture on the sprite // doesn't give it the correct size; using an SKAction does. if let sprite = cookie.sprite { let texture = SKTexture(imageNamed: cookie.cookieType.highlightedSpriteName) selectionSprite.size = texture.size() selectionSprite.runAction(SKAction.setTexture(texture)) sprite.addChild(selectionSprite) selectionSprite.alpha = 1.0 } } func hideSelectionIndicator() { selectionSprite.runAction(SKAction.sequence([ SKAction.fadeOutWithDuration(0.3), SKAction.removeFromParent()])) } }
a33435529280b4f801d26734a15696c3
34.748366
94
0.682604
false
false
false
false
laszlokorte/reform-swift
refs/heads/master
ReformTools/ReformTools/Input.swift
mit
1
// // Input.swift // ReformTools // // Created by Laszlo Korte on 17.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // import ReformMath public struct Modifier : OptionSet { public let rawValue : Int public init(rawValue: Int) { self.rawValue = rawValue } public static let Streight = Modifier(rawValue: 1) public static let AlternativeAlignment = Modifier(rawValue: 2) public static let Glomp = Modifier(rawValue: 4) public static let Free = Modifier(rawValue: 8) } public func ==(lhs: Modifier, rhs: Modifier) -> Bool { return lhs.rawValue == rhs.rawValue } extension Modifier { var isStreight : Bool { return contains(Modifier.Streight) } var isAlignOption : Bool { return contains(Modifier.AlternativeAlignment) } } public enum Input { case move case press case release case cycle case toggle case modifierChange }
53733774f8bb7e30ef59475cc39903c4
19.425532
66
0.657292
false
false
false
false
IngmarStein/swift
refs/heads/master
validation-test/compiler_crashers_fixed/01669-void.swift
apache-2.0
11
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse import Foundation protocol b : C: (s: String { func a(a: AnyObject, let b in c == " protocol b : A { typealias B : c, B>() { var _ = g: A, Any, let v: d == d.init()" protocol A : A(a)
4d7663d954c4e992d5e33e83d48215cd
37.4
78
0.696181
false
false
false
false
merlos/iOS-Open-GPX-Tracker
refs/heads/master
Pods/CoreGPX/Classes/GPXPoint.swift
gpl-3.0
1
// // GPXPoint.swift // GPXKit // // Created by Vincent on 23/11/18. // import Foundation /** * This class (`ptType`) is added to conform with the GPX v1.1 schema. `ptType` of GPX schema. Not supported in GPXRoot, nor GPXParser's parsing. */ open class GPXPoint: GPXElement, Codable { /// Elevation Value in (metre, m) public var elevation: Double? /// Time/Date of creation public var time: Date? /// Latitude of point public var latitude: Double? /// Longitude of point public var longitude: Double? // MARK:- Instance /// Default Initializer. required public init() { super.init() } /// Initialize with latitude and longitude public init(latitude: Double, longitude: Double) { super.init() self.latitude = latitude self.longitude = longitude } /// Inits native element from raw parser value /// /// - Parameters: /// - raw: Raw element expected from parser init(raw: GPXRawElement) { self.latitude = Convert.toDouble(from: raw.attributes["lat"]) self.longitude = Convert.toDouble(from: raw.attributes["lon"]) for child in raw.children { switch child.name { case "ele": self.elevation = Convert.toDouble(from: child.text) case "time": self.time = GPXDateParser().parse(date: child.text) default: continue } } } // MARK:- Tag override func tagName() -> String { return "pt" } // MARK: GPX override func addOpenTag(toGPX gpx: NSMutableString, indentationLevel: Int) { let attribute = NSMutableString(string: "") if let latitude = latitude { attribute.append(" lat=\"\(latitude)\"") } if let longitude = longitude { attribute.append(" lon=\"\(longitude)\"") } gpx.appendOpenTag(indentation: indent(forIndentationLevel: indentationLevel), tag: tagName(), attribute: attribute) } override func addChildTag(toGPX gpx: NSMutableString, indentationLevel: Int) { super.addChildTag(toGPX: gpx, indentationLevel: indentationLevel) self.addProperty(forDoubleValue: elevation, gpx: gpx, tagName: "ele", indentationLevel: indentationLevel) self.addProperty(forValue: Convert.toString(from: time), gpx: gpx, tagName: "time", indentationLevel: indentationLevel) } }
7fe36b40708d777f66c46cb882ed7c8e
29.170732
127
0.613581
false
false
false
false
lightbluefox/rcgapp
refs/heads/master
IOS App/RCGApp/RCGApp/VacancyViewController.swift
gpl-2.0
1
// // VacancyViewController.swift // RCGApp // // Created by iFoxxy on 12.05.15. // Copyright (c) 2015 LightBlueFox. All rights reserved. // import UIKit class VacancyViewController: UIViewController { var fullTextImageURL: String? var maleImg: UIImage! var femaleImg: UIImage! var createdDate: String? var heading: String? var announcement: String? var fullText: String? var rate: String? var vacancyId: Int? @IBOutlet weak var vacancyScrollView: UIScrollView! @IBAction func vacancyRespondButton(sender: AnyObject) { } @IBOutlet weak var vacancyFullTextImage: UIImageView! @IBOutlet weak var vacancyMaleImg: UIImageView! @IBOutlet weak var vacancyFemaleImg: UIImageView! @IBOutlet weak var vacancyCreatedDate: UILabel! @IBOutlet weak var vacancyTitle: UILabel! @IBOutlet weak var vacancyAnnouncement: UILabel! @IBOutlet weak var vacancyRate: UILabel! @IBOutlet weak var vacancyFullText: UILabel! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "ВАКАНСИЯ" let buttonBack: UIButton = UIButton.buttonWithType(.Custom) as! UIButton; buttonBack.frame = CGRectMake(0, 0, 40, 40); buttonBack.setImage(UIImage(named: "backButton"), forState: .Normal); buttonBack.addTarget(self, action: "leftNavButtonClick:", forControlEvents: UIControlEvents.TouchUpInside); var leftBarButtonItem: UIBarButtonItem = UIBarButtonItem(customView: buttonBack); self.navigationItem.setLeftBarButtonItem(leftBarButtonItem, animated: false); vacancyTitle.text = heading! vacancyAnnouncement.text = announcement! if fullTextImageURL != nil && fullTextImageURL != "" { vacancyFullTextImage.sd_setImageWithURL(NSURL(string: fullTextImageURL!)) vacancyFullTextImage.layer.cornerRadius = 5.0 vacancyFullTextImage.layer.masksToBounds = true } vacancyMaleImg.image = maleImg; vacancyFemaleImg.image = femaleImg; vacancyCreatedDate.text = createdDate; vacancyRate.text = rate; vacancyFullText.text = fullText; } func leftNavButtonClick(sender: UIButton!) { self.navigationController?.popViewControllerAnimated(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. var vacancyRespondFormViewController = segue.destinationViewController as! VacancyRespondFormViewController // Pass the selected object to the new view controller. vacancyRespondFormViewController.vacancyId = vacancyId } }
8e34cf479b56d58c572ec76052cbe98a
34.767442
115
0.695059
false
false
false
false
Hodglim/hacking-with-swift
refs/heads/master
Project-18/iAds/ViewController.swift
mit
1
// // ViewController.swift // iAds // // Created by Darren Hodges on 24/06/2016. // Copyright © 2016 Darren Hodges. All rights reserved. // import UIKit import iAd class ViewController: UIViewController, ADBannerViewDelegate { var bannerView: ADBannerView! override func viewDidLoad() { super.viewDidLoad() bannerView = ADBannerView(adType: .Banner) bannerView.translatesAutoresizingMaskIntoConstraints = false bannerView.delegate = self bannerView.hidden = true view.addSubview(bannerView) let viewsDictionary = ["bannerView": bannerView] view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[bannerView]|", options: [], metrics: nil, views: viewsDictionary)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[bannerView]|", options: [], metrics: nil, views: viewsDictionary)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func bannerViewDidLoadAd(banner: ADBannerView!) { bannerView.hidden = false } func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) { bannerView.hidden = true } }
ed65eb498ed8584ec7c914dcf871b154
24.468085
140
0.756892
false
false
false
false
Ben21hao/edx-app-ios-new
refs/heads/master
Source/TDUserCenterViewController/Views/TDUserCenterView.swift
apache-2.0
1
// // TDUserCenterView.swift // edX // // Created by Elite Edu on 17/4/14. // Copyright © 2017年 edX. All rights reserved. // import UIKit class TDUserCenterView: UIView,UITableViewDataSource { internal let tableView = UITableView() internal var score = Double()//宝典 internal var statusCode = Int() //认证状态 400 未认证,200 提交成功 ,201 已认证,202 认证失败 internal var coupons = Double()//优惠券 internal var orders = Double()//订单 private let toolModel = TDBaseToolModel.init() private var isHidePuchase = true //默认隐藏内购 typealias clickHeaderImageBlock = () -> () var clickHeaderImageHandle : clickHeaderImageBlock? var userProfile: UserProfile? var networkManager: NetworkManager? override init(frame: CGRect) { super.init(frame: frame) setViewConstraint() toolModel.showPurchase() toolModel.judHidePurchseHandle = {(isHide:Bool?)in //yes 不用内购;no 使用内购 self.isHidePuchase = isHide! } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: UI func setViewConstraint() { self.backgroundColor = OEXStyles.sharedStyles().baseColor5() self.tableView.backgroundColor = OEXStyles.sharedStyles().baseColor6() self.tableView.tableFooterView = UIView.init() self.tableView.dataSource = self self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0) self.addSubview(self.tableView) self.tableView.snp_makeConstraints { (make) in make.left.right.top.bottom.equalTo(self) } } func populateFields(profile: UserProfile, editable : Bool, networkManager : NetworkManager) { //认证状态 -- 400 未认证,200 提交成功 ,201 已认证,202 认证失败 statusCode = profile.statusCode! self.userProfile = profile self.networkManager = networkManager self.score = profile.remainscore! //学习宝典 self.coupons = profile.coupon! //优惠券 self.orders = profile.order! //未支付订单 self.tableView.reloadData() } //MARK: tableview Datasource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 3 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 1 } else if section == 1 { if self.isHidePuchase == true { return 3 } else { return 1 } } else { return 2 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //邮箱或手机 let baseTool = TDBaseToolModel.init() if indexPath.section == 0 { let cell = TDUserMessageCell.init(style: .Default, reuseIdentifier: "UserMessageCell") cell.accessoryType = .DisclosureIndicator cell.selectionStyle = .None let tap = UITapGestureRecognizer.init(target: self, action: #selector(gotoAuthenVc)) cell.headerImageView.addGestureRecognizer(tap) if self.userProfile != nil { //用户名 if self.userProfile!.nickname != nil { cell.nameLabel.text = self.userProfile!.nickname } else { if self.userProfile!.name != self.userProfile!.username { cell.nameLabel.text = self.userProfile!.name } else { cell.nameLabel.text = Strings.noName } } if self.userProfile!.phone != nil { let newStr = baseTool.setPhoneStyle(self.userProfile!.phone) cell.acountLabel.text = newStr } else { let newStr = baseTool.setEmailStyle(self.userProfile!.email) cell.acountLabel.text = newStr } if self.networkManager != nil { cell.headerImageView.remoteImage = self.userProfile?.image(self.networkManager!) } if statusCode == 400 || statusCode == 202 { cell.statusLabel.text = Strings.tdUnvertified cell.statusLabel.backgroundColor = OEXStyles.sharedStyles().baseColor6() cell.statusLabel.textColor = OEXStyles.sharedStyles().baseColor8() } else if statusCode == 200 { cell.statusLabel.text = Strings.tdProcessing cell.statusLabel.backgroundColor = OEXStyles.sharedStyles().baseColor2() cell.statusLabel.textColor = UIColor.whiteColor() } else if statusCode == 201 { cell.statusLabel.text = Strings.tdVertified cell.statusLabel.backgroundColor = OEXStyles.sharedStyles().baseColor4() cell.statusLabel.textColor = UIColor.whiteColor() } } return cell } else { let cell = TDUserCeterCell.init(style: .Default, reuseIdentifier: "UserCenterCell") cell.accessoryType = .DisclosureIndicator var imageStr : String var titleStr : String if indexPath.section == 1 { switch indexPath.row { case 0: titleStr = Strings.studyCoins cell.messageLabel.attributedText = baseTool.setDetailString(Strings.nowHave(count: String(format: "%.2f",score)), withFont: 12, withColorStr: "#A7A4A4") imageStr = "baodian" case 1: titleStr = Strings.couponPaper cell.messageLabel.text = Strings.couponNumber(count:String(format: "%.0f",coupons)) imageStr = "coupons" default: titleStr = Strings.courseOrder cell.messageLabel.text = Strings.orderCount(count: String(format: "%.0f",orders)) imageStr = "Page" } } else { switch indexPath.row { case 0: titleStr = "讲座" cell.messageLabel.text = "讲座预约报名" imageStr = "lecture_image" default: titleStr = "助教服务" cell.messageLabel.text = "助教服务订单列表" imageStr = "assistant_image" } } cell.titleLabel.text = titleStr cell.iconImageView.image = UIImage.init(named: imageStr) return cell } } func gotoAuthenVc() { if (clickHeaderImageHandle != nil) { clickHeaderImageHandle!() } } }
14ed12fb9538341181f5f8548cd0e4b4
35.546392
172
0.541185
false
false
false
false
skedgo/tripkit-ios
refs/heads/main
Sources/TripKit/model/API/RoutingAPIModel.swift
apache-2.0
1
// // RoutingAPIModel.swift // TripKit // // Created by Adrian Schönig on 6/8/21. // Copyright © 2021 SkedGo Pty Ltd. All rights reserved. // import Foundation import CoreLocation extension TKAPI { public struct RoutingResponse: Codable { public let error: String? public var segmentTemplates: [SegmentTemplate]? @DefaultEmptyArray public var alerts: [Alert] public let groups: [TripGroup]? public let query: Query? } public struct Query: Codable, Hashable { public let from: TKNamedCoordinate public let to: TKNamedCoordinate @OptionalISO8601OrSecondsSince1970 public var depart: Date? @OptionalISO8601OrSecondsSince1970 public var arrive: Date? } public struct TripGroup: Codable, Hashable { public let trips: [Trip] public var frequency: Int? @DefaultEmptyArray public var sources: [DataAttribution] } public struct Trip: Codable, Hashable { @ISO8601OrSecondsSince1970 public var depart: Date @ISO8601OrSecondsSince1970 public var arrive: Date @DefaultFalse public var hideExactTimes: Bool public let mainSegmentHashCode: Int public let segments: [SegmentReference] public let caloriesCost: Double public let carbonCost: Double public let hassleCost: Double public let weightedScore: Double public var moneyCost: Double? public var moneyCostUSD: Double? public var currency: String? public var budgetPoints: Double? public var bundleId: String? public var saveURL: URL? public var shareURL: URL? public var temporaryURL: URL? public var updateURL: URL? public var progressURL: URL? public var plannedURL: URL? public var logURL: URL? @UnknownNil public var availability: TripAvailability? } public enum TripAvailability: String, Codable, Hashable { case missedPrebookingWindow = "MISSED_PREBOOKING_WINDOW" case canceled = "CANCELLED" } public struct SegmentReference: Codable, Hashable { public let segmentTemplateHashCode: Int @ISO8601OrSecondsSince1970 public var startTime: Date @ISO8601OrSecondsSince1970 public var endTime: Date @DefaultFalse public var timesAreRealTime: Bool @DefaultEmptyArray public var alertHashCodes: [Int] var booking: BookingData? public var bookingHashCode: Int? // Public transport public var serviceTripID: String? public var serviceColor: RGBColor? public var frequency: Int? public var lineName: String? public var direction: String? public var number: String? @DefaultFalse public var bicycleAccessible: Bool public var wheelchairAccessible: Bool? // `nil` means unknown public var startPlatform: String? public var endPlatform: String? public var serviceStops: Int? @UnknownNil public var ticketWebsite: URL? // Backend might send empty string, which is not a valid URL public var ticket: TKSegment.Ticket? @OptionalISO8601OrSecondsSince1970 public var timetableStartTime: Date? @OptionalISO8601OrSecondsSince1970 public var timetableEndTime: Date? @UnknownNil public var realTimeStatus: RealTimeStatus? // PT and non-PT public var realTimeVehicle: Vehicle? @DefaultEmptyArray public var realTimeVehicleAlternatives: [Vehicle] @UnknownNil public var sharedVehicle: TKAPI.SharedVehicleInfo? public var vehicleUUID: String? enum CodingKeys: String, CodingKey { case segmentTemplateHashCode case startTime case endTime case timesAreRealTime = "realTime" case alertHashCodes case booking case bookingHashCode case serviceTripID case serviceColor case frequency case lineName = "serviceName" case direction = "serviceDirection" case number = "serviceNumber" case bicycleAccessible case wheelchairAccessible case startPlatform case endPlatform case serviceStops = "stops" case ticketWebsite = "ticketWebsiteURL" case ticket case timetableStartTime case timetableEndTime case realTimeStatus case realTimeVehicle = "realtimeVehicle" case realTimeVehicleAlternatives = "realtimeVehicleAlternatives" case sharedVehicle case vehicleUUID } } public struct SegmentTemplate: Codable, Hashable { public let hashCode: Int public let type: SegmentType public let visibility: SegmentVisibility public let modeIdentifier: String? public let modeInfo: TKModeInfo? public let action: String? public var notes: String? @UnknownNil public var localCost: TKLocalCost? // Backend is sometimes sending this invalid without currency as of 2021-08-17 var mini: TKMiniInstruction? @DefaultFalse var hideExactTimes: Bool // stationary public var location: TKNamedCoordinate? @DefaultFalse public var hasCarParks: Bool // moving public var bearing: Int? public var from: TKNamedCoordinate? public var to: TKNamedCoordinate? // moving.unscheduled public var metres: CLLocationDistance? public var metresSafe: CLLocationDistance? public var metresUnsafe: CLLocationDistance? public var metresDismount: CLLocationDistance? public var durationWithoutTraffic: TimeInterval? public var mapTiles: TKMapTiles? @UnknownNil public var turnByTurn: TKTurnByTurnMode? public var streets: [SegmentShape]? // moving.scheduled public var stopCode: String? // scheduledStartStopCode public var endStopCode: String? public var operatorName: String? public var operatorID: String? @DefaultFalse public var isContinuation: Bool public var shapes: [SegmentShape]? enum CodingKeys: String, CodingKey { case hashCode case type case visibility case modeIdentifier case modeInfo case action case notes case metres case metresSafe case metresUnsafe case metresDismount case durationWithoutTraffic case bearing = "travelDirection" case localCost case mapTiles case mini case hideExactTimes case turnByTurn = "turn-by-turn" case streets case stopCode case endStopCode case operatorName = "operator" case operatorID case isContinuation case hasCarParks case location case from case to case shapes } } public enum SegmentVisibility: String, Codable, Hashable { case inSummary = "in summary" case onMap = "on map" case inDetails = "in details" case hidden var tkVisibility: TKTripSegmentVisibility { switch self { case .inSummary: return .inSummary case .onMap: return .onMap case .inDetails: return .inDetails case .hidden: return .hidden } } } public enum SegmentType: String, Codable, Hashable { case scheduled case unscheduled case stationary var tkType: TKSegmentType { switch self { case .stationary: return .stationary case .scheduled: return .scheduled case .unscheduled: return .unscheduled } } } public struct SegmentShape: Codable, Hashable { public let encodedWaypoints: String public var modeInfo: TKModeInfo? @DefaultTrue public var travelled: Bool // scheduled public var serviceTripID: String? public var serviceColor: RGBColor? public var frequency: Int? public var lineName: String? public var direction: String? public var number: String? @DefaultFalse public var bicycleAccessible: Bool public var wheelchairAccessible: Bool? public var operatorName: String? public var operatorID: String? @DefaultEmptyArray public var stops: [TKAPI.ShapeStop] // unscheduled public var name: String? @DefaultFalse public var dismount: Bool @DefaultFalse public var hop: Bool public var metres: CLLocationDistance? public var cyclingNetwork: String? public var safe: Bool? @UnknownNil public var instruction: ShapeInstruction? @EmptyLossyArray @LossyArray public var roadTags: [Shape.RoadTag] enum CodingKeys: String, CodingKey { case encodedWaypoints case modeInfo case travelled case serviceTripID case serviceColor case frequency case lineName = "serviceName" case direction = "serviceDirection" case number = "serviceNumber" case bicycleAccessible case wheelchairAccessible case operatorName = "operator" case operatorID case stops case name case dismount case hop case metres case cyclingNetwork case safe case instruction case roadTags } } public struct ShapeStop: Codable, Hashable { public let lat: CLLocationDegrees public let lng: CLLocationDegrees public let code: String public let name: String public let shortName: String? @OptionalISO8601OrSecondsSince1970 public var arrival: Date? @OptionalISO8601OrSecondsSince1970 public var departure: Date? public var relativeArrival: TimeInterval? public var relativeDeparture: TimeInterval? public var bearing: Int? public let wheelchairAccessible: Bool? } public enum ShapeInstruction: String, Codable { case headTowards = "HEAD_TOWARDS" case continueStraight = "CONTINUE_STRAIGHT" case turnSlightyLeft = "TURN_SLIGHTLY_LEFT" case turnLeft = "TURN_LEFT" case turnSharplyLeft = "TURN_SHARPLY_LEFT" case turnSlightlyRight = "TURN_SLIGHTLY_RIGHT" case turnRight = "TURN_RIGHT" case turnSharplyRight = "TURN_SHARPLY_RIGHT" } }
4870e80a21a60426213246f506a47451
29.622642
129
0.702403
false
false
false
false
joakim666/chainbuilderapp
refs/heads/master
chainbuilder/ShareViewModel.swift
apache-2.0
1
// // ShareViewModel.swift // chainbuilder // // Created by Joakim Ek on 2017-06-19. // Copyright © 2017 Morrdusk. All rights reserved. // import UIKit /** * The View model for the sharing action, where a chain is exported as a CSV-file. */ class ShareViewModel { let excludedActivityTypes = [UIActivityType.addToReadingList] var chain: Chain? var shareMode = false var fileURL: URL? func shareChain(_ chain: Chain?) { shareMode = true self.chain = chain } func sharedFileURL() -> URL? { guard let chain = self.chain else { log.error("No chain to export!") return nil } let df = DateFormatter() df.timeStyle = DateFormatter.Style.none df.dateStyle = DateFormatter.Style.short var csvData = "" // add header csvData = csvData.appending("Marked dates\n") // add the marked dates for the chosen chain for date in chain.days { if let d = date.date { csvData = csvData.appending(df.string(from: d)) csvData = csvData.appending("\n") } } let fileName = "export" // name of output file without the extension let docDir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) if let fileURL = docDir?.appendingPathComponent(fileName).appendingPathExtension("csv") { do { try csvData.write(to: fileURL, atomically: true, encoding: .utf8) log.debug("CSV: \(csvData)") } catch let error as NSError { log.error("Failed to export csv to: \(fileURL) due to: " + error.localizedDescription) } self.fileURL = fileURL return fileURL } else { log.error("Failed to create csv export file") self.fileURL = nil return nil } } func completed() { shareMode = false // Do not remove the created csv file here because if we do that, the deletion will occur before // the application targeted for the share action gets a chance to read the file } }
c973c0e19eafc7d15242b67587ad39f5
28.291139
130
0.567848
false
false
false
false