repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
younata/RSSClient
TethysAppSpecs/Easter Eggs/EasterEggGalleryViewControllerSpec.swift
1
3299
import Quick import Nimble @testable import Tethys final class EasterEggGalleryViewControllerSpec: QuickSpec { override func spec() { var subject: EasterEggGalleryViewController! var easterEggVC1: UIViewController! var easterEggVC2: UIViewController! let easterEggs = [ EasterEgg(name: "test 1", image: UIImage(named: "GrayIcon")!, viewController: { easterEggVC1 }), EasterEgg(name: "test 2", image: UIImage(named: "Checkmark")!, viewController: { easterEggVC2 }) ] beforeEach { easterEggVC1 = UIViewController() easterEggVC2 = UIViewController() subject = EasterEggGalleryViewController(easterEggs: easterEggs) subject.view.layoutIfNeeded() } it("titles itself") { expect(subject.title).to(equal("Easter Eggs")) } describe("the collection view") { it("has an item for each easter egg") { expect(subject.collectionView.numberOfSections).to(equal(1)) expect(subject.collectionView.numberOfItems(inSection: 0)).to(equal(easterEggs.count)) } it("is configured with the theme") { expect(subject.collectionView.backgroundColor).to(equal(Theme.backgroundColor)) expect(subject.view.backgroundColor).to(equal(Theme.backgroundColor)) } describe("a cell") { var cell: CollectionViewCell? let indexPath = IndexPath(item: 0, section: 0) beforeEach { guard subject.collectionView.numberOfSections == 1, subject.collectionView.numberOfItems(inSection: 0) == easterEggs.count else { return } cell = subject.collectionView.cellForItem(at: indexPath) as? CollectionViewCell } it("displays information about the easter egg") { expect(cell?.imageView.image).to(equal(UIImage(named: "GrayIcon"))) expect(cell?.label.text).to(equal("test 1")) } it("is themed properly") { expect(cell?.label.textColor).to(equal(Theme.textColor)) expect(cell?.backgroundColor).to(equal(Theme.overlappingBackgroundColor)) expect(cell?.layer.cornerRadius).to(equal(4)) } it("is configured for accessibility") { expect(cell?.accessibilityLabel).to(equal("test 1")) expect(cell?.accessibilityTraits).to(equal([.button])) } } describe("selecting a cell") { let indexPath = IndexPath(item: 0, section: 0) beforeEach { subject.collectionView.delegate?.collectionView?(subject.collectionView, didSelectItemAt: indexPath) } it("presents the easter egg's view controller") { expect(subject.presentedViewController).to(equal(easterEggVC1)) expect(subject.presentedViewController?.modalPresentationStyle).to(equal(.fullScreen)) } } } } }
mit
535ada0c561babd48268c87dbc4b7801
37.360465
120
0.565929
5.21169
false
true
false
false
Urinx/SublimeCode
Sublime/Sublime/Utils/ShareToWeixin.swift
1
6198
// // ShareToWeixin.swift // Sublime // // Created by Eular on 2/18/16. // Copyright © 2016 Eular. All rights reserved. // import UIKit import Foundation // MARK: - 微信分享 extension UIViewController { // MARK: - 分享链接 func WXShareLink(title: String, desc: String, img: String, link: String, isTimeline: Bool = false) { if WXApi.isWXAppInstalled() { let message = WXMediaMessage() message.title = title message.description = desc message.setThumbImage(UIImage(named: img)) let ext = WXWebpageObject() ext.webpageUrl = link message.mediaObject = ext let req = SendMessageToWXReq() req.bText = false req.message = message req.scene = isTimeline ? Int32(WXSceneTimeline.rawValue) : Int32(WXSceneSession.rawValue) WXApi.sendReq(req) } else { _WXIsNotInstallAlert() } } // MARK: - 分享图片 func WXShareImage(image: UIImage, isTimeline: Bool = false) { if WXApi.isWXAppInstalled() { let message = WXMediaMessage() let imageObject = WXImageObject() imageObject.imageData = UIImagePNGRepresentation(image) message.mediaObject = imageObject //图片缩略图 let width: CGFloat = 240 let height = width * image.size.height / image.size.width UIGraphicsBeginImageContext(CGSizeMake(width, height)) image.drawInRect(CGRectMake(0, 0, width, height)) message.setThumbImage(UIGraphicsGetImageFromCurrentImageContext()) UIGraphicsEndImageContext() let req = SendMessageToWXReq() req.bText = false req.message = message req.scene = isTimeline ? Int32(WXSceneTimeline.rawValue) : Int32(WXSceneSession.rawValue) WXApi.sendReq(req) } else { _WXIsNotInstallAlert() } } // MARK: - 分享文字 func WXShareText(text: String, isTimeline: Bool = false) { if WXApi.isWXAppInstalled() { let req = SendMessageToWXReq() req.bText = true req.text = text req.scene = isTimeline ? Int32(WXSceneTimeline.rawValue) : Int32(WXSceneSession.rawValue) WXApi.sendReq(req) } else { _WXIsNotInstallAlert() } } // MARK: - 分享音乐 func WXShareMusic(name: String, singer: String, img: String, url: String, isTimeline: Bool = false) { if WXApi.isWXAppInstalled() { let message = WXMediaMessage() message.title = name message.description = singer message.setThumbImage(UIImage(named: img)) let music = WXMusicObject() music.musicUrl = url music.musicDataUrl = url message.mediaObject = music let req = SendMessageToWXReq() req.bText = false req.message = message req.scene = isTimeline ? Int32(WXSceneTimeline.rawValue) : Int32(WXSceneSession.rawValue) WXApi.sendReq(req) } else { _WXIsNotInstallAlert() } } // MARK: - 分享视频 func WXShareVideo(title: String, desc: String, img: String, url: String, isTimeline: Bool = false) { if WXApi.isWXAppInstalled() { let message = WXMediaMessage() message.title = title message.description = desc message.setThumbImage(UIImage(named: img)) let video = WXVideoObject() video.videoUrl = url message.mediaObject = video let req = SendMessageToWXReq() req.bText = false req.message = message req.scene = isTimeline ? Int32(WXSceneTimeline.rawValue) : Int32(WXSceneSession.rawValue) WXApi.sendReq(req) } else { _WXIsNotInstallAlert() } } // MARK: - 分享表情,包括gif func WXShareEmoticon(emotPath: String, isTimeline: Bool = false) { if WXApi.isWXAppInstalled() { let message = WXMediaMessage() message.setThumbImage(UIImage(contentsOfFile: emotPath)) let emot = WXEmoticonObject() emot.emoticonData = NSData(contentsOfFile: emotPath) message.mediaObject = emot let req = SendMessageToWXReq() req.bText = false req.message = message req.scene = isTimeline ? Int32(WXSceneTimeline.rawValue) : Int32(WXSceneSession.rawValue) WXApi.sendReq(req) } else { _WXIsNotInstallAlert() } } // MARK: - 分享文件 func WXShareFile(title: String, desc: String, file: File, isTimeline: Bool = false) { if WXApi.isWXAppInstalled() { let message = WXMediaMessage() message.title = title message.description = desc message.setThumbImage(UIImage(named: file.img)) let fobj = WXFileObject() fobj.fileExtension = file.ext fobj.fileData = file.data message.mediaObject = fobj let req = SendMessageToWXReq() req.bText = false req.message = message req.scene = isTimeline ? Int32(WXSceneTimeline.rawValue) : Int32(WXSceneSession.rawValue) WXApi.sendReq(req) } else { _WXIsNotInstallAlert() } } func WXLogin() { let req: SendAuthReq = SendAuthReq() req.scope = "snsapi_userinfo,snsapi_base" WXApi.sendReq(req) } // MARK: - 私有方法 private func _WXIsNotInstallAlert() { let alert = UIAlertController(title: "Share Fail", message: "Wechat app is not installed!", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(alert, animated: true, completion: nil) } }
gpl-3.0
f82e5c3dd88270f8d9757e796a24914d
34.114943
123
0.567851
4.505162
false
false
false
false
Bluthwort/Bluthwort
Sources/Classes/Style/WKWebViewStyle.swift
1
2441
// // WKWebViewStyle.swift // // Copyright (c) 2018 Bluthwort // // 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 WebKit extension Bluthwort where Base: WKWebView { @discardableResult public func customUserAgent(_ agent: String?) -> Bluthwort { // The custom user agent string. base.customUserAgent = agent return self } @discardableResult public func navigationDelegate(_ delegate: WKNavigationDelegate?) -> Bluthwort { // The web view's navigation delegate. base.navigationDelegate = delegate return self } @discardableResult public func uiDelegate(_ delegate: WKUIDelegate?) -> Bluthwort { // The web view's user interface delegate. base.uiDelegate = delegate return self } @discardableResult public func allowsBackForwardNavigationGestures(_ flag: Bool) -> Bluthwort { // A Boolean value indicating whether horizontal swipe gestures will trigger back-forward // list navigations. base.allowsBackForwardNavigationGestures = flag return self } @discardableResult public func allowsLinkPreview(_ flag: Bool) -> Bluthwort { // A Boolean value that determines whether pressing on a link displays a preview of the // destination for the link. base.allowsLinkPreview = flag return self } }
mit
09fdda2fb2d5236a2c40fff29d656c72
35.984848
97
0.707087
4.99182
false
false
false
false
EaglesoftZJ/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Contacts/ZZJG/BMJGTableViewController.swift
1
2533
// // BMJGTableViewController.swift // ActorSDK // // Created by dingjinming on 2017/11/20. // Copyright © 2017年 Steve Kite. All rights reserved. // 部门结构 // "id": "bm002", "mc": "液体化工/船配产业部", "fid": "-1 ", "wzh": 14, "dwid": "dw001", "szk": "ZSGM" // wzh:根据这个排序 fid -1为第一层 为bmxxx时为bmid的子节点 import UIKit class BMJGTableViewController: UITableViewController { var dwid:String = "" var szk:String = ""//所在库 var mc:String = "" var dict = Dictionary<String, Any>() var bm_arr = Array<Dictionary<String, Any>>() override func viewDidLoad() { super.viewDidLoad() self.title = mc self.tableView.tableFooterView = UIView() self.tableView?.register(UITableViewCell.self, forCellReuseIdentifier: "cell") let arr:Array = dict["bm_data"] as! [Dictionary<String, Any>] var wzh_arr = Array<Dictionary<String, Any>>() for bmInfo in arr { if bmInfo["dwid"] as! String == dwid && bmInfo["szk"] as! String == szk{ if bmInfo["fid"] as! String == "-1 "{ wzh_arr.append(bmInfo) } } } bm_arr = wzh_arr.sorted(by: { (s1, s2) -> Bool in return (s1["wzh"] as! Int) < (s2["wzh"] as! Int) ? true:false }) self.tableView.reloadData() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return bm_arr.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 56 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = (bm_arr[indexPath.row]["mc"] as! String) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){ let bmjg:Dictionary = bm_arr[indexPath.row] let ygjg:YGJGTableViewController = YGJGTableViewController() ygjg.dwid = dwid ygjg.mc = bmjg["mc"] as! String ygjg.bmid = bmjg["id"] as! String ygjg.szk = szk ygjg.dict = dict self.navigateDetail(ygjg) } }
agpl-3.0
3708467ec1513359955d1b63e0b9b3e4
32.753425
109
0.599026
3.722054
false
false
false
false
2hme/Class-Tracker
hello-gimbal-swift/AppDelegate.swift
1
3531
import UIKit import Parse import Bolts @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var placeManager: GMBLPlaceManager? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. //[NSThread sleepForTimeInterval,:5.0]; UINavigationBar.appearance().barTintColor = UIColor.blueColor() UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()] UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent self.localNotificationPermission() /** Connnect To Parse */ // [Optional] Power your app with Local Datastore. For more info, go to // https://parse.com/docs/ios_guide#localdatastore/iOS Parse.enableLocalDatastore() // Initialize Parse. Parse.setApplicationId("1Ib7wxcXubez4jpnTXfVCL1zMzG515WgR2u5kIii", clientKey: "8DG0RT5m68O2guSvAE4rbpjV1kM02MTMuBnmY4Ln") GimbalDelegate.sharedInstance // [Optional] Track statistics around application opens. PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions) 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:. print("poop") } func localNotificationPermission() -> Void { let types : UIUserNotificationType = [UIUserNotificationType.Badge, UIUserNotificationType.Alert, UIUserNotificationType.Sound] let settings : UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories:nil) let app = UIApplication.sharedApplication() app.registerUserNotificationSettings(settings) } }
apache-2.0
38a50b721a3943f10a56283ce2bb8cc6
49.442857
285
0.726423
5.640575
false
false
false
false
BasqueVoIPMafia/cordova-plugin-iosrtc
src/PluginGetUserMedia.swift
1
5460
import Foundation import AVFoundation class PluginGetUserMedia { var rtcPeerConnectionFactory: RTCPeerConnectionFactory init(rtcPeerConnectionFactory: RTCPeerConnectionFactory) { NSLog("PluginGetUserMedia#init()") self.rtcPeerConnectionFactory = rtcPeerConnectionFactory } deinit { NSLog("PluginGetUserMedia#deinit()") } func call( _ constraints: NSDictionary, callback: (_ data: NSDictionary) -> Void, errback: (_ error: String) -> Void, eventListenerForNewStream: (_ pluginMediaStream: PluginMediaStream) -> Void ) { NSLog("PluginGetUserMedia#call()") var videoRequested: Bool = false var audioRequested: Bool = false if (constraints.object(forKey: "video") != nil) { videoRequested = true } if constraints.object(forKey: "audio") != nil { audioRequested = true } var rtcMediaStream: RTCMediaStream var pluginMediaStream: PluginMediaStream? var rtcAudioTrack: RTCAudioTrack? var rtcVideoTrack: RTCVideoTrack? var rtcVideoSource: RTCVideoSource? if videoRequested == true { switch AVCaptureDevice.authorizationStatus(for: AVMediaType.video) { case AVAuthorizationStatus.notDetermined: NSLog("PluginGetUserMedia#call() | video authorization: not determined") case AVAuthorizationStatus.authorized: NSLog("PluginGetUserMedia#call() | video authorization: authorized") case AVAuthorizationStatus.denied: NSLog("PluginGetUserMedia#call() | video authorization: denied") errback("video denied") return case AVAuthorizationStatus.restricted: NSLog("PluginGetUserMedia#call() | video authorization: restricted") errback("video restricted") return } } if audioRequested == true { switch AVCaptureDevice.authorizationStatus(for: AVMediaType.audio) { case AVAuthorizationStatus.notDetermined: NSLog("PluginGetUserMedia#call() | audio authorization: not determined") case AVAuthorizationStatus.authorized: NSLog("PluginGetUserMedia#call() | audio authorization: authorized") case AVAuthorizationStatus.denied: NSLog("PluginGetUserMedia#call() | audio authorization: denied") errback("audio denied") return case AVAuthorizationStatus.restricted: NSLog("PluginGetUserMedia#call() | audio authorization: restricted") errback("audio restricted") return } } rtcMediaStream = self.rtcPeerConnectionFactory.mediaStream(withStreamId: UUID().uuidString) if videoRequested { NSLog("PluginGetUserMedia#call() | video requested") rtcVideoSource = self.rtcPeerConnectionFactory.videoSource() rtcVideoTrack = self.rtcPeerConnectionFactory.videoTrack(with: rtcVideoSource!, trackId: UUID().uuidString) // Handle legacy plugin instance or video: true var videoConstraints : NSDictionary = [:]; if (!(constraints.object(forKey: "video") is Bool)) { videoConstraints = constraints.object(forKey: "video") as! NSDictionary } NSLog("PluginGetUserMedia#call() | chosen video constraints: %@", videoConstraints) // Ignore Simulator cause does not support Camera #if !targetEnvironment(simulator) let videoCapturer: RTCCameraVideoCapturer = RTCCameraVideoCapturer(delegate: rtcVideoSource!) let videoCaptureController: PluginRTCVideoCaptureController = PluginRTCVideoCaptureController(capturer: videoCapturer) rtcVideoTrack!.videoCaptureController = videoCaptureController let constraintsSatisfied = videoCaptureController.setConstraints(constraints: videoConstraints) if (!constraintsSatisfied) { errback("constraints not satisfied") return } let captureStarted = videoCaptureController.startCapture() if (!captureStarted) { errback("constraints failed") return } #endif // If videoSource state is "ended" it means that constraints were not satisfied so // invoke the given errback. if (rtcVideoSource!.state == RTCSourceState.ended) { NSLog("PluginGetUserMedia() | rtcVideoSource.state is 'ended', constraints not satisfied") errback("constraints not satisfied") return } rtcMediaStream.addVideoTrack(rtcVideoTrack!) } if audioRequested == true { NSLog("PluginGetUserMedia#call() | audio requested") // Handle legacy plugin instance or audio: true var audioConstraints : NSDictionary = [:]; if (!(constraints.object(forKey: "audio") is Bool)) { audioConstraints = constraints.object(forKey: "audio") as! NSDictionary } NSLog("PluginGetUserMedia#call() | chosen audio constraints: %@", audioConstraints) var audioDeviceId = audioConstraints.object(forKey: "deviceId") as? String if(audioDeviceId == nil && audioConstraints.object(forKey: "deviceId") != nil){ let audioId = audioConstraints.object(forKey: "deviceId") as! NSDictionary audioDeviceId = audioId.object(forKey: "exact") as? String if(audioDeviceId == nil){ audioDeviceId = audioId.object(forKey: "ideal") as? String } } rtcAudioTrack = self.rtcPeerConnectionFactory.audioTrack(withTrackId: UUID().uuidString) rtcMediaStream.addAudioTrack(rtcAudioTrack!) if (audioDeviceId != nil) { PluginRTCAudioController.saveInputAudioDevice(inputDeviceUID: audioDeviceId!) } } pluginMediaStream = PluginMediaStream(rtcMediaStream: rtcMediaStream) pluginMediaStream!.run() // Let the plugin store it in its dictionary. eventListenerForNewStream(pluginMediaStream!) callback([ "stream": pluginMediaStream!.getJSON() ]) } }
mit
4d6ecb271f478718bf09523be7152290
31.891566
121
0.741575
4.252336
false
false
false
false
mindbody/Conduit
Sources/Conduit/Networking/URLSessionClient.swift
1
17889
// // URLSessionClient.swift // Conduit // // Created by John Hammerlund on 7/22/16. // Copyright © 2017 MINDBODY. All rights reserved. // import Foundation public typealias SessionTaskCompletion = (Data?, HTTPURLResponse?, Error?) -> Void public typealias SessionTaskProgressHandler = (Progress) -> Void private typealias SessionCompletionHandler = (URLSession.AuthChallengeDisposition, URLCredential?) -> Void /// Errors thrown from URLSessionClient requests public enum URLSessionClientError: Error { case noResponse case requestTimeout case missingURLInMiddlewareRequest } /// Pipes requests through provided middleware and queues them into a single NSURLSession public struct URLSessionClient: URLSessionClientType { /// Shared URL session client, can be overriden public static var shared: URLSessionClientType = URLSessionClient(delegateQueue: OperationQueue()) /// The middleware that all incoming requests should be piped through public var requestMiddleware: [RequestPipelineMiddleware] /// The middleware that all response payloads should be piped through public var responseMiddleware: [ResponsePipelineMiddleware] /// The authentication policies to be evaluated against for NSURLAuthenticationChallenges against the /// NSURLSession. Mutating this will affect all URLSessionClient copies. public var serverAuthenticationPolicies: [ServerAuthenticationPolicyType] { get { return sessionDelegate.serverAuthenticationPolicies } set { sessionDelegate.serverAuthenticationPolicies = newValue } } private let urlSession: URLSession private let serialQueue = DispatchQueue(label: "com.mindbodyonline.Conduit.URLSessionClient-\(UUID().uuidString)", attributes: []) private let activeTaskQueueDispatchGroup = DispatchGroup() // swiftlint:disable weak_delegate private let sessionDelegate = SessionDelegate() // swiftlint:enable weak_delegate private static var requestCounter: Int64 = 0 /// Creates a new URLSessionClient with provided middleware and NSURLSession parameters /// - Parameters: /// - middleware: The middleware that all incoming requests should be piped through /// - sessionConfiguration: The NSURLSessionConfiguration used to construct the underlying NSURLSession. /// Defaults to NSURLSessionConfiguration.defaultSessionConfiguration() /// - delegateQueue: The NSOperationQueue in which completion handlers should execute public init(requestMiddleware: [RequestPipelineMiddleware] = [], responseMiddleware: [ResponsePipelineMiddleware] = [], sessionConfiguration: URLSessionConfiguration = URLSessionConfiguration.default, delegateQueue: OperationQueue = OperationQueue.main) { self.requestMiddleware = requestMiddleware self.responseMiddleware = responseMiddleware self.urlSession = URLSession(configuration: sessionConfiguration, delegate: self.sessionDelegate, delegateQueue: delegateQueue) } /// Queues a request into the session pipeline, blocking until request completes or fails. /// Method will throw an error if the request times out or if there is no response. /// Empty data (`nil`) is considered a valid result and will not throw an exception. /// /// Note: Synchronoys blocking calls will block the current thread, preventing the result from /// ever being returned. To avoid this, make sure the `delegateQueue` is different than /// the one from the calling thread. /// /// - Parameters: /// - request: The URLRequest to be enqueued /// - Returns: Tuple containing data and response /// - Throws: URLSessionClientError, if any @discardableResult public func begin(request: URLRequest) throws -> (data: Data?, response: HTTPURLResponse) { var result: (data: Data?, response: HTTPURLResponse?, error: Error?) = (nil, nil, nil) let semaphore = DispatchSemaphore(value: 0) begin(request: request) { data, response, error in result = (data, response, error) semaphore.signal() } let timeout = urlSession.configuration.timeoutIntervalForRequest if semaphore.wait(timeout: .now() + timeout) == .timedOut { throw URLSessionClientError.requestTimeout } if let error = result.error { throw error } guard let response = result.response else { throw URLSessionClientError.noResponse } return (data: result.data, response: response) } /// Queues a request into the session pipeline /// - Parameters: /// - request: The URLRequest to be enqueued /// - completion: The response handler, which will execute on the session's delegateQueue @discardableResult public func begin(request: URLRequest, completion: @escaping SessionTaskCompletion) -> SessionTaskProxyType { let sessionTaskProxy = SessionTaskProxy() let requestID = OSAtomicIncrement64Barrier(&URLSessionClient.requestCounter) serialQueue.async { self.synchronouslyWaitForMiddleware() // Next, allow each middleware component to have its way with the original URLRequest // This is done synchronously on the serial queue since the pipeline itself shouldn't allow for concurrency logger.verbose("Processing request through middleware pipeline ⌛︎") let middlewareProcessingResult = self.synchronouslyProcessRequestMiddleware(for: request) let modifiedRequest: URLRequest switch middlewareProcessingResult { case .error(let error): var taskResponse = TaskResponse() taskResponse.error = error self.synchronouslyProcessResponseMiddleware(request: request, taskResponse: &taskResponse) self.urlSession.delegateQueue.addOperation { completion(taskResponse.data, taskResponse.response, taskResponse.error) } return case .value(let request): modifiedRequest = request } logger.verbose("Finished processing request through middleware pipeline ✓") // This is an edge case. In `refreshBearerTokenWithin` method of Auth class we are delibertely making the request URL // as nil. Since the request URL is nil, the data task is not initialized and we do not get the call back. // To fix this we have added a nil check. If the URL is nil, we are returning a call back with missingURL error. guard modifiedRequest.url != nil else { completion(nil, nil, URLSessionClientError.missingURLInMiddlewareRequest) return } // Finally, send the request // Once tasks are created, the operation moves to the connection queue, // so even though the pipeline is serial, requests run in parallel let task = self.dataTaskWith(request: modifiedRequest) { taskResponse in self.serialQueue.async { var taskResponse = taskResponse self.synchronouslyProcessResponseMiddleware(request: request, taskResponse: &taskResponse) self.urlSession.delegateQueue.addOperation { self.log(taskResponse: taskResponse, request: request, requestID: requestID) completion(taskResponse.data, taskResponse.response, taskResponse.error) } } } self.log(request: request, requestID: requestID) self.sessionDelegate.registerDownloadProgressHandler(taskIdentifier: task.taskIdentifier) { progress in sessionTaskProxy.downloadProgressHandler?(progress) } self.sessionDelegate.registerUploadProgressHandler(taskIdentifier: task.taskIdentifier) { progress in sessionTaskProxy.uploadProgressHandler?(progress) } task.resume() sessionTaskProxy.task = task } return sessionTaskProxy } private func synchronouslyWaitForMiddleware() { logger.verbose("Scanning middlware options ⌛︎") for middleware in self.requestMiddleware { if middleware.pipelineBehaviorOptions.contains(.awaitsOutgoingCompletion) { logger.verbose("Paused session queue ⏸") _ = self.activeTaskQueueDispatchGroup.wait(timeout: DispatchTime.distantFuture) logger.verbose("Resumed session queue ▶️") } } logger.verbose("Finished scanning middleware options ✓") } private func synchronouslyProcessRequestMiddleware(for request: URLRequest) -> Result<URLRequest> { var middlwareError: Error? let middlewarePipelineDispatchGroup = DispatchGroup() var modifiedRequest = request for middleware in requestMiddleware { middlewarePipelineDispatchGroup.enter() middleware.prepareForTransport(request: modifiedRequest) { result in switch result { case .value(let request): modifiedRequest = request case .error(let error): logger.warn("Encountered an error within the middleware pipeline") middlwareError = error } middlewarePipelineDispatchGroup.leave() } _ = middlewarePipelineDispatchGroup.wait(timeout: .distantFuture) if let error = middlwareError { return .error(error) } } return .value(modifiedRequest) } func synchronouslyProcessResponseMiddleware(request: URLRequest, taskResponse: inout TaskResponse) { let dispatchGroup = DispatchGroup() for middleware in responseMiddleware { dispatchGroup.enter() middleware.prepare(request: request, taskResponse: &taskResponse) { dispatchGroup.leave() } _ = dispatchGroup.wait(timeout: .distantFuture) } } private func dataTaskWith(request: URLRequest, completion: @escaping (TaskResponse) -> Void) -> URLSessionDataTask { activeTaskQueueDispatchGroup.enter() let dataTask = urlSession.dataTask(with: request) sessionDelegate.registerCompletionHandler(taskIdentifier: dataTask.taskIdentifier) { _, _, _ in // Usage of strong self: If for some reason the client isn't retained elsewhere, it will at least stay alive // while active tasks are running self.activeTaskQueueDispatchGroup.leave() let taskResponse = self.sessionDelegate.taskResponseFor(taskIdentifier: dataTask.taskIdentifier) completion(taskResponse) } return dataTask } } private class SessionDelegate: NSObject, URLSessionDataDelegate { var serverAuthenticationPolicies: [ServerAuthenticationPolicyType] = [] private var taskCompletionHandlers: [Int: SessionTaskCompletion] = [:] private var taskDownloadProgressHandlers: [Int: SessionTaskProgressHandler] = [:] private var taskDownloadProgresses: [Int: Progress] = [:] private var taskUploadProgressHandlers: [Int: SessionTaskProgressHandler] = [:] private var taskUploadProgresses: [Int: Progress] = [:] private var taskResponses: [Int: TaskResponse] = [:] private let serialQueue = DispatchQueue(label: "com.mindbodyonline.Conduit.SessionDelegate-\(UUID().uuidString)") func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping SessionCompletionHandler) { for policy in serverAuthenticationPolicies { if policy.evaluate(authenticationChallenge: challenge) == false { completionHandler(.cancelAuthenticationChallenge, nil) return } } guard let serverTrust = challenge.protectionSpace.serverTrust else { completionHandler(.useCredential, challenge.proposedCredential) return } completionHandler(.useCredential, URLCredential(trust: serverTrust)) } /// Reports upload progress func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { var progressHandler: SessionTaskProgressHandler? var uploadProgress: Progress? serialQueue.sync { progressHandler = taskUploadProgressHandlers[task.taskIdentifier] uploadProgress = taskUploadProgresses[task.taskIdentifier] ?? Progress() uploadProgress?.completedUnitCount = totalBytesSent uploadProgress?.totalUnitCount = totalBytesExpectedToSend taskUploadProgresses[task.taskIdentifier] = uploadProgress } if let progress = uploadProgress { progressHandler?(progress) } } /// Reports download progress and appends response data func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { var taskResponse = taskResponseFor(taskIdentifier: dataTask.taskIdentifier) var responseData = taskResponse.data ?? Data() responseData.append(data) taskResponse.data = responseData update(taskResponse: taskResponse, for: dataTask.taskIdentifier) guard let expectedContentLength = taskResponse.expectedContentLength else { return } var progressHandler: SessionTaskProgressHandler? var downloadProgress: Progress? serialQueue.sync { progressHandler = taskDownloadProgressHandlers[dataTask.taskIdentifier] downloadProgress = taskDownloadProgresses[dataTask.taskIdentifier] ?? Progress() downloadProgress?.completedUnitCount = Int64(responseData.count) downloadProgress?.totalUnitCount = expectedContentLength taskDownloadProgresses[dataTask.taskIdentifier] = downloadProgress } if let progress = downloadProgress { progressHandler?(progress) } } /// Prepares task response. This delegate method is always called before data is received. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { var taskResponse = taskResponseFor(taskIdentifier: dataTask.taskIdentifier) taskResponse.response = response as? HTTPURLResponse taskResponse.expectedContentLength = response.expectedContentLength update(taskResponse: taskResponse, for: dataTask.taskIdentifier) completionHandler(.allow) } /// Stores request metrics in task response, for later consumption. /// This delegate method is always called after `didReceive response`, and before `didCompleteWithError`. @available(iOS 10, macOS 10.12, tvOS 10, watchOS 3, *) func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { var taskResponse = taskResponseFor(taskIdentifier: task.taskIdentifier) taskResponse.metrics = metrics update(taskResponse: taskResponse, for: task.taskIdentifier) } /// Fires completion handler and releases upload, download, and completion handlers func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { var taskResponse = taskResponseFor(taskIdentifier: task.taskIdentifier) taskResponse.error = error update(taskResponse: taskResponse, for: task.taskIdentifier) var completionHandler: SessionTaskCompletion? serialQueue.sync { completionHandler = taskCompletionHandlers[task.taskIdentifier] taskCompletionHandlers[task.taskIdentifier] = nil taskDownloadProgressHandlers[task.taskIdentifier] = nil taskUploadProgressHandlers[task.taskIdentifier] = nil taskDownloadProgresses[task.taskIdentifier] = nil taskUploadProgresses[task.taskIdentifier] = nil } completionHandler?(taskResponse.data, taskResponse.response, taskResponse.error) } func registerCompletionHandler(taskIdentifier: Int, completionHandler: @escaping SessionTaskCompletion) { serialQueue.sync { self.taskCompletionHandlers[taskIdentifier] = completionHandler } } func registerDownloadProgressHandler(taskIdentifier: Int, progressHandler: @escaping SessionTaskProgressHandler) { serialQueue.sync { self.taskDownloadProgressHandlers[taskIdentifier] = progressHandler } } func registerUploadProgressHandler(taskIdentifier: Int, progressHandler: @escaping SessionTaskProgressHandler) { serialQueue.sync { self.taskUploadProgressHandlers[taskIdentifier] = progressHandler } } func taskResponseFor(taskIdentifier: Int) -> TaskResponse { return serialQueue.sync { return taskResponses[taskIdentifier] ?? makeTaskResponseFor(taskIdentifier: taskIdentifier) } } func update(taskResponse: TaskResponse, for taskIdentifier: Int) { serialQueue.sync { taskResponses[taskIdentifier] = taskResponse } } private func makeTaskResponseFor(taskIdentifier: Int) -> TaskResponse { let taskResponse = TaskResponse() taskResponses[taskIdentifier] = taskResponse return taskResponse } }
apache-2.0
a58a8ba1dcac27cb928eeca2dea657ae
44.820513
156
0.685395
5.758943
false
false
false
false
mckaskle/FlintKit
FlintKit/Core Location/CLLocationCoordinate2D+FlintKit.swift
1
1446
// // MIT License // // CLLocationCoordinate2D+FlintKit.swift // // Copyright (c) 2016 Devin McKaskle // // 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 CoreLocation extension CLLocationCoordinate2D: Equatable { public static func == (lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool { return lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude } }
mit
12e5fe062b849e5d7da36c83b779e944
39.166667
92
0.745505
4.278107
false
false
false
false
TheNounProject/CollectionView
CollectionView/DataStructures/EditDistance/CustomDiff.swift
1
2316
// // CustomDiff.swift // CollectionView // // Created by Wesley Byrne on 2/26/18. // Copyright © 2018 Noun Project. All rights reserved. // import Foundation public final class CVDiff: DiffAware { public init() { } public func diff<T>(old: T, new: T) -> [Edit<T.Element>] where T: Collection, T.Element: Hashable, T.Index == Int { let sourceSet = old.indexedSet let targetSet = new.indexedSet var insertions = IndexSet() var deletions = IndexSet() var _edits = EditOperationIndex<T.Iterator.Element>() for value in Set(old).union(new) { let sIdx = sourceSet.index(of: value) let tIdx = targetSet.index(of: value) if let s = sIdx, let t = tIdx { if s == t { } else { let adjust = insertions.count(in: 0...s) - deletions.count(in: 0...s) if s + adjust == t { continue } _edits.delete(value, index: s) _edits.insert(value, index: t) insertions.insert(t) deletions.insert(s) } } else if let idx = sIdx { _edits.delete(value, index: idx) deletions.insert(idx) } else if let idx = tIdx { _edits.insert(value, index: idx) insertions.insert(idx) } } return reduceEdits(_edits) } public func reduceEdits<T>(_ edits: EditOperationIndex<T>) -> [Edit<T>] { var res = [Edit<T>]() var edits = edits for target in edits.inserts { guard edits.deletes.contains(target.value), let source = edits.deletes.remove(target.value) else { res.append(target.value) continue } let newEdit = Edit(.move(origin: source), value: target.value.value, index: target.index) res.append(newEdit) } res.append(contentsOf: edits.deletes.values) res.append(contentsOf: edits.moves.values) res.append(contentsOf: edits.substitutions.values) return res } }
mit
12fbc9c9956a3a3bfa61b4d8a5ae3279
31.152778
119
0.50108
4.359699
false
false
false
false
onekiloparsec/siesta
Source/UI/RemoteImageView.swift
2
2360
// // RemoteImageView.swift // Siesta // // Created by Paul on 2015/8/26. // Copyright © 2016 Bust Out Solutions. All rights reserved. // import Foundation import UIKit /** A `UIImageView` that asynchronously loads and displays remote images. */ public class RemoteImageView: UIImageView { /// Optional view to show while image is loading. @IBOutlet public weak var loadingView: UIView? /// Optional view to show if image is unavailable. Not shown while image is loading. @IBOutlet public weak var alternateView: UIView? /// Optional image to show if image is either unavailable or loading. Suppresses alternateView if non-nil. @IBOutlet public var placeholderImage: UIImage? /// The default service to cache `RemoteImageView` images. public static var defaultImageService: Service = Service() /// The service this view should use to request & cache its images. public var imageService: Service = RemoteImageView.defaultImageService /// A URL whose content is the image to display in this view. public var imageURL: String? { get { return imageResource?.url.absoluteString } set { imageResource = imageService.resource(absoluteURL: newValue) } } /** A remote resource whose content is the image to display in this view. If this image is already in memory, it is displayed synchronously (no flicker!). If the image is missing or potentially stale, setting this property triggers a load. */ public var imageResource: Resource? { willSet { imageResource?.removeObservers(ownedBy: self) imageResource?.cancelLoadIfUnobserved(afterDelay: 0.05) } didSet { imageResource?.loadIfNeeded() imageResource?.addObserver(owner: self) { [weak self] _ in self?.updateViews() } if imageResource == nil // (and thus closure above was not called on ObserverAdded) { updateViews() } } } private func updateViews() { image = imageResource?.typedContent(ifNone: placeholderImage) let isLoading = imageResource?.isLoading ?? false loadingView?.hidden = !isLoading alternateView?.hidden = (image != nil) || isLoading } }
mit
1a5f886c6a307f418a1c2641ec8019be
31.763889
113
0.652395
5.019149
false
false
false
false
jtsmrd/Intrview
Models/PreviousSearch.swift
1
1619
// // PreviousSearch.swift // Intrview // // Created by JT Smrdel on 8/11/17. // Copyright © 2017 SmrdelJT. All rights reserved. // import Foundation class PreviousSearch: NSObject, NSCoding { var name: String var profession: String var contactEmail: String var cKRecordName: String var searchDate: Date init(name: String, profession: String, contactEmail: String, cKRecordName: String, searchDate: Date) { self.name = name self.profession = profession self.contactEmail = contactEmail self.cKRecordName = cKRecordName self.searchDate = searchDate } // MARK: NSCoding func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: "name") aCoder.encode(profession, forKey: "profession") aCoder.encode(contactEmail, forKey: "contactEmail") aCoder.encode(cKRecordName, forKey: "cKRecordName") aCoder.encode(searchDate, forKey: "searchDate") } required convenience init?(coder aDecoder: NSCoder) { let name = aDecoder.decodeObject(forKey: "name") as! String let profession = aDecoder.decodeObject(forKey: "profession") as! String let contactEmail = aDecoder.decodeObject(forKey: "contactEmail") as! String let cKRecordName = aDecoder.decodeObject(forKey: "cKRecordName") as! String let searchDate = aDecoder.decodeObject(forKey: "searchDate") as! Date self.init(name: name, profession: profession, contactEmail: contactEmail, cKRecordName: cKRecordName, searchDate: searchDate) } }
mit
74e77ec013fdd3a23232f04cb7555d37
32.708333
133
0.666255
4.280423
false
false
false
false
february29/Learning
swift/ReactiveCocoaDemo/ReactiveCocoaDemo/BTools/BExtension/UIView+BExtension.swift
1
2524
// // UIView+BExtension.swift // ReactiveCocoaDemo // // Created by bai on 2017/10/30. // Copyright © 2017年 北京仙指信息技术有限公司. All rights reserved. // import UIKit extension UIView{ func b_clipRectCorner(direction:UIRectCorner,cornerRadius:CGFloat) { let cornerSize = CGSize(width: cornerRadius, height: cornerRadius); let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: direction, cornerRadii: cornerSize); let maskLayer = CAShapeLayer(); maskLayer.frame = bounds; maskLayer.path = maskPath.cgPath; layer.addSublayer(maskLayer); layer.mask = maskLayer; } /// x var x: CGFloat { get { return frame.origin.x } set(newValue) { var tempFrame: CGRect = frame tempFrame.origin.x = newValue frame = tempFrame } } /// y var y: CGFloat { get { return frame.origin.y } set(newValue) { var tempFrame: CGRect = frame tempFrame.origin.y = newValue frame = tempFrame } } /// height var height: CGFloat { get { return frame.size.height } set(newValue) { var tempFrame: CGRect = frame tempFrame.size.height = newValue frame = tempFrame } } /// width var width: CGFloat { get { return frame.size.width } set(newValue) { var tempFrame: CGRect = frame tempFrame.size.width = newValue frame = tempFrame } } /// size var size: CGSize { get { return frame.size } set(newValue) { var tempFrame: CGRect = frame tempFrame.size = newValue frame = tempFrame } } /// centerX var centerX: CGFloat { get { return center.x } set(newValue) { var tempCenter: CGPoint = center tempCenter.x = newValue center = tempCenter } } /// centerY var centerY: CGFloat { get { return center.y } set(newValue) { var tempCenter: CGPoint = center tempCenter.y = newValue center = tempCenter; } } }
mit
897789a1611c61ec47b71bf38f66ab91
21.908257
112
0.488186
5.044444
false
false
false
false
madeatsampa/MacMagazine-iOS
MacMagazine/ShareAction/Share.swift
1
1858
// // Share.swift // MacMagazine // // Created by Cassio Rossi on 15/04/2019. // Copyright © 2019 MacMagazine. All rights reserved. // import UIKit struct Share { func present<T>(at location: T?, using items: [Any], activities: [UIActivityExtensions]? = nil) { let safari = UIActivityExtensions(title: "Abrir no Safari", image: UIImage(systemName: "safari")) { items in for item in items { guard let url = URL(string: "\(item)") else { continue } if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } } let chrome = UIActivityExtensions(title: "Abrir no Chrome", image: UIImage(named: "chrome")) { items in for item in items { guard let url = URL(string: "\(item)".replacingOccurrences(of: "http", with: "googlechrome")) else { continue } if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } } var applicationActivities = [UIActivityExtensions]() if let activities = activities { applicationActivities.append(contentsOf: activities) } applicationActivities.append(safari) if let url = URL(string: "googlechrome://"), UIApplication.shared.canOpenURL(url) { applicationActivities.append(chrome) } let activityVC = UIActivityViewController(activityItems: items, applicationActivities: applicationActivities) if let ppc = activityVC.popoverPresentationController { if location != nil { if let view = location as? UIView { ppc.sourceView = view } if let button = location as? UIBarButtonItem { ppc.barButtonItem = button } } } UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.rootViewController?.present(activityVC, animated: true) } }
mit
b247082ba18633c5b0dcaadb295658ba
31.017241
126
0.674744
3.959488
false
false
false
false
alexfish/tissue
tissue/Modules/Issues/IssueParser.swift
1
853
// // IssueParser.swift // tissue // // Created by Alex Fish on 07/06/2014. // Copyright (c) 2014 alexefish. All rights reserved. // import UIKit struct IssueAPIKey { static let body = "body" static let title = "title" static let state = "state" static let id = "number" static let url = "url" } class IssueParser: Parser { override func parseObject(json: NSDictionary) -> AnyObject? { var issue: Issue? let title = parseString(json, key: IssueAPIKey.title) let id = parseNumber(json, key: IssueAPIKey.id) let url = parseURL(json, key: IssueAPIKey.url) let body = parseString(json, key: IssueAPIKey.body) if title? && id? && url? { issue = Issue(id: id!.stringValue, title: title!, body: body, url: url!) } return issue } }
mit
b2a2922b458bf4a45dd202aef23b0a29
23.371429
84
0.600234
3.629787
false
false
false
false
nathawes/swift
test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_class_specialized_at_generic_class.swift
2
10870
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment --check-prefix=CHECK --check-prefix=CHECK-%target-vendor // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main3Box[[UNIQUE_ID_1:[A-Za-z0-9_]+]]LLCyAA5InnerACLLCySiGGMf" = // CHECK: @"$s4main5Value[[UNIQUE_ID_1]]LLCyAA3BoxACLLCyAA5InnerACLLCySiGGGMf" = linkonce_odr hidden // CHECK-apple-SAME: global // CHECK-unknown-SAME: constant // CHECK-SAME: <{ // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* // CHECK-SAME: )*, // CHECK-SAME: i8**, // : [[INT]], // CHECK-apple-SAME: %objc_class*, // CHECK-unknown-SAME: %swift.type*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: [[INT]], // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i16, // CHECK-SAME: i16, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: i8*, // CHECK-SAME: %swift.type*, // CHECK-SAME: [[INT]], // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* ( // CHECK-SAME: %swift.opaque*, // CHECK-SAME: %swift.type* // CHECK-SAME: )* // CHECK-SAME: }> <{ // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCfD // CHECK-SAME: $sBoWV // CHECK-apple-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCyAA3BoxACLLCyAA5InnerACLLCySiGGGMM // CHECK-unknown-SAME: [[INT]] 0, // CHECK-apple-SAME: OBJC_CLASS_$__TtCs12_SwiftObject // CHECK-apple-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-apple-SAME: %swift.opaque* null, // CHECK-apple-SAME: [[INT]] add ( // CHECK-apple-SAME: [[INT]] ptrtoint ( // CHECK-apple-SAME: { // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // : i32, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: { // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: [ // CHECK-apple-SAME: 1 x { // CHECK-apple-SAME: [[INT]]*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32 // CHECK-apple-SAME: } // CHECK-apple-SAME: ] // CHECK-apple-SAME: }*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8* // CHECK-apple-SAME: }* @_DATA__TtC4mainP[[UNIQUE_ID_1]]5Value to [[INT]] // CHECK-apple-SAME: ), // CHECK-apple-SAME: [[INT]] 2 // CHECK-apple-SAME: ), // CHECK-SAME: i32 26, // CHECK-SAME: i32 0, // CHECK-SAME: i32 {{(24|12)}}, // CHECK-SAME: i16 {{(7|3)}}, // CHECK-SAME: i16 0, // CHECK-apple-SAME: i32 {{(120|72)}}, // CHECK-unknown-SAME: i32 96, // CHECK-SAME: i32 {{(16|8)}}, // : %swift.type_descriptor* bitcast ( // : <{ // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i16, // : i16, // : i16, // : i16, // : i8, // : i8, // : i8, // : i8, // : i32, // : i32, // : %swift.method_descriptor // : }>* @"$s4main5Value[[UNIQUE_ID_1]]LLCMn" to %swift.type_descriptor* // : ), // CHECK-SAME: i8* null, // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_heapmetadata, // CHECK-SAME: %swift.full_heapmetadata* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: void ( // CHECK-SAME: %T4main3Box[[UNIQUE_ID_1:[a-zA-Z0-9_]+]]LLC* // CHECK-SAME: )*, // CHECK-SAME: i8**, // : [[INT]], // CHECK-apple-SAME: %objc_class*, // CHECK-unknown-SAME: %swift.type*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: [[INT]], // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i16, // CHECK-SAME: i16, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: i8*, // CHECK-SAME: %swift.type*, // CHECK-SAME: [[INT]], // CHECK-SAME: %T4main3Box[[UNIQUE_ID_1]]LLC* ( // CHECK-SAME: %swift.opaque*, // CHECK-SAME: %swift.type* // CHECK-SAME: )* // CHECK-SAME: }>* @"$s4main3Box[[UNIQUE_ID_1]]LLCyAA5InnerACLLCySiGGMf" to %swift.full_heapmetadata* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 2 // CHECK-SAME: ), // CHECK-SAME: [[INT]] {{(16|8)}}, // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* ( // CHECK-SAME: %swift.opaque*, // CHECK-SAME: %swift.type* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLC5firstADyxGx_tcfC // CHECK-SAME: }>, // CHECK-SAME: align [[ALIGNMENT]] fileprivate class Value<First> { let first_Value: First init(first: First) { self.first_Value = first } } fileprivate class Box<Value> { let value: Value init(value: Value) { self.value = value } } fileprivate class Inner<Value> { let value: Value init(value: Value) { self.value = value } } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: [[METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_4:[0-9A-Z_]+]]LLCyAA3BoxACLLCyAA5InnerACLLCySiGGGMb"([[INT]] 0) // CHECK: [[METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0 // CHECK: call swiftcc void @"$s4main7consumeyyxlF"( // CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}}, // CHECK-SAME: %swift.type* [[METADATA]]) // CHECK: } func doit() { consume( Value(first: Box(value: Inner(value: 13))) ) } doit() // CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], %swift.type* %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata( // CHECK: [[INT]] [[METADATA_REQUEST]], // CHECK: i8* [[ERASED_TYPE]], // CHECK: i8* undef, // CHECK: i8* undef, // CHECK: %swift.type_descriptor* bitcast ( // : <{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8, i32, i32, %swift.method_descriptor }>* // CHECK: $s4main5Value[[UNIQUE_ID_1]]LLCMn // CHECK: to %swift.type_descriptor* // CHECK: ) // CHECK: ) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: } // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCyAA3BoxACLLCyAA5InnerACLLCySiGGGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} { // CHECK: entry: // CHECK-unknown: ret // CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call %objc_class* @objc_opt_self( // : %objc_class* bitcast ( // : %swift.type* getelementptr inbounds ( // : %swift.full_heapmetadata, // : %swift.full_heapmetadata* bitcast ( // : <{ // : void ( // : %T4main5Value33_9100AE3EFBE408E03C856CED54B18B61LLC* // : )*, // : i8**, // : [[INT]], // : %objc_class*, // : %swift.opaque*, // : %swift.opaque*, // : [[INT]], // : i32, // : i32, // : i32, // : i16, // : i16, // : i32, // : i32, // : %swift.type_descriptor*, // : i8*, // : %swift.type*, // : [[INT]], // : %T4main5Value33_9100AE3EFBE408E03C856CED54B18B61LLC* ( // : %swift.opaque*, // : %swift.type* // : )* // CHECK-SAME: @"$s4main5Value[[UNIQUE_ID_1]]LLCyAA3BoxACLLCyAA5InnerACLLCySiGGGMf" // : to %swift.full_heapmetadata* // : ), // : i32 0, // : i32 2 // : ) to %objc_class* // : ) // : ) // CHECK-apple: [[INITIALIZED_METADATA:%[0-9]+]] = bitcast %objc_class* [[INITIALIZED_CLASS]] to %swift.type* // CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[INITIALIZED_METADATA]], 0 // CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 // CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] // CHECK: }
apache-2.0
251ce9cdf64ccfffff92e70aa033882f
40.018868
214
0.453634
3.207436
false
false
false
false
sembsa/CProgressView
CProgressView/CProgressView.swift
1
3501
// // CProgressView.swift // CProgressView // // Created by Sebastian Trześniewski on 21.04.2015. // Copyright (c) 2015 Sebastian Trześniewski. All rights reserved. // import UIKit @IBDesignable class CProgressView: UIView { // Variables private var π: CGFloat = CGFloat(M_PI) private var progressCircle = CAShapeLayer() private var realProgressCircle = CAShapeLayer() private var circlePath = UIBezierPath() internal var statusProgress: Int = Int() // Method for calculate ARC private func arc(arc: CGFloat) -> CGFloat { let results = ( π * arc ) / 180 return results } // Variables for IBInspectable @IBInspectable var circleColor: UIColor = UIColor.grayColor() @IBInspectable var progressColor: UIColor = UIColor.greenColor() @IBInspectable var lineWidth: Float = Float(3.0) @IBInspectable var valueProgress: Float = Float() @IBInspectable var imageView: UIImageView = UIImageView() @IBInspectable var image: UIImage? override func drawRect(rect: CGRect) { // Create Path for ARC let centerPointArc = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2) let radiusArc: CGFloat = self.frame.width / 2 * 0.8 circlePath = UIBezierPath(arcCenter: centerPointArc, radius: radiusArc, startAngle: arc(0), endAngle: arc(360), clockwise: true) // Define background circle progress progressCircle.path = circlePath.CGPath progressCircle.strokeColor = circleColor.CGColor progressCircle.fillColor = UIColor.clearColor().CGColor progressCircle.lineWidth = CGFloat(lineWidth) progressCircle.strokeStart = 0 progressCircle.strokeEnd = 100 // Define real circle progress realProgressCircle.path = circlePath.CGPath realProgressCircle.strokeColor = progressColor.CGColor realProgressCircle.fillColor = UIColor.clearColor().CGColor realProgressCircle.lineWidth = CGFloat(lineWidth) + 0.1 realProgressCircle.strokeStart = 0 realProgressCircle.strokeEnd = CGFloat(valueProgress) / 100 // UIImageView imageView.frame = CGRect(origin: CGPoint(x: circlePath.bounds.minX, y: circlePath.bounds.minY), size: CGSize(width: circlePath.bounds.width, height: circlePath.bounds.height)) imageView.image = image imageView.layer.cornerRadius = radiusArc imageView.layer.masksToBounds = true addSubview(imageView) // Set for sublayer circle progress layer.addSublayer(progressCircle) layer.addSublayer(realProgressCircle) } // Method for update status progress func updateProgressCircle(status: Float) { statusProgress = Int(status) realProgressCircle.strokeEnd = CGFloat(status) / 100 } func resetProgressCircle() { realProgressCircle.strokeEnd = CGFloat(0.0) } // Method for update look :) func changeColorBackgroundCircleProgress(stroke: UIColor?, fill: UIColor?) { progressCircle.strokeColor = stroke!.CGColor progressCircle.fillColor = fill!.CGColor } func changeColorRealCircleProgress( stroke: UIColor?, fill: UIColor?) { realProgressCircle.strokeColor = stroke!.CGColor realProgressCircle.fillColor = fill!.CGColor } func changeLineWidth(size: CGFloat) { progressCircle.lineWidth = size realProgressCircle.lineWidth = size + 0.1 } }
mit
1ed51863e9fc55aceb26c5ca17e47050
35.821053
183
0.684873
4.770805
false
false
false
false
chenkaige/EasyIOS-Swift
Pod/Classes/Extend/EUI/EUI+TextFieldProperty.swift
1
2281
// // EUI+TextFieldProperty.swift // medical // // Created by zhuchao on 15/5/1. // Copyright (c) 2015年 zhuchao. All rights reserved. // import Foundation class TextFieldProperty:ViewProperty{ var placeholder:NSData? var placeholderStyle = "" var text:NSData? var keyboardType = UIKeyboardType.Default override func view() -> UITextField{ let view = UITextField() view.tagProperty = self view.keyboardType = self.keyboardType let str = NSAttributedString(fromHTMLData:self.text, attributes: ["html":self.style]) view.defaultTextAttributes = str.attributesAtIndex(0, effectiveRange:nil) view.attributedPlaceholder = NSAttributedString(fromHTMLData: self.placeholder, attributes: ["html":self.placeholderStyle]) self.renderViewStyle(view) return view } override func renderTag(pelement: OGElement) { self.tagOut += ["placeholder","placeholder-style","text","keyboard-type"] super.renderTag(pelement) if let text = EUIParse.string(pelement, key: "text"), let newHtml = Regex("\\{\\{(\\w+)\\}\\}").replace(text, withBlock: { (regx) -> String in let keyPath = regx.subgroupMatchAtIndex(0)?.trim self.bind["text"] = keyPath return "" }) { self.contentText = newHtml } self.text = "1".dataUsingEncoding(NSUTF8StringEncoding)?.dataByReplacingOccurrencesOfData("\\n".dataUsingEncoding(NSUTF8StringEncoding), withData: "\n".dataUsingEncoding(NSUTF8StringEncoding)) if let placeholderStyle = EUIParse.string(pelement,key: "placeholder-style") { self.placeholderStyle = "html{" + placeholderStyle + "}" } if let placeholder = EUIParse.string(pelement,key: "placeholder") { self.placeholder = placeholder.dataUsingEncoding(NSUTF8StringEncoding)?.dataByReplacingOccurrencesOfData("\\n".dataUsingEncoding(NSUTF8StringEncoding), withData: "\n".dataUsingEncoding(NSUTF8StringEncoding)) } if let keyboardType = EUIParse.string(pelement, key: "keyboard-type") { self.keyboardType = keyboardTypeFromString(keyboardType) } } }
mit
07d9a9938f93dffff6f0b8f4b0ec9609
39.696429
219
0.64853
4.747917
false
false
false
false
kamleshgk/iOSStarterTemplate
foodcolors/Classes/ViewControllers/ProductsViewController.swift
1
18912
// // ProductsViewController.swift // Foodcolors // // Created by kamyFCMacBook on 10/26/16. // Copyright © 2016 kamyFCMacBook. All rights reserved. // import UIKit protocol ProductsDelegate { func updateCartChange() } class ProductsViewController: UIViewController, CartCellDelegate , HQPagerViewControllerDataSource, UITableViewDataSource { var tabTitle: String! = "" var tabColori: UIColor! var tabNormalIconImage: UIImage! var tabHighlightedIconImage: UIImage! var deleteIndexPath: IndexPath! var delegate: ProductsDelegate? @IBOutlet var productTable: UITableView! @IBOutlet var noLoginViewSeparator: UIView! @IBOutlet var noLoginMessageLabel: UILabel! var bookItemArray: Array<CartDetails> = [] var musicItemArray: Array<CartDetails> = [] var arrayHeaders = ["Books", "Music"] override func viewDidLoad() { super.viewDidLoad() let session = UserSessionInfo.sharedUser() as UserSessionInfo var booksArray: Array<CartDetails> = [] var musicsArray: Array<CartDetails> = [] for item in session.cartList { let cartItem:CartDetails cartItem = item as! CartDetails if (cartItem.cartType == Music) { /*let musicDetailInfo:MusicDetails musicDetailInfo = cartItem.itemDetails as! MusicDetails*/ musicsArray.append(cartItem) } else if (cartItem.cartType == Books) { /*let bookDetailInfo:BookDetails bookDetailInfo = cartItem.itemDetails as! BookDetails*/ booksArray.append(cartItem) } } bookItemArray = booksArray musicItemArray = musicsArray productTable.separatorStyle = .none productTable.estimatedRowHeight = 95.0 //productTable.rowHeight = UITableViewAutomaticDimension productTable.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { // Hide the navigation bar on the this view controller //self.navigationController?.setNavigationBarHidden(true, animated: true) self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false super.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { // Show the navigation bar on other view controllers self.navigationController?.setNavigationBarHidden(false, animated: true) self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true super.viewWillDisappear(animated) } //MARK: - Private methods // Delete Confirmation and Handling func confirmDelete(title: String) { let alert = UIAlertController(title: "Delete Item", message: "Are you sure you want to permanently delete \(title) from the cart?", preferredStyle: .actionSheet) let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: handleDeleteRow) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: cancelDeleteRow) alert.addAction(deleteAction) alert.addAction(cancelAction) // Support presentation in iPad //alert.popoverPresentationController?.sourceView = self.view //alert.popoverPresentationController?.sourceRect = CGRect(x: 1, y: 1, width: self.view.bounds.size.width / 2.0, height: self.view.bounds.size.height / 2.0) self.present(alert, animated: true, completion: nil) } func handleDeleteRow(alertAction: UIAlertAction!) -> Void { print("Deleteing ...") if let indexPath = deleteIndexPath { var bookDetailObject:BookDetails? = nil var musicDetailObject:MusicDetails? = nil if (indexPath.section == 0) { let cartObject = bookItemArray[indexPath.row] bookDetailObject = cartObject.itemDetails as? BookDetails } else { let cartItem = musicItemArray[indexPath.row] musicDetailObject = cartItem.itemDetails as? MusicDetails } //Update Session Object let session = UserSessionInfo.sharedUser() as UserSessionInfo var index:Int index = 0 for item in session.cartList { let cartItem:CartDetails cartItem = item as! CartDetails if (cartItem.cartType == Books) { let bookDetailInfo:BookDetails bookDetailInfo = cartItem.itemDetails as! BookDetails if (bookDetailInfo.idelement == bookDetailObject?.idelement) { break } } else { let musicDetailInfo:MusicDetails musicDetailInfo = cartItem.itemDetails as! MusicDetails if (musicDetailInfo.idelement == musicDetailObject?.idelement) { break } } index = index + 1 } session.cartList.removeObject(at: index) //Update UI self.productTable.beginUpdates() if (indexPath.section == 0) { bookItemArray.remove(at: indexPath.row) } else { musicItemArray.remove(at: indexPath.row) } // Note that indexPath is wrapped in an array: [indexPath] self.productTable.deleteRows(at: [indexPath], with: .automatic) self.productTable.reloadData() deleteIndexPath = nil self.productTable.endUpdates() //Make callback delegate?.updateCartChange() } } func cancelDeleteRow(alertAction: UIAlertAction!) { print("Cancelling ...") self.productTable.reloadRows(at: [deleteIndexPath], with: .automatic) deleteIndexPath = nil } // MARK: - CartCell stuff func addMinusQuantity(_ isAdd: Bool, cartDetails cartItem: CartDetails, indexPath currentIndexPath: IndexPath) { //Update Session Object let session = UserSessionInfo.sharedUser() as UserSessionInfo var index:Int var bookDetailObject = BookDetails() var musicDetailObject = MusicDetails() var cartObject = CartDetails() if (cartItem.cartType == Books) { bookDetailObject = cartItem.itemDetails as! BookDetails index = 0 for item in session.cartList { cartObject = item as! CartDetails if (cartObject.cartType == Music) { index = index + 1 continue; } let bookDetailInfo:BookDetails bookDetailInfo = cartObject.itemDetails as! BookDetails if (bookDetailInfo.idelement == bookDetailObject.idelement) { if (isAdd == true) { var perUnitCost : Float perUnitCost = Float((cartObject.cost/Float(cartObject.quantity))) cartObject.quantity = (cartObject.quantity + 1) cartObject.cost = (perUnitCost * Float(cartObject.quantity)) break } else { if (cartObject.quantity == 1) { cartObject.quantity = 0 cartObject.cost = 0 } else { var perUnitCost : Float perUnitCost = Float((cartObject.cost/Float(cartObject.quantity))) cartObject.quantity = (cartObject.quantity - 1) cartObject.cost = (perUnitCost * Float(cartObject.quantity)) } break; } } index = index + 1 } } else { musicDetailObject = cartItem.itemDetails as! MusicDetails index = 0 for item in session.cartList { cartObject = item as! CartDetails if (cartObject.cartType == Books) { index = index + 1 continue; } let musicDetailInfo:MusicDetails musicDetailInfo = cartObject.itemDetails as! MusicDetails if (musicDetailInfo.idelement == musicDetailObject.idelement) { if (isAdd == true) { var perUnitCost : Float perUnitCost = Float((cartObject.cost/Float(cartObject.quantity))) cartObject.quantity = (cartObject.quantity + 1) cartObject.cost = (perUnitCost * Float(cartObject.quantity)) break } else { if (cartObject.quantity == 1) { cartObject.quantity = 0 cartObject.cost = 0 } else { var perUnitCost : Float perUnitCost = Float((cartObject.cost/Float(cartObject.quantity))) cartObject.quantity = (cartObject.quantity - 1) cartObject.cost = (perUnitCost * Float(cartObject.quantity)) } break; } } index = index + 1 } } if (cartObject.quantity == 0) { session.cartList.removeObject(at: index) //Update UI self.productTable.beginUpdates() if (currentIndexPath.section == 0) { print(currentIndexPath.row) bookItemArray.remove(at: currentIndexPath.row) } else { print(currentIndexPath.row) musicItemArray.remove(at: currentIndexPath.row) } // Note that indexPath is wrapped in an array: [indexPath] self.productTable.deleteRows(at: [currentIndexPath], with: .automatic) self.productTable.reloadData() self.productTable.endUpdates() //Make callback delegate?.updateCartChange() } else { //Update our session cart with updated quantity session.cartList[index] = cartObject //Update UI self.productTable.beginUpdates() // Note that indexPath is wrapped in an array: [indexPath] self.productTable.reloadRows(at: [currentIndexPath], with: .automatic) self.productTable.endUpdates() if (bookItemArray.count == 0) || (musicItemArray.count == 0) { self.productTable.reloadData() } //Make callback delegate?.updateCartChange() } } // MARK: - UITableView stuf func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (section == 0) { return bookItemArray.count; } else { return musicItemArray.count; } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 85.0;//Choose your custom row height } func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return ""; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cartcell", for: indexPath as IndexPath) as! CartCell; cell.contentView.backgroundColor = UIColor.clear cell.delegate = self cell.currentIndexPath = indexPath if (indexPath.section == 0) { //Books let cartObject = bookItemArray[indexPath.row] let bookDetailObject:BookDetails bookDetailObject = cartObject.itemDetails as! BookDetails cell.titleLabel.text = bookDetailObject.productTitle cell.subTitleLabel.text = bookDetailObject.productSubTitle.uppercased() cell.quantityLabel.text = "Quantity: " + String(cartObject.quantity) cell.priceLabel.text = String(cartObject.cost) + " €" cell.profileImageView?.image = bookDetailObject.bookImage; cell.cartObject = cartObject; } else { //Music let cartItem = musicItemArray[indexPath.row] let musicDetailObject:MusicDetails musicDetailObject = cartItem.itemDetails as! MusicDetails cell.titleLabel.text = musicDetailObject.productTitle cell.subTitleLabel.text = musicDetailObject.productSubTitle.uppercased() let quantityString = "Quantity: " + String(cartItem.quantity) cell.quantityLabel.text = quantityString cell.priceLabel.text = String(cartItem.cost) + " €" cell.profileImageView?.image = musicDetailObject.musicImage; cell.cartObject = cartItem; } cell.profileImageView?.layer.cornerRadius = 4; cell.profileImageView?.layer.masksToBounds = true; let whiteRoundedView : UIView = UIView(frame: CGRect(x: 7, y: 4, width: self.view.frame.size.width - 17, height: cell.frame.size.height)) whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 0.9]) whiteRoundedView.layer.masksToBounds = false whiteRoundedView.layer.cornerRadius = 2.0 whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1) whiteRoundedView.layer.shadowOpacity = 0.2 cell.contentView.addSubview(whiteRoundedView) cell.contentView.sendSubview(toBack: whiteRoundedView) return cell } func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRow(at: indexPath as IndexPath, animated: true) } func tableView( _ tableView : UITableView, titleForHeaderInSection section: Int)->String? { var header:String header = "" if (section == 0) { //Books if (bookItemArray.count == 0) { header = ""; } else { header = arrayHeaders[section] } } else { //Music if (musicItemArray.count == 0) { header = ""; } else { header = arrayHeaders[section] } } return header; } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { deleteIndexPath = indexPath if (indexPath.section == 0) { let cartObject = bookItemArray[indexPath.row] let bookDetailObject:BookDetails bookDetailObject = cartObject.itemDetails as! BookDetails confirmDelete(title: bookDetailObject.productTitle) } else { let cartItem = musicItemArray[indexPath.row] let musicDetailObject:MusicDetails musicDetailObject = cartItem.itemDetails as! MusicDetails confirmDelete(title: musicDetailObject.productTitle) } } } func numberOfSections(in tableView: UITableView) -> Int { var numOfSections: Int = 0 if (bookItemArray.count == 0) && (musicItemArray.count == 0) { let noDataLabel: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height)) noDataLabel.text = "No items in cart" noDataLabel.textColor = UIColor.black noDataLabel.textAlignment = .center tableView.backgroundView = noDataLabel tableView.separatorStyle = .none numOfSections = 2 } else { numOfSections = 2 } return numOfSections } // MARK: - HQPagerMenuViewItemProvider func menuViewItemOf(inPager pagerViewController: HQPagerViewController) -> HQPagerMenuViewItemProvider { let item = HQPagerMenuViewItemProvider(title: tabTitle, normalImage: tabNormalIconImage, selectedImage: tabHighlightedIconImage, selectedBackgroundColor: tabColori) let vc = pagerViewController as! CartViewController vc.bottomBarHeight.constant = 75 vc.totalCost.isHidden = false return item } }
mit
8311db12ba04286a25c3d10547cc6df8
33.005396
172
0.527424
5.588826
false
false
false
false
kamleshgk/iOSStarterTemplate
foodcolors/Classes/ViewControllers/MusicDetailViewController.swift
1
12093
// // MusicDetailViewController.swift // foodcolors // // Created by kamyFCMacBook on 1/18/17. // Copyright © 2017 foodcolors. All rights reserved. // import UIKit class MusicDetailViewController: UIViewController { @IBOutlet weak var musicImage: UIImageView! @IBOutlet weak var subTitleLabel: UILabel! @IBOutlet weak var costLabel: UILabel! @IBOutlet weak var productDescription: UITextView! @IBOutlet var pickerViewBox: UIView! @IBOutlet weak var pickerShowButton1: UIButton! @IBOutlet weak var pickerShowButton2: UIButton! @IBOutlet weak var quantityLabel: UILabel! @IBOutlet weak var totalCostLabel: UILabel! @IBOutlet weak var addCartButton: UIButton! var quantitySelected:Int = -1 var musicDetailObject : MusicDetails? = nil @IBOutlet weak var textViewHeightContraint: NSLayoutConstraint! @IBOutlet weak var scrollBarHeightConstraint: NSLayoutConstraint! @IBOutlet weak var messageView: UIView! @IBOutlet weak var messageLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() pickerViewBox.layer.cornerRadius = 10 let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor(red: 0.42, green: 0.81, blue: 0.023, alpha: 1.0)] self.navigationController!.navigationBar.titleTextAttributes = titleDict as? [String : AnyObject] view.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor).isActive = true self.messageView.layer.borderWidth = 1 self.messageView.layer.borderColor = UIColor(red: 0.42, green: 0.81, blue: 0.023, alpha: 1.0).cgColor } override func viewWillAppear(_ animated: Bool) { if ((musicDetailObject) != nil) { quantitySelected = -1 var image = UIImage(named: "Placeholder") if (musicDetailObject?.musicImage != nil) { image = (musicDetailObject?.musicImage)! as UIImage } else { image = UIImage(named: "Placeholder") } musicImage.image = image let label = UILabel(frame: CGRect(x:0, y:0, width:400, height:50)) label.backgroundColor = UIColor.clear label.numberOfLines = 2 label.font = UIFont.boldSystemFont(ofSize: 16.0) label.textAlignment = .center label.textColor = UIColor(red: 0.42, green: 0.81, blue: 0.023, alpha: 1.0) label.text = musicDetailObject?.productTitle self.navigationItem.titleView = label subTitleLabel.text = musicDetailObject?.productSubTitle costLabel.text = (musicDetailObject?.price)! + " €" productDescription.text = musicDetailObject?.description textViewHeightContraint.constant = productDescription.sizeThatFits(CGSize(width: CGFloat(productDescription.frame.size.width), height: CGFloat(CGFloat.greatestFiniteMagnitude))).height quantityLabel.text = "1" let priceInt:Float? = Float((musicDetailObject?.price)!) //let quantityInt:Float? = Float((bookDetailObject?.quantityAvailable)!) let totalCost:Float? = Float(priceInt! * 1) let myStringToTwoDecimals = String(format:"%.2f", totalCost!) totalCostLabel.text = "Total: " + myStringToTwoDecimals + " €" } messageView.isHidden = true messageLabel.isHidden = true messageView.isHidden = true messageLabel.isHidden = true let session = UserSessionInfo.sharedUser() as UserSessionInfo let cartImage = UIImage(named: "carts") let myBarButtonItem = UIBarButtonItem(badge: "0", image: cartImage!, target: self, action: #selector(self.goKart)) if (session.cartList.count == 0) { myBarButtonItem.badgeString = "0" } else { myBarButtonItem.badgeString = String(session.cartList.count) var musicExistsInCart:Bool musicExistsInCart = false var quantityInCart:Int32 = 0 var index:Int index = 0 for item in session.cartList { let cartItem:CartDetails cartItem = item as! CartDetails if (cartItem.cartType == Books) { index = index + 1 continue } let musicDetailInfo:MusicDetails musicDetailInfo = cartItem.itemDetails as! MusicDetails if (musicDetailInfo.idelement == self.musicDetailObject?.idelement) { quantityInCart = cartItem.quantity //Book already exists in Cart musicExistsInCart = true break } index = index + 1 } if (musicExistsInCart == true) { //update the quantity of that product in the cart self.showDodo(quantity: Int(quantityInCart)) } } self.navigationItem.rightBarButtonItem = nil if (session.cartList.count == 0) { myBarButtonItem.badgeString = "0" } else { myBarButtonItem.badgeString = String(session.cartList.count) } self.navigationItem.rightBarButtonItem = myBarButtonItem } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Button Handlers @IBAction func pickerShow(_ sender: Any) { self.showPicker(sender) } @IBAction func pickerShowAgain(_ sender: Any) { self.showPicker(sender) } @IBAction func addCartACtion(_ sender: Any) { self.navigationItem.rightBarButtonItem = nil let session = UserSessionInfo.sharedUser() as UserSessionInfo let cartImage = UIImage(named: "carts") let myBarButtonItem = UIBarButtonItem(badge: "0", image: cartImage!, target: self, action: #selector(self.goKart)) let cartObject = CartDetails() cartObject.cartType = Music cartObject.itemDetails = self.musicDetailObject let price:Float? = Float((self.musicDetailObject?.price)!) let quantityString = self.quantityLabel.text let totalCost:Float? = Float(price! * Float(quantityString!)!) if (session.cartList.count == 0) { //If there are no products in Cart, blindly add it cartObject.quantity = Int32(quantityString!)! cartObject.cost = totalCost! session.cartList.add(cartObject) self.showDodo(quantity: Int(quantityString!)!) } else { //Else make checks :-| var musicExistsInCart:Bool musicExistsInCart = false var index:Int index = 0 for item in session.cartList { let cartItem:CartDetails cartItem = item as! CartDetails if (cartItem.cartType == Books) { index = index + 1 continue } let bookDetailInfo:MusicDetails bookDetailInfo = cartItem.itemDetails as! MusicDetails if (bookDetailInfo.idelement == self.musicDetailObject?.idelement) { //Book already exists in Cart musicExistsInCart = true break } index = index + 1 } if (musicExistsInCart == true) { //update the quantity of that product in the cart cartObject.quantity = Int32(quantityString!)! cartObject.cost = totalCost! //Update our session cart with new object session.cartList[index] = cartObject self.showDodo(quantity: Int(cartObject.quantity)) /*let alert = UIAlertController(title: "Cart", message: "The quantity is updated in your cart!", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Okay!", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil)*/ } else { cartObject.quantity = Int32(quantityString!)! cartObject.cost = totalCost! session.cartList.add(cartObject) self.showDodo(quantity: Int(quantityString!)!) } } myBarButtonItem.badgeString = String(session.cartList.count) self.navigationItem.rightBarButtonItem = myBarButtonItem } // MARK: - Private Methods func goKart() { self.performSegue(withIdentifier: "showCart", sender: self) } func showPicker(_ sender: Any) { var stringArray : [String] = [] let quantityInt:Int? = Int((musicDetailObject?.quantityAvailable)!) if (self.quantitySelected == -1) { self.quantitySelected = 1 } for index in 0 ..< (quantityInt!) { let stringVal = String((index+1)) stringArray.append(stringVal) //stringArray[index] = stringVal } ActionSheetStringPicker.show(withTitle: "Select Quantity", rows: stringArray, initialSelection: (self.quantitySelected - 1), doneBlock: { picker, value, index in print("value = \(value)") print("index = \(index)") print("picker = \(picker)") let priceInt:Float? = Float((self.musicDetailObject?.price)!) let quantityString = index as! String let totalCost:Float? = Float(priceInt! * Float(quantityString)!) let myStringToTwoDecimals = String(format:"%.2f", totalCost!) self.totalCostLabel.text = "Total: " + myStringToTwoDecimals + " €" self.quantityLabel.text = quantityString self.quantitySelected = Int(quantityString)! return }, cancel: { ActionStringCancelBlock in return }, origin: sender) } private func showDodo(quantity:Int) { let stringVal = " The product is present in the basket with a quantity of " + String(quantity) + " elements" messageLabel.text = stringVal messageView.isHidden = false messageLabel.isHidden = false } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
340aea35968a9e74d50e7e04f61f3f9c
30.473958
196
0.540626
5.371556
false
false
false
false
redlock/JAYSON
JAYSON/Classes/Reflection/Properties.swift
2
2847
struct HashedType : Hashable { let hashValue: Int init(_ theType: Any.Type) { hashValue = unsafeBitCast(theType, to: Int.self) } init<T>(_ pointer: UnsafePointer<T>) { hashValue = pointer.hashValue } } func == (lhs: HashedType, rhs: HashedType) -> Bool { return lhs.hashValue == rhs.hashValue } private var cachedProperties = [HashedType : Array<Property.Description>]() /// An instance property public struct Property { public let key: String public let value: Any /// An instance property description public struct Description { public let key: String public let theType: Any.Type let offset: Int func write(_ value: Any, to storage: UnsafeMutableRawPointer) throws { return try extensions(of: theType).write(value, to: storage.advanced(by: offset)) } } } /// Retrieve properties for `instance` //public func properties(_ instance: Any) throws -> [Property] { // let props = try properties(type(of: instance)) // var copy = extensions(of: instance) // let storage = copy.storage() // return props.map { nextProperty(description: $0, storage: storage) } //} private func nextProperty(description: Property.Description, storage: UnsafeRawPointer) -> Property { return Property( key: description.key, value: extensions(of: description.theType).value(from: storage.advanced(by: description.offset)) ) } /// Retrieve property descriptions for `type` public func properties(_ type: Any.Type) throws -> [Property.Description] { let hashedType = HashedType(type) if let properties = cachedProperties[hashedType] { return properties } else if let nominalType = Metadata.Struct(type) { return try fetchAndSaveProperties(nominalType: nominalType, hashedType: hashedType) } else if let nominalType = Metadata.Class(type) { return try nominalType.properties() } else { throw ReflectionError.notStruct(theType: type) } } func fetchAndSaveProperties<T : NominalType>(nominalType: T, hashedType: HashedType) throws -> [Property.Description] { let properties = try propertiesForNominalType(nominalType) cachedProperties[hashedType] = properties return properties } private func propertiesForNominalType<T : NominalType>(_ theType: T) throws -> [Property.Description] { guard theType.nominalTypeDescriptor.numberOfFields != 0 else { return [] } guard let fieldTypes = theType.fieldTypes, let fieldOffsets = theType.fieldOffsets else { throw ReflectionError.unexpected } let fieldNames = theType.nominalTypeDescriptor.fieldNames return (0..<theType.nominalTypeDescriptor.numberOfFields).map { i in return Property.Description(key: fieldNames[i], theType: fieldTypes[i], offset: fieldOffsets[i]) } }
mit
58690de33f439048f710a09fd6153374
35.974026
119
0.697576
4.217778
false
false
false
false
Chen-Dixi/SwiftHashDict
sy4/sy4/Sorting.swift
1
1064
// // Sorting.swift // sy4 // // Created by Dixi-Chen on 16/6/17. // Copyright © 2016年 Dixi-Chen. All rights reserved. // import Foundation func QuickSort<T:Comparable>(inout list: [T], first: Int, last: Int) { var i, j:Int var key:T if first >= last { return; } i = first j = last key = list[i] while i < j { //找出来比key小的 并排到key前面 while i < j && key < list[j]{ j -= 1 } if i < j { list[i] = list[j] i+=1 } //找出来比key大的 并排到key后面 while i < j && list[i] < key { i+=1 } if i < j { list[j] = list[i] j-=1 } } list[i] = key //将key前面元素递归的进行下一轮排序 if first < i - 1 { QuickSort(&list, first: first, last: i - 1) } //将key后面的元素递归的进行下一轮排序 if i + 1 < last { QuickSort(&list, first: i + 1, last: last) } }
mit
a835f5227f0d8b5f77aac6f4e049cc60
16.685185
70
0.439791
3.051118
false
false
false
false
ashfurrow/eidolon
Kiosk/Bid Fulfillment/KeypadViewModel.swift
2
2297
import Foundation import Action import RxSwift let KeypadViewModelMaxIntegerValue: Currency = 10_000_000 class KeypadViewModel: NSObject { //MARK: - Variables lazy var currencyValue = Variable<Currency>(0) lazy var stringValue = Variable("") // MARK: - Actions lazy var deleteAction: CocoaAction = { return CocoaAction { [weak self] _ in self?.delete() ?? .empty() } }() lazy var clearAction: CocoaAction = { return CocoaAction { [weak self] _ in self?.clear() ?? .empty() } }() lazy var addDigitAction: Action<Int, Void> = { let localSelf = self return Action<Int, Void> { [weak localSelf] input in return localSelf?.addDigit(input) ?? .empty() } }() } private extension KeypadViewModel { func delete() -> Observable<Void> { return Observable.create { [weak self] observer in if let strongSelf = self { strongSelf.currencyValue.value = Currency(strongSelf.currencyValue.value / 10) if strongSelf.stringValue.value.isNotEmpty { var string = strongSelf.stringValue.value string.removeLast() strongSelf.stringValue.value = string } } observer.onCompleted() return Disposables.create() } } func clear() -> Observable<Void> { return Observable.create { [weak self] observer in self?.currencyValue.value = 0 self?.stringValue.value = "" observer.onCompleted() return Disposables.create() } } func addDigit(_ input: Int) -> Observable<Void> { return Observable.create { [weak self] observer in if let strongSelf = self { let newValue = (10 * strongSelf.currencyValue.value) + Currency(input) if (newValue < KeypadViewModelMaxIntegerValue) { strongSelf.currencyValue.value = newValue } strongSelf.stringValue.value = "\(strongSelf.stringValue.value)\(input)" } observer.onCompleted() return Disposables.create() } } }
mit
636a3abf449ef09aed4e45a64d09d5fc
28.831169
94
0.558119
5.07064
false
false
false
false
darrarski/Messages-iOS
MessagesApp/UI/Helpers/UICollectionViewCell_ComputeHeight.swift
1
868
import UIKit extension UICollectionViewCell { func prepareForComputingHeight() { translatesAutoresizingMaskIntoConstraints = false contentView.translatesAutoresizingMaskIntoConstraints = false setNeedsLayout() layoutIfNeeded() prepareForReuse() } func computeHeight(forWidth width: CGFloat) -> CGFloat { bounds = { var bounds = self.bounds bounds.size.width = width return bounds }() setNeedsLayout() layoutIfNeeded() let targetSize = CGSize(width: width, height: 0) let fittingSize = systemLayoutSizeFitting( targetSize, withHorizontalFittingPriority: UILayoutPriorityDefaultHigh, verticalFittingPriority: UILayoutPriorityFittingSizeLevel ) return fittingSize.height } }
mit
69c5359fd59d0cfaaef375fed76340ab
27.933333
71
0.646313
6.888889
false
false
false
false
fthomasmorel/insapp-iOS
Insapp/UserEventsCell.swift
1
2956
// // UserEventsCell.swift // Insapp // // Created by Florent THOMAS-MOREL on 2/9/17. // Copyright © 2017 Florent THOMAS-MOREL. All rights reserved. // import Foundation import UIKit protocol UserEventsDelegate { func showAllEventAction() func show(event: Event, forAssociation association: Association) } let kUserEventsCell = "kUserEventsCell" class UserEventsCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var tableView: UITableView! var events: [Event] = [] var associations: [String : Association] = [:] var delegate: UserEventsDelegate? override func layoutSubviews() { self.tableView.dataSource = self self.tableView.delegate = self self.tableView.showsHorizontalScrollIndicator = false self.tableView.separatorStyle = .none self.tableView.register(UINib(nibName: "EventListCell", bundle: nil), forCellReuseIdentifier: kEventListCell) } func load(events: [Event], forAssociations associations: [String : Association], isSelf: Bool) { self.events = events self.associations = associations if isSelf { self.titleLabel.text = "Mes Évènements" }else{ self.titleLabel.text = "Évènements" self.events = Event.filter(events: self.events) } self.tableView.reloadData() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return min(3, self.events.count) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let event = self.events[indexPath.row] (cell as! EventListCell).load(event: event, withColor: .black) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: kEventListCell, for: indexPath) as! EventListCell return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let event = self.events[indexPath.row] let association = self.associations[event.association!] self.delegate?.show(event: event, forAssociation: association!) } static func getHeightForEvents(events: [Event], isSelf: Bool) -> CGFloat{ var events = events if !isSelf { events = Event.filter(events: events) } return CGFloat(min(events.count, 3) * 60 + (events.count > 0 ? 47 + 30 : 0 )) } @IBAction func seeAllAction(_ sender: Any) { self.delegate?.showAllEventAction() } }
mit
005724e47e449ee346c598f0b8001208
32.91954
117
0.663504
4.639937
false
false
false
false
tomerciucran/space-game
spacegame/StarfieldNode.swift
1
1375
// // StarfieldNode.swift // spacegame // // Created by Tomer Ciucran on 9/8/16. // Copyright © 2016 Tomer Ciucran. All rights reserved. // import SpriteKit class StarfieldNode: SKEmitterNode { static func initialize(_ frame: CGRect, color: SKColor, starSpeedY: CGFloat, starsPerSecond: CGFloat, starScaleFactor: CGFloat) -> SKEmitterNode { // Determine the time a star is visible on screen let lifetime = frame.size.height * UIScreen.main.scale / starSpeedY // Create the emitter node let emitterNode = SKEmitterNode() emitterNode.particleTexture = SKTexture(imageNamed: "star") emitterNode.particleBirthRate = starsPerSecond emitterNode.particleColor = SKColor.lightGray emitterNode.particleSpeed = starSpeedY * -1 emitterNode.particleScale = starScaleFactor emitterNode.particleColorBlendFactor = 1 emitterNode.particleLifetime = lifetime // Position in the middle at top of the screen emitterNode.position = CGPoint(x: frame.size.width/2, y: frame.size.height) emitterNode.particlePositionRange = CGVector(dx: frame.size.width, dy: 0) // Fast forward the effect to start with a filled screen emitterNode.advanceSimulationTime(TimeInterval(lifetime)) return emitterNode } }
mit
151616551633350f61ce31e3b93fd577
36.135135
150
0.681951
4.519737
false
false
false
false
skylib/SnapOnboarding-iOS
SnapOnboarding-iOS/SnapOnboarding-iOS/NSURL+withSize.swift
2
940
import Foundation import UIKit internal extension URL { internal func withSize(_ size: CGSize) -> URL { let scale = UIScreen.main.scale let scaledSize = CGSize(width: size.width * scale, height: size.height * scale) if (scaledSize.width != 512 && scaledSize.height != 512) && (scaledSize.height != 512 && scaledSize.width != 512) { var absoluteString = self.absoluteString if let squareRange = absoluteString.range(of: "=-c") { absoluteString = absoluteString.substring(to: squareRange.lowerBound) } guard let fetchingUrl = URL(string: "\(absoluteString)=s\(Int(max(scaledSize.width, scaledSize.height)))-c") else { return URL(string: "https://snapsale.com")! } return fetchingUrl } return self } }
bsd-3-clause
d53b18286c18966efb45dd005ec27231
31.413793
127
0.548936
4.973545
false
true
false
false
suzuki-0000/CountdownLabel
CountdownLabel/LTMorphingLabel/LTMorphingLabel+Anvil.swift
1
11288
// // LTMorphingLabel+Anvil.swift // https://github.com/lexrus/LTMorphingLabel // // The MIT License (MIT) // Copyright (c) 2017 Lex Tang, http://lexrus.com // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files // (the “Software”), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit extension LTMorphingLabel { @objc func AnvilLoad() { startClosures["Anvil\(LTMorphingPhases.start)"] = { self.emitterView.removeAllEmitters() guard self.newRects.count > 0 else { return } let centerRect = self.newRects[Int(self.newRects.count / 2)] _ = self.emitterView.createEmitter( "leftSmoke", particleName: "Smoke", duration: 0.6 ) { (layer, cell) in layer.emitterSize = CGSize(width: 1, height: 1) layer.emitterPosition = CGPoint( x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3) layer.renderMode = CAEmitterLayerRenderMode.additive cell.emissionLongitude = CGFloat(Double.pi / 2) cell.scale = self.font.pointSize / 90.0 cell.scaleSpeed = self.font.pointSize / 130 cell.birthRate = 60 cell.velocity = CGFloat(80 + Int(arc4random_uniform(60))) cell.velocityRange = 100 cell.yAcceleration = -40 cell.xAcceleration = 70 cell.emissionLongitude = CGFloat(-Double.pi / 2) cell.emissionRange = CGFloat(Double.pi / 4) / 5.0 cell.lifetime = self.morphingDuration * 2.0 cell.spin = 10 cell.alphaSpeed = -0.5 / self.morphingDuration } _ = self.emitterView.createEmitter( "rightSmoke", particleName: "Smoke", duration: 0.6 ) { (layer, cell) in layer.emitterSize = CGSize(width: 1, height: 1) layer.emitterPosition = CGPoint( x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3) layer.renderMode = CAEmitterLayerRenderMode.additive cell.emissionLongitude = CGFloat(Double.pi / 2) cell.scale = self.font.pointSize / 90.0 cell.scaleSpeed = self.font.pointSize / 130 cell.birthRate = 60 cell.velocity = CGFloat(80 + Int(arc4random_uniform(60))) cell.velocityRange = 100 cell.yAcceleration = -40 cell.xAcceleration = -70 cell.emissionLongitude = CGFloat(Double.pi / 2) cell.emissionRange = CGFloat(-Double.pi / 4) / 5.0 cell.lifetime = self.morphingDuration * 2.0 cell.spin = -10 cell.alphaSpeed = -0.5 / self.morphingDuration } _ = self.emitterView.createEmitter( "leftFragments", particleName: "Fragment", duration: 0.6 ) { (layer, cell) in layer.emitterSize = CGSize( width: self.font.pointSize, height: 1 ) layer.emitterPosition = CGPoint( x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3 ) cell.scale = self.font.pointSize / 90.0 cell.scaleSpeed = self.font.pointSize / 40.0 cell.color = self.textColor.cgColor cell.birthRate = 60 cell.velocity = 350 cell.yAcceleration = 0 cell.xAcceleration = CGFloat(10 * Int(arc4random_uniform(10))) cell.emissionLongitude = CGFloat(-Double.pi / 2) cell.emissionRange = CGFloat(Double.pi / 4) / 5.0 cell.alphaSpeed = -2 cell.lifetime = self.morphingDuration } _ = self.emitterView.createEmitter( "rightFragments", particleName: "Fragment", duration: 0.6 ) { (layer, cell) in layer.emitterSize = CGSize( width: self.font.pointSize, height: 1 ) layer.emitterPosition = CGPoint( x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3) cell.scale = self.font.pointSize / 90.0 cell.scaleSpeed = self.font.pointSize / 40.0 cell.color = self.textColor.cgColor cell.birthRate = 60 cell.velocity = 350 cell.yAcceleration = 0 cell.xAcceleration = CGFloat(-10 * Int(arc4random_uniform(10))) cell.emissionLongitude = CGFloat(Double.pi / 2) cell.emissionRange = CGFloat(-Double.pi / 4) / 5.0 cell.alphaSpeed = -2 cell.lifetime = self.morphingDuration } _ = self.emitterView.createEmitter( "fragments", particleName: "Fragment", duration: 0.6 ) { (layer, cell) in layer.emitterSize = CGSize( width: self.font.pointSize, height: 1 ) layer.emitterPosition = CGPoint( x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3) cell.scale = self.font.pointSize / 90.0 cell.scaleSpeed = self.font.pointSize / 40.0 cell.color = self.textColor.cgColor cell.birthRate = 60 cell.velocity = 250 cell.velocityRange = CGFloat(Int(arc4random_uniform(20)) + 30) cell.yAcceleration = 500 cell.emissionLongitude = 0 cell.emissionRange = CGFloat(Double.pi / 2) cell.alphaSpeed = -1 cell.lifetime = self.morphingDuration } } progressClosures["Anvil\(LTMorphingPhases.progress)"] = { (index: Int, progress: Float, isNewChar: Bool) in if !isNewChar { return min(1.0, max(0.0, progress)) } let j = Float(sin(Float(index))) * 1.7 return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * j)) } effectClosures["Anvil\(LTMorphingPhases.disappear)"] = { char, index, progress in return LTCharacterLimbo( char: char, rect: self.previousRects[index], alpha: CGFloat(1.0 - progress), size: self.font.pointSize, drawingProgress: 0.0) } effectClosures["Anvil\(LTMorphingPhases.appear)"] = { char, index, progress in var rect = self.newRects[index] if progress < 1.0 { let easingValue = LTEasing.easeOutBounce(progress, 0.0, 1.0) rect.origin.y = CGFloat(Float(rect.origin.y) * easingValue) } if progress > self.morphingDuration * 0.5 { let end = self.morphingDuration * 0.55 self.emitterView.createEmitter( "fragments", particleName: "Fragment", duration: 0.6 ) { (_, _) in }.update { (layer, _) in if progress > end { layer.birthRate = 0 } }.play() self.emitterView.createEmitter( "leftFragments", particleName: "Fragment", duration: 0.6 ) { (_, _) in }.update { (layer, _) in if progress > end { layer.birthRate = 0 } }.play() self.emitterView.createEmitter( "rightFragments", particleName: "Fragment", duration: 0.6 ) { (_, _) in }.update { (layer, _) in if progress > end { layer.birthRate = 0 } }.play() } if progress > self.morphingDuration * 0.63 { let end = self.morphingDuration * 0.7 self.emitterView.createEmitter( "leftSmoke", particleName: "Smoke", duration: 0.6 ) { (_, _) in }.update { (layer, _) in if progress > end { layer.birthRate = 0 } }.play() self.emitterView.createEmitter( "rightSmoke", particleName: "Smoke", duration: 0.6 ) { (_, _) in }.update { (layer, _) in if progress > end { layer.birthRate = 0 } }.play() } return LTCharacterLimbo( char: char, rect: rect, alpha: CGFloat(self.morphingProgress), size: self.font.pointSize, drawingProgress: CGFloat(progress) ) } } }
mit
d21a3a33a4682ea9a365264c665a8755
41.566038
84
0.469326
5.368872
false
false
false
false
michaello/Aloha
AlohaGIF/SpeechRecognizer.swift
1
1867
// // SpeechRecognizer.swift // AlohaGIF // // Created by Michal Pyrka on 17/04/2017. // Copyright © 2017 Michal Pyrka. All rights reserved. // import Speech final class SpeechRecognizer { private lazy var recognizer: SFSpeechRecognizer = { Logger.verbose("Will use SFSpeechRecognizer with locale: \(Locale.current.description)") return SFSpeechRecognizer(locale: Locale.current)! }() //Sometimes error [AFAggregator logDictationFailedWithError:] Error Domain=kAFAssistantErrorDomain Code=203 "Retry" is returned, so should it be retried. func detectSpeechPromise(from audioURL: URL) -> Promise<[SpeechModel]> { return Promise<[SpeechModel]>(work: { fulfill, reject in self.recognizer.recognitionTask(with: self.request(url: audioURL), resultHandler: { result, recognizerError in if let recognizerError = recognizerError { Logger.error("Could not recognize voice from audio. Error message: \(recognizerError.localizedDescription)") reject(recognizerError) } if let bestTranscription = result?.bestTranscription { let speechModelArray = self.speechModels(from: bestTranscription) Logger.debug("Successfully detected speech. Words count: \(speechModelArray.count)") fulfill(speechModelArray) } }) }) } private func speechModels(from result: SFTranscription) -> [SpeechModel] { return result.segments.map(SpeechModel.init) } private func request(url: URL) -> SFSpeechURLRecognitionRequest { let request = SFSpeechURLRecognitionRequest(url: url) request.taskHint = .dictation request.shouldReportPartialResults = false return request } }
mit
5e35fb5462a8039a267d413bb90e2523
38.702128
157
0.653805
5.016129
false
false
false
false
AllisonWangJiaoJiao/KnowledgeAccumulation
09-AlipayDemo/AlipayDemo/ViewController.swift
1
3084
// // ViewController.swift // AlipayDemo // // Created by Allison on 2017/5/5. // Copyright © 2017年 Allison. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func alipayClick(_ sender: UIButton) { alipayFunc() } } extension ViewController{ fileprivate func alipayFunc() -> () { let rsa2PrivateKey = "" let rsaPrivateKey = kRsaPrivateKey; let order = Order() order.app_id = appId // NOTE: 支付接口名称 order.method = "alipay.trade.app.pay" // NOTE: 参数编码格式 order.charset = "utf-8" // NOTE: 当前时间点 let formatter:DateFormatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" order.timestamp = formatter.string(from: Date()) // NOTE: 支付版本 order.version = "1.0"; // NOTE: sign_type设置 order.sign_type = "RSA"; // NOTE: 商品数据 order.biz_content = BizContent() //商品描述 order.biz_content.body = "我是测试数据"; //商品的标题/交易标题/订单标题/订单关键字等 order.biz_content.subject = "1"; // 商户网站唯一订单号 // order.biz_content.out_trade_no = //订单ID(由商家自行制定) order.biz_content.timeout_express = "30m" //超时时间设置 //订单总金额 // order.biz_content.total_amount = String(format: "%.2f", order.biz_content.total_amount) //商品价格 order.biz_content.seller_id = "18721450464" //收款支付宝用户ID //回调url order.notify_url = "http://www.baidu.com" let appScheme = "AlipayDemo" let orderSpec = order.description //将商品信息拼接成字符串 let orderInfo = order.orderInfoEncoded(false) let orderInfoEncoded = order.orderInfoEncoded(true) print(orderInfo) //对订单进行加密签名 var signedString = "" guard let signer = RSADataSigner.init(privateKey: rsa2PrivateKey.characters.count > 1 ?rsa2PrivateKey:rsaPrivateKey) else{ return } if ((rsa2PrivateKey.characters.count > 1)) { signedString = signer.sign(orderInfo, withRSA2: false) } else { signedString = signer.sign(orderInfo, withRSA2: true) } // NOTE: 如果加签成功,则继续执行支付 if (signedString != "") { //应用注册scheme,在AliSDKDemo-Info.plist定义URL types let appScheme = "alisdkdemo"; // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式 let orderString = String(format:"%.2f ", orderInfoEncoded!) + signedString // NOTE: 调用支付结果开始支付 AlipaySDK.defaultService().payOrder(orderString, fromScheme: appScheme, callback: { (dict:[AnyHashable : Any]?) in print(dict) }) } } }
mit
4a7162ac9338906f49386570a80f7d41
23.150442
126
0.614144
3.507712
false
false
false
false
reidmweber/SwiftCSV
SwiftCSVTests/CSVTests.swift
1
2136
// // CSVTests.swift // CSVTests // // Created by naoty on 2014/06/09. // Copyright (c) 2014年 Naoto Kaneko. All rights reserved. // import XCTest import SwiftCSV class CSVTests: XCTestCase { var csv: CSV! var csvWithCRLF: CSV! var csvFromString: CSV! var error: NSErrorPointer = nil override func setUp() { let csvURL = NSBundle(forClass: CSVTests.self).URLForResource("users", withExtension: "csv") do { csv = try CSV(contentsOfURL: csvURL!) } catch let error1 as NSError { error.memory = error1 csv = nil } let csvWithCRLFURL = NSBundle(forClass: CSVTests.self).URLForResource("users_with_crlf", withExtension: "csv") do { csvWithCRLF = try CSV(contentsOfURL: csvWithCRLFURL!) } catch let error1 as NSError { error.memory = error1 csvWithCRLF = nil } let csvString = "id,name,age\n1,Alice,18\n2,Bob,19\n3,Charlie,\n" csvFromString = CSV(string: csvString) } func testHeaders() { XCTAssertEqual(csv.headers, ["id", "name", "age"], "") XCTAssertEqual(csvWithCRLF.headers, ["id", "name", "age"], "") XCTAssertEqual(csvFromString.headers, ["id", "name", "age"], "") } func testRows() { let expects = [ ["id": "1", "name": "Alice", "age": "18"], ["id": "2", "name": "Bob", "age": "19"], ["id": "3", "name": "Charlie", "age": ""], ] XCTAssertEqual(csv.rows, expects, "") XCTAssertEqual(csvWithCRLF.rows, expects, "") XCTAssertEqual(csvFromString.rows, expects, "") } func testColumns() { XCTAssertEqual(["id": ["1", "2", "3"], "name": ["Alice", "Bob", "Charlie"], "age": ["18", "19", ""]], csv.columns, "") XCTAssertEqual(["id": ["1", "2", "3"], "name": ["Alice", "Bob", "Charlie"], "age": ["18", "19", ""]], csvWithCRLF.columns, "") XCTAssertEqual(["id": ["1", "2", "3"], "name": ["Alice", "Bob", "Charlie"], "age": ["18", "19", ""]], csvFromString.columns, "") } }
mit
7ee9d0dadb15bbfb60be6d5c0460aa09
33.983607
137
0.534677
3.704861
false
true
false
false
NoryCao/zhuishushenqi
zhuishushenqi/NewVersion/ZSExtension/ZSExtension/Classes/UICollectionView+QSExtension.swift
2
2037
// // UICollectionView+QSExtension.swift // zhuishushenqi // // Created by yung on 2017/8/22. // Copyright © 2017年 QS. All rights reserved. // import Foundation import UIKit protocol ReusableView: class { static var reuseId: String {get} } extension ReusableView where Self: UIView { static var reuseId: String { return String(describing: self) } } extension UICollectionReusableView: ReusableView { } extension UICollectionView { func qs_registerCellNib<T:UICollectionViewCell>(_ aClass:T.Type){ let name = String(describing: aClass) let nib = UINib(nibName: name, bundle: nil) self.register(nib, forCellWithReuseIdentifier: name) } func qs_registerCellClass<T:UICollectionViewCell>(_ aClass:T.Type){ let name = String(describing:aClass) self.register(aClass, forCellWithReuseIdentifier: name) } func qs_dequeueReusableCell<T:UICollectionViewCell>(_ aClass:T.Type, for indexPath:IndexPath)->T where T:ReusableView{ let name = String(describing:aClass) guard let cell = dequeueReusableCell(withReuseIdentifier: name, for: indexPath) as? T else { fatalError("\(name) is not registered") } return cell } // func qs_registerHeaderFooterNib<T:UIView>(_ aClass:T.Type){ // let name = String(describing: aClass) // let nib = UINib(nibName: name, bundle: nil) // self.register(nib, forHeaderFooterViewReuseIdentifier: name) // } // // func qs_registerHeaderFooterClass<T:UIView>(_ aClass:T.Type){ // let name = String(describing:aClass) // self.register(aClass, forHeaderFooterViewReuseIdentifier: name) // } // // func qs_dequeueReusableHeaderFooterView<T:UIView>(_ aClass:T.Type)->T!{ // let name = String(describing:aClass) // guard let cell = dequeueReusableHeaderFooterView(withIdentifier: name) as? T else { // fatalError("\(name) is not registered") // } // return cell // } }
mit
62208c352921c38a3957e14f5493ab4c
30.78125
122
0.661259
4.273109
false
false
false
false
craiggrummitt/ActionSwift3
ActionSwift3/text/TextFormat.swift
1
1057
// // TextFormat.swift // ActionSwift // // Created by Craig on 27/07/2015. // Copyright (c) 2015 Interactive Coconut. All rights reserved. // import SpriteKit import UIKit /** Set up your text formatting here, add it to your text field with the `defaultTextFormat` property. Get a list of iOS fonts here: http://iosfonts.com Leave leading as -1 and it will be automatically made the same as the font size */ open class TextFormat:Object { open var font = "ArialMT" open var size:CGFloat = 12 open var color = UIColor.black open var leading:CGFloat = 12 open var align:SKLabelHorizontalAlignmentMode = .left public init(font:String = "ArialMT", size:CGFloat = 12, color:UIColor = UIColor.black,leading:CGFloat = -1,align:SKLabelHorizontalAlignmentMode = .left) { self.font = font self.size = size self.color = color if (self.leading == -1) { self.leading = self.size } else { self.leading = leading } self.align = align } }
mit
86b3fe0b8e4cc5571d52d37ccc9796a0
28.361111
158
0.648061
3.94403
false
false
false
false
zach-freeman/swift-localview
ThirdPartyLib/Alamofire/Tests/FileManager+AlamofireTests.swift
2
2950
// // FileManager+AlamofireTests.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension FileManager { // MARK: - Common Directories static var temporaryDirectoryPath: String { return NSTemporaryDirectory() } static var temporaryDirectoryURL: URL { return URL(fileURLWithPath: FileManager.temporaryDirectoryPath, isDirectory: true) } // MARK: - File System Modification @discardableResult static func createDirectory(atPath path: String) -> Bool { do { try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) return true } catch { return false } } @discardableResult static func createDirectory(at url: URL) -> Bool { return createDirectory(atPath: url.path) } @discardableResult static func removeItem(atPath path: String) -> Bool { do { try FileManager.default.removeItem(atPath: path) return true } catch { return false } } @discardableResult static func removeItem(at url: URL) -> Bool { return removeItem(atPath: url.path) } @discardableResult static func removeAllItemsInsideDirectory(atPath path: String) -> Bool { let enumerator = FileManager.default.enumerator(atPath: path) var result = true while let fileName = enumerator?.nextObject() as? String { let success = removeItem(atPath: path + "/\(fileName)") if !success { result = false } } return result } @discardableResult static func removeAllItemsInsideDirectory(at url: URL) -> Bool { return removeAllItemsInsideDirectory(atPath: url.path) } }
mit
a9636d60f1488c6175c079442e7b187a
32.522727
117
0.681356
4.812398
false
false
false
false
sviatoslav/EndpointProcedure
Examples/Using DefaultConfigurationProvider and HTTPRequestDataBuidlerProvider.playground/Sources/Group.swift
2
32295
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // // swiftlint:disable file_length import Foundation import Dispatch /** A `Procedure` subclass which enables the grouping of other procedures. Use `Group`s to associate related operations together, thereby creating higher levels of abstractions. */ open class GroupProcedure: Procedure { public typealias TransformChildErrorsBlockType = (Procedure, inout [Error]) -> Void internal let queue = ProcedureQueue() internal var queueDelegate: GroupQueueDelegate! fileprivate let initialChildren: [Operation] fileprivate var groupCanFinish: CanFinishGroup! fileprivate var groupStateLock = PThreadMutex() // Protected private properties fileprivate var _groupChildren: [Operation] // swiftlint:disable:this variable_name fileprivate var _groupIsFinishing = false // swiftlint:disable:this variable_name fileprivate var _groupIsSuspended = false // swiftlint:disable:this variable_name fileprivate var _groupTransformChildErrorsBlock: TransformChildErrorsBlockType? /// - returns: the operations which have been added to the queue final public var children: [Operation] { get { return groupStateLock.withCriticalScope { _groupChildren } } } /** The default service level to apply to the GroupProcedure and its child operations. This property specifies the service level applied to the GroupProcedure itself, and to operation objects added to the GroupProcedure. If the added operation object has an explicit service level set, that value is used instead. For more, see the NSOperation and NSOperationQueue documentation for `qualityOfService`. */ @available(OSX 10.10, iOS 8.0, tvOS 8.0, watchOS 2.0, *) open override var qualityOfService: QualityOfService { get { return queue.qualityOfService } set { super.qualityOfService = newValue queue.qualityOfService = newValue } } /** - WARNING: Do not call `finish()` on a GroupProcedure or a GroupProcedure subclass. A GroupProcedure finishes when all of its children finish. It is an anti-pattern to call `finish()` directly on a GroupProcedure. To cause a GroupProcedure to finish more quickly, without waiting for all of its children to complete, call `cancel()`. The Group will then cancel all of its children and finish as soon as they have handled cancellation / finished. */ final public override func finish(withErrors errors: [Error] = []) { assertionFailure("Do not call finish() on a GroupProcedure or a GroupProcedure subclass.") // no-op // } /** Designated initializer for GroupProcedure. Create a GroupProcedure with an array of Operation instances. Optionally provide the underlying dispatch queue for the group's internal ProcedureQueue. - parameter underlyingQueue: an optional DispatchQueue which defaults to nil, this parameter is set as the underlying queue of the group's own ProcedureQueue. - parameter operations: an array of Operation instances. Note that these do not have to be Procedure instances - you can use `Foundation.Operation` instances from other sources. */ public init(dispatchQueue underlyingQueue: DispatchQueue? = nil, operations: [Operation]) { assert(operations.filter({ if let procedure = $0 as? Procedure { return procedure.isEnqueued } else { return false } }).isEmpty, "Cannot initialize GroupProcedure with Procedures that have already been added to another queue / GroupProcedure: \(operations.filter({ if let procedure = $0 as? Procedure { return procedure.isEnqueued } else { return false } }))") _groupChildren = operations initialChildren = operations /** GroupProcedure is responsible for calling `finish()` on cancellation once all of its childred have cancelled and finished, and its own finishing operation has finished. Therefore we disable `Procedure`'s automatic finishing mechanisms. */ super.init(disableAutomaticFinishing: true) queue.isSuspended = true queue.underlyingQueue = underlyingQueue queueDelegate = GroupQueueDelegate(self) queue.delegate = queueDelegate groupCanFinish = CanFinishGroup(group: self) } /// Create a GroupProcedure with a variadic array of Operation instances. /// /// - Parameter operations: a variadic array of `Operation` instances. public convenience init(operations: Operation...) { self.init(operations: operations) } deinit { // To ensure that any remaining operations on the internal queue are released // we must cancelAllOperations and also ensure the queue is not suspended. queue.cancelAllOperations() queue.isSuspended = false } // MARK: - Handling Cancellation // GroupProcedure child cancellation can be safely handled without dispatching to the EventQueue. // // This function is called internally by the Group's .cancel() (Procedure.cancel()) // prior to dispatching DidCancel observers on the Group's EventQueue. override func _procedureDidCancel(withAdditionalErrors additionalErrors: [Error]) { if additionalErrors.isEmpty { children.forEach { $0.cancel() } } else { let (operations, procedures) = children.operationsAndProcedures operations.forEach { $0.cancel() } procedures.forEach { $0.cancel(withError: ProcedureKitError.parent(cancelledWithErrors: additionalErrors)) } } // the GroupProcedure ensures that `finish()` is called once all the // children have finished in its CanFinishGroup operation } // MARK: - Execute /// Adds the GroupProcedure's initial child Operations to its internal queue (and other setup). /// /// If the Group is not suspended, the child Operations will execute once they are ready. /// /// - important: When overriding GroupProcedure's `execute()`, always call `super.execute()`. open override func execute() { // Add the initial children to the Group's internal queue. // (This is delayed until execute to allow WillAdd/DidAdd observers set on the Group, post-init (but pre-execute), // to receive the initial children.) add(additional: initialChildren, toOperationsArray: false, alreadyOnEventQueue: true) // Add the CanFinishGroup (which is used to provide concurrency-safety for adding children post-execute). add(canFinishGroup: groupCanFinish) // Unsuspend the Group's internal queue (unless the user has suspended the Group) groupStateLock.withCriticalScope { if !_groupIsSuspended { queue.isSuspended = false } } } // MARK: - GroupWillAddChild override /** This method is called when a child will be added to the Group. (It is called on the Group's EventQueue.) */ open func groupWillAdd(child: Operation) { /* no-op */ } // MARK: - Customizing the Group's Child Error Handling /** This method is called when a child Procedure will finish (with / without errors). (It is called on the Group's EventQueue.) The default behavior is to append the child's errors, if any, to the Group's errors. When subclassing GroupProcedure, you can override this method to execute custom code in response to child Procedures finishing, or to override the default error-aggregating behavior. The child Procedure (and, thus, the Group) will not finish until this method returns. - parameter child: the child Procedure which is finishing - parameter errors: an [Error], the errors of the child Procedure */ open func child(_ child: Procedure, willFinishWithErrors errors: [Error]) { assert(!child.isFinished, "child(_:willFinishWithErrors:) called with a child that has already finished") // Default GroupProcedure error-handling behavior: // - Aggregate errors from child Procedures guard !errors.isEmpty else { return } append(errors: errors, fromChild: child) } /** The transformChildErrorsBlock is called before the GroupProcedure handles child errors. (It is called on the Group's EventQueue.) The block is passed two parameters: - Procedure: the child Procedure that will finish - inout [Error]: the errors that the Group attributes to the child (on input: the errors that the child Procedure will finish with) The array of errors is an `inout` parameter, and may be modified directly. This enables the customization of the errors that the GroupProcedure (or GroupProcedure subclass) attributes to the child and considers in its `child(_:willFinishWithErrors:)` function. - IMPORTANT: This only affects the child errors that the GroupProcedure (or GroupProcedure subclass) utilizes. It does not directly impact the child Procedure itself, nor the child Procedure's errors (if obtained or read directly from the child). */ final public var transformChildErrorsBlock: TransformChildErrorsBlockType? { get { return groupStateLock.withCriticalScope { _groupTransformChildErrorsBlock } } set { assert(!isExecuting, "Do not modify the child errors block after the Group has started.") groupStateLock.withCriticalScope { _groupTransformChildErrorsBlock = newValue } } } } // MARK: - GroupProcedure API public extension GroupProcedure { /** Access the underlying queue of the GroupProcedure. - returns: the underlying DispatchQueue of the groups private ProcedureQueue */ final var dispatchQueue: DispatchQueue? { return queue.underlyingQueue } /** The maximum number of child operations that can execute at the same time. The value in this property affects only the operations that the current GroupProcedure has executing at the same time. Other operation queues and GroupProcedures can also execute their maximum number of operations in parallel. Reducing the number of concurrent operations does not affect any operations that are currently executing. Specifying the value NSOperationQueueDefaultMaxConcurrentOperationCount (which is recommended) causes the system to set the maximum number of operations based on system conditions. The default value of this property is NSOperationQueueDefaultMaxConcurrentOperationCount. */ final var maxConcurrentOperationCount: Int { get { return queue.maxConcurrentOperationCount } set { queue.maxConcurrentOperationCount = newValue } } /** A Boolean value indicating whether the GroupProcedure is actively scheduling operations for execution. When the value of this property is false, the GroupProcedure actively starts child operations that are ready to execute once the GroupProcedure has been executed. Setting this property to true prevents the GroupProcedure from starting any child operations, but already executing child operations continue to execute. You may continue to add operations to a GroupProcedure that is suspended but those operations are not scheduled for execution until you change this property to false. The default value of this property is false. */ final var isSuspended: Bool { get { return groupStateLock.withCriticalScope { _groupIsSuspended } } set { groupStateLock.withCriticalScope { log.verbose(message: "isSuspended = \(newValue), (old value: \(_groupIsSuspended))") _groupIsSuspended = newValue queue.isSuspended = newValue } } } } public extension GroupProcedure { // MARK: - Add Child API /** Add a single child Operation instance to the group - parameter child: an Operation instance */ final func add(child: Operation, before pendingEvent: PendingEvent? = nil) { add(children: child, before: pendingEvent) } /** Add children Operation instances to the group - parameter children: a variable number of Operation instances */ final func add(children: Operation..., before pendingEvent: PendingEvent? = nil) { add(children: children, before: pendingEvent) } /** Add a sequence of Operation instances to the group - parameter children: a sequence of Operation instances */ final func add<Children: Collection>(children: Children, before pendingEvent: PendingEvent? = nil) where Children.Iterator.Element: Operation { add(additional: children, toOperationsArray: true, before: pendingEvent) } private func shouldAdd<Additional: Collection>(additional: Additional, toOperationsArray shouldAddToProperty: Bool) -> Bool where Additional.Iterator.Element: Operation { return groupStateLock.withCriticalScope { guard !_groupIsFinishing else { assertionFailure("Cannot add new operations to a group after the group has started to finish.") return false } // Debug check whether any of the additional Procedures have already been added to another queue/Group. assert(additional.filter({ if let procedure = $0 as? Procedure { return procedure.isEnqueued } else { return false } }).isEmpty, "Cannot add Procedures to a GroupProcedure that have already been added to another queue / GroupProcedure: \(additional.filter({ if let procedure = $0 as? Procedure { return procedure.isEnqueued } else { return false } }))") // Add the new children as a dependencies of the internal GroupCanFinish operation groupCanFinish.add(dependencies: additional) // Add the new children to the Group's internal `children` array if shouldAddToProperty { let childrenToAdd: [Operation] = Array(additional) _groupChildren.append(contentsOf: childrenToAdd) } return true } } /** Adds one or more operations to the Group. */ final fileprivate func add<Additional: Collection>(additional: Additional, toOperationsArray shouldAddToProperty: Bool, before pendingEvent: PendingEvent? = nil, alreadyOnEventQueue: Bool = false) where Additional.Iterator.Element: Operation { // Exit early if there are no children in the collection guard !additional.isEmpty else { return } // Check to see if should add child operations, depending on finishing state // (Also enters the groupIsAddingOperations group) guard shouldAdd(additional: additional, toOperationsArray: shouldAddToProperty) else { let message = !isFinished ? "started to finish" : "completed" assertionFailure("Cannot add new children to a group after the group has \(message).") return } log.verbose(message: "is adding \(additional.count) child operations to the queue.") // If the Group is cancelled, cancel the additional operations if isCancelled { additional.forEach { if !$0.isCancelled { $0.cancel() } } } // Step 2: guard alreadyOnEventQueue else { dispatchEvent { self.addOperation_step2(additional: additional, before: pendingEvent) } return } addOperation_step2(additional: additional, before: pendingEvent) } fileprivate func addOperation_step2<Additional: Collection>(additional: Additional, before pendingEvent: PendingEvent?) where Additional.Iterator.Element: Operation { eventQueue.debugAssertIsOnQueue() // groupWillAdd(child:) override additional.forEach { self.groupWillAdd(child: $0) } // WillAddOperation observers let willAddObserversGroup = self.dispatchObservers(pendingEvent: PendingEvent.addOperation) { observer, _ in additional.forEach { observer.procedure(self, willAdd: $0) } } optimizedDispatchEventNotify(group: willAddObserversGroup) { // Add to queue self.queue.add(operations: additional, withContext: self.queueAddContext).then(on: self) { if let pendingEvent = pendingEvent { pendingEvent.doBeforeEvent { self.log.verbose(message: "Children (\(additional)) added prior to (\(pendingEvent)).") } } // DidAddOperation observers let didAddObserversGroup = self.dispatchObservers(pendingEvent: PendingEvent.postDidAdd) { observer, _ in additional.forEach { observer.procedure(self, didAdd: $0) } } self.optimizedDispatchEventNotify(group: didAddObserversGroup) { self.log.verbose(message: "finished adding child operations to the queue.") } } } } } public extension GroupProcedure { // MARK: - Aggregating Errors /// Append an error to the Group's errors /// /// - Parameter error: an Error final public func append(error: Error, fromChild child: Operation? = nil) { if let child = child { log.warning(message: "\(child.operationName) did encounter error: \(error).") } else { log.warning(message: "Appending error: \(error).") } append(errors: [error]) } /// Append errors to the Group's errors /// /// - Parameter errors: an [Error] /// - Parameter child: a child Operation final public func append(errors: [Error], fromChild child: Operation? = nil) { if let child = child { log.warning(message: "\(child.operationName) did encounter \(errors.count) errors.") } else { log.warning(message: "Appending \(errors.count) errors.") } append(errors: errors) } } // MARK: - GroupProcedure Private Queue Delegate internal extension GroupProcedure { /** The group utilizes a GroupQueueDelegate to effectively act as its own delegate for its own internal queue, while keeping this implementation detail private. When an operation is added to the queue, assuming that the group is not yet finishing or finished, then we add the operation as a dependency to an internal "barrier" operation that separates executing from finishing state. This serves to keep the internal operation as a final child operation that executes when there are no more operations in the group operation, safely handling the transition of group operation state. */ internal class GroupQueueDelegate: ProcedureQueueDelegate { private weak var group: GroupProcedure? init(_ group: GroupProcedure) { self.group = group } func procedureQueue(_ queue: ProcedureQueue, willAddOperation operation: Operation, context: Any?) -> ProcedureFuture? { guard let strongGroup = group else { return nil } guard queue === strongGroup.queue else { return nil } return strongGroup.willAdd(operation: operation, context: context) } func procedureQueue(_ queue: ProcedureQueue, willAddProcedure procedure: Procedure, context: Any?) -> ProcedureFuture? { guard let strongGroup = group else { return nil } guard queue === strongGroup.queue else { return nil } return strongGroup.willAdd(operation: procedure, context: context) } public func procedureQueue(_ queue: ProcedureQueue, willFinishProcedure procedure: Procedure, withErrors initialErrors: [Error]) -> ProcedureFuture? { guard let strongGroup = group else { return nil } guard queue === strongGroup.queue else { return nil } /// If the group is cancelled, exit early guard !strongGroup.isCancelled else { return nil } let promise = ProcedurePromise() strongGroup.dispatchEvent { defer { promise.complete() } var childErrors: [Error] = initialErrors if let transformChildErrors = strongGroup.transformChildErrorsBlock { // transform child errors transformChildErrors(procedure, &childErrors) strongGroup.log.verbose(message: "Child errors for <\(procedure.operationName)> \((initialErrors.count != childErrors.count) ? "were transformed." : "were passed to transform block.")\n\t Initial errors ((initialErrors.count)): \(initialErrors)\n\t Transformed errors (\(childErrors.count)): \(childErrors)") } // handle child errors strongGroup.child(procedure, willFinishWithErrors: childErrors) } return promise.future } } private func shouldAdd(operation: Operation) -> Bool { return groupStateLock.withCriticalScope { guard !_groupIsFinishing else { assertionFailure("Cannot add new operations to a group after the group has started to finish.") return false } // Add the new child as a dependency of the internal GroupCanFinish operation groupCanFinish.addDependency(operation) // Add the new child to the Group's internal children array _groupChildren.append(operation) return true } } /** - returns: a `ProcedureFuture` that is signaled once the Group has fully prepared for the operation to be added to its internal queue (including notifying all WillAdd observers) */ private func willAdd(operation: Operation, context: Any?) -> ProcedureFuture? { if let context = context as? ProcedureQueueContext, context === queueAddContext { // The Procedure adding the operation to the Group's private queue is the Group itself // // which means it could only have come from: // - self.add(child:) (and convenience overloads) // // which will handle the setup-work for this operation in the context of the Group // (asynchronously) so there is nothing to do here - exit early return nil } // The Procedure adding the operation to the Group's private queue is *not* the Group. // // It could have come from: // - a child.produce(operation:) // - an Operation (NSOperation) subclass calling OperationQueue.current.addOperation() // (which is not at all recommended, but is possible from an Operation subclass) // // In either case, the operation has not yet been handled in the context of the Group // (i.e. adding it as a child, adding it as a dependency on finishing, notifying Group // Will/DidAddOperation observers) thus it must be handled here: // assert(!isFinished, "Cannot add new operations to a group after the group has completed.") guard shouldAdd(operation: operation) else { return nil } let promise = ProcedurePromise() // If the Group is already cancelled, ensure that the new child is cancelled. if isCancelled && !operation.isCancelled { operation.cancel() } // Dispatch the next step (observers, etc) asynchronously on the Procedure EventQueue dispatchEvent { self.willAdd_step2(operation: operation, promise: promise) } return promise.future } private func willAdd_step2(operation: Operation, promise: ProcedurePromise) { eventQueue.debugAssertIsOnQueue() // groupWillAdd(child:) override groupWillAdd(child: operation) // WillAddOperation observers let willAddObserversGroup = dispatchObservers(pendingEvent: PendingEvent.addOperation) { observer, _ in observer.procedure(self, willAdd: operation) } optimizedDispatchEventNotify(group: willAddObserversGroup) { // Complete the promise promise.complete() // DidAddOperation observers _ = self.dispatchObservers(pendingEvent: PendingEvent.postDidAdd) { observer, _ in observer.procedure(self, didAdd: operation) } // Note: no need to wait on DidAddOperation observers - nothing left to do. } } } // MARK: - Finishing fileprivate extension GroupProcedure { fileprivate final class CanFinishGroup: Operation { private weak var group: GroupProcedure? private var _isFinished = false private var _isExecuting = false private let stateLock = PThreadMutex() init(group: GroupProcedure) { self.group = group super.init() } fileprivate override func start() { // Override Operation.start() because this operation may have to // finish asynchronously (if it has to register to be notified when // operations are no longer being added concurrently). // // Since we override start(), it is important to send Operation // isExecuting / isFinished KVO notifications. // // (Otherwise, the operation may not be released, there may be // problems with dependencies, with the queue's handling of // maxConcurrentOperationCount, etc.) isExecuting = true main() } override func main() { execute() } func execute() { if let group = group { group.log.verbose(message: "executing can finish group operation.") // All operations that were added as a side-effect of anything up to // WillFinishObservers of prior operations should have been executed. // // Handle an edge case caused by concurrent calls to Group.add(children:) enum GroupCanFinishResult { case canFinishNow case waitingOnNewChildren(CanFinishGroup, [Operation]) } let isWaiting: GroupCanFinishResult = group.groupStateLock.withCriticalScope { // Check whether new children were added prior to the lock // (i.e. after the queue decided to start the CanFinish operation) // by checking for child operations that are not finished. let active = group._groupChildren.filter({ !$0.isFinished }) if !active.isEmpty { // Children were added after this CanFinishOperation became // ready, but before it executed or before the lock could be acquired. group.log.verbose(message: "cannot finish now, as there are children still active.") // The GroupProcedure should wait for these children to finish // before finishing. Add the oustanding children as // dependencies to a new CanFinishGroup, and add that as the // Group's new CanFinishGroup. let newCanFinishGroup = GroupProcedure.CanFinishGroup(group: group) group.groupCanFinish = newCanFinishGroup return .waitingOnNewChildren(newCanFinishGroup, active) } else { // There are no additional children to handle. // Ensure that no new operations can be added. group.log.verbose(message: "can now finish.") group._groupIsFinishing = true return .canFinishNow } } // End of isWaiting switch isWaiting { case .canFinishNow: // trigger an immediate finish of the parent Group group._finishGroup() case .waitingOnNewChildren(let newCanFinishGroup, let newChildrenToWaitOn): // add the new children as dependencies to the newCanFinishGroup, // (which is already set as the `group.groupCanFinish` inside the lock // above) and then add the newCanFinishGroup to the group's internal queue newCanFinishGroup.add(dependencies: newChildrenToWaitOn) group.add(canFinishGroup: newCanFinishGroup) // continue on to finish this CanFinishGroup operation // (the newCanFinishGroup takes over responsibility) break } } isExecuting = false isFinished = true } override private(set) var isExecuting: Bool { get { return stateLock.withCriticalScope { _isExecuting } } set { willChangeValue(forKey: .executing) stateLock.withCriticalScope { _isExecuting = newValue } didChangeValue(forKey: .executing) } } override private(set) var isFinished: Bool { get { return stateLock.withCriticalScope { _isFinished } } set { willChangeValue(forKey: .finished) stateLock.withCriticalScope { _isFinished = newValue } didChangeValue(forKey: .finished) } } } fileprivate func add(canFinishGroup: CanFinishGroup) { queue.add(canFinishGroup: canFinishGroup) } } fileprivate extension GroupProcedure { fileprivate func _finishGroup() { // Because errors have been added throughout to the (superclass) Procedure's `errors`, // there is no need to pass any additional errors to the call to finish(). super.finish() queue.isSuspended = true } } fileprivate extension ProcedureQueue { func add(canFinishGroup: GroupProcedure.CanFinishGroup) { // Do not add observers (not needed - CanFinishGroup is an implementation detail of Group) // Do not add conditions (CanFinishGroup has none) // Call OperationQueue.addOperation() directly super.addOperation(canFinishGroup) } } // MARK: - Unavailable public extension GroupProcedure { @available(*, unavailable, renamed: "children") var operations: [Operation] { return children } @available(*, unavailable, renamed: "isSuspended") final var suspended: Bool { return isSuspended } @available(*, unavailable, renamed: "add(child:)") func addOperation(operation: Operation) { } @available(*, unavailable, renamed: "add(children:)") func addOperations(operations: Operation...) { } @available(*, unavailable, renamed: "add(children:)") func addOperations(additional: [Operation]) { } @available(*, unavailable, message: "GroupProcedure child error handling customization has been re-worked. Consider overriding child(_:willFinishWithErrors:).") final public func childDidRecoverFromErrors(_ child: Operation) { } @available(*, unavailable, message: "GroupProcedure child error handling customization has been re-worked. Consider overriding child(_:willFinishWithErrors:).") final public func childDidNotRecoverFromErrors(_ child: Operation) { } @available(*, unavailable, renamed: "append(error:)") final public func append(fatalError error: Error) { } @available(*, unavailable, renamed: "append(errors:)") final public func append(fatalErrors errors: [Error]) { } }
mit
c6d0fd8dd2bed488a1321ef725b764dc
40.034307
365
0.651019
5.25362
false
false
false
false
mathcamp/swiftz
swiftz/ArrayZipper.swift
2
1725
// // ArrayZipper.swift // swiftz // // Created by Alexander Ronald Altman on 8/4/14. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // import Foundation import swiftz_core public final class ArrayZipper<A>: ArrayLiteralConvertible { typealias Element = A public let values: [A] public let position: Int public required init(_ values: [A] = [], _ position: Int = 0) { if position < 0 { self.position = 0 } else if position >= values.count { self.position = values.count - 1 } else { self.position = position } self.values = values } public convenience init(arrayLiteral elements: Element...) { self.init(elements, 0) } public func map<B>(f: A -> B) -> ArrayZipper<B> { return f <^> self } public func dup() -> ArrayZipper<ArrayZipper<A>> { return duplicate(self) } public func extend<B>(f: ArrayZipper<A> -> B) -> ArrayZipper<B> { return self ->> f } public func move(n: Int = 1) -> ArrayZipper<A> { return ArrayZipper(values, position + n) } public func moveTo(pos: Int) -> ArrayZipper<A> { return ArrayZipper(values, pos) } } public func extract<A>(xz: ArrayZipper<A>) -> A { return xz.values[xz.position] } public func <^><A, B>(f: A -> B, xz: ArrayZipper<A>) -> ArrayZipper<B> { return ArrayZipper(f <^> xz.values, xz.position) } public func duplicate<A>(xz: ArrayZipper<A>) -> ArrayZipper<ArrayZipper<A>> { return ArrayZipper((0 ..< xz.values.count).map { ArrayZipper(xz.values, $0) }, xz.position) } public func ->><A, B>(xz: ArrayZipper<A>, f: ArrayZipper<A> -> B) -> ArrayZipper<B> { return ArrayZipper((0 ..< xz.values.count).map { f(ArrayZipper(xz.values, $0)) }, xz.position) }
bsd-3-clause
3a6110fed05f0ad440413dda9600b675
24.367647
96
0.637101
3.130672
false
false
false
false
Binlogo/One3-iOS-Swift
One3-iOS/Controllers/Search/SearchViewController.swift
1
5966
// // SearchViewController.swift // One3-iOS // // Created by Binboy_王兴彬 on 2016/12/31. // Copyright © 2016年 Binboy. All rights reserved. // import UIKit import SnapKit enum SearchType: Int { case home case read case music case movie case author static let items: [String] = ["插图", "阅读", "音乐", "影视", "作者/音乐人"] var title: String { return SearchType.items[self.rawValue] } var cellIdentifier: String { switch self { case .home: return ResultCellIdentifier.SearchPictureCellIdentifier.rawValue case .read: return ResultCellIdentifier.SearchReadCellIdentifier.rawValue case .music: return ResultCellIdentifier.SearchMusicCellIdentifier.rawValue case .movie: return ResultCellIdentifier.SearchMovieCellIdentifier.rawValue case .author: return ResultCellIdentifier.SearchAuthorCellIdentifier.rawValue } } } enum ResultCellIdentifier: String { case SearchPictureCellIdentifier case SearchReadCellIdentifier case SearchMusicCellIdentifier case SearchMovieCellIdentifier case SearchAuthorCellIdentifier } class SearchViewController: UIViewController { lazy var searchBar = UISearchBar() lazy var hintView = UIImageView(image: #imageLiteral(resourceName: "search_all")) lazy var segmentedControl = UISegmentedControl(items: SearchType.items) lazy var tableView: UITableView = UITableView(frame: self.view.bounds) lazy var activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray) var searchType: SearchType = .home var dataSource: [String: Any] = [:] override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white setupSubviews() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) searchBar.becomeFirstResponder() } func setupSubviews() { setupSearchBar() setupHintView() setupSegmentedControl() setupTableView() setupActivityIndicatorView() } func setupSearchBar() { navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(SearchViewController.cancelAction)) searchBar.placeholder = "输入搜索内容" searchBar.tintColor = UIColor.navigationBarTintColor searchBar.returnKeyType = .search searchBar.searchBarStyle = .minimal searchBar.delegate = self navigationItem.titleView = searchBar } func setupHintView() { hintView.backgroundColor = UIColor.white view.addSubview(hintView) hintView.snp.makeConstraints { (make) in make.size.equalTo(CGSize(width: 165, height: 110)) make.top.equalTo(view).offset(114) make.centerX.equalTo(view) } } func setupSegmentedControl() { segmentedControl.backgroundColor = UIColor.white segmentedControl.tintColor = UIColor.navigationBarTintColor segmentedControl.selectedSegmentIndex = 0 segmentedControl.addTarget(self, action: #selector(SearchViewController.selectedSegment(_:)), for: .valueChanged) view.addSubview(segmentedControl) segmentedControl.snp.makeConstraints { (make) in make.width.equalTo(UIScreen.main.bounds.width) make.height.equalTo(25) make.left.top.right.equalTo(view).inset(UIEdgeInsetsMake(64, 0, 0, 0)) } segmentedControl.isHidden = true } func setupTableView() { tableView.backgroundColor = UIColor.white tableView.delegate = self tableView.dataSource = self tableView.register(SearchPictureCell.self, forCellReuseIdentifier: ResultCellIdentifier.SearchPictureCellIdentifier.rawValue) tableView.register(SearchReadCell.self, forCellReuseIdentifier: ResultCellIdentifier.SearchReadCellIdentifier.rawValue) tableView.register(SearchMusicCell.self, forCellReuseIdentifier: ResultCellIdentifier.SearchMusicCellIdentifier.rawValue) tableView.register(SearchMovieCell.self, forCellReuseIdentifier: ResultCellIdentifier.SearchMovieCellIdentifier.rawValue) tableView.register(SearchAuthorCell.self, forCellReuseIdentifier: ResultCellIdentifier.SearchAuthorCellIdentifier.rawValue) tableView.tableFooterView = UIView() view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.top.equalTo(segmentedControl.snp.bottom).offset(2) make.left.bottom.right.equalTo(view) } tableView.isHidden = true } func setupActivityIndicatorView() { activityIndicatorView.hidesWhenStopped = true view.addSubview(activityIndicatorView) activityIndicatorView.snp.makeConstraints { (make) in make.center.equalTo(view) } } // MARK: Actions func cancelAction() { searchBar.resignFirstResponder() dismiss(animated: true) } func selectedSegment(_ sender: UISegmentedControl) { searchType = SearchType(rawValue: sender.selectedSegmentIndex)! print(searchType.title) } } extension SearchViewController: UISearchBarDelegate { } extension SearchViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: searchType.cellIdentifier) cell?.textLabel?.text = String.random(ofLength: 8) return cell! } } extension SearchViewController: UITableViewDelegate { }
mit
938ad50e8065051f5ebbd8664b689ba9
33.213873
157
0.68863
5.41042
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Layers/Change sublayer visibility/SublayersTableViewController.swift
1
2644
// Copyright 2016 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class SublayersTableViewController: UITableViewController { /// The sublayers to be displayed in the table view. var sublayers = [AGSArcGISMapImageSublayer]() { didSet { guard isViewLoaded else { return } tableView.reloadData() } } private var tableViewContentSizeObservation: NSKeyValueObservation? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableViewContentSizeObservation = tableView.observe(\.contentSize) { [unowned self] (tableView, _) in self.preferredContentSize = CGSize(width: self.preferredContentSize.width, height: tableView.contentSize.height) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) tableViewContentSizeObservation = nil } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sublayers.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let sublayer = sublayers[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "SublayerCell", for: indexPath) cell.textLabel?.text = sublayer.name // accessory switch let visibilitySwitch = UISwitch(frame: .zero) visibilitySwitch.tag = indexPath.row visibilitySwitch.isOn = sublayer.isVisible visibilitySwitch.addTarget(self, action: #selector(SublayersTableViewController.switchChanged(_:)), for: .valueChanged) cell.accessoryView = visibilitySwitch return cell } @objc func switchChanged(_ sender: UISwitch) { let index = sender.tag // change the visiblity let sublayer = self.sublayers[index] sublayer.isVisible = sender.isOn } }
apache-2.0
a3f0fc79031f7d844c326ea6611a39cd
36.239437
127
0.692511
5.11412
false
false
false
false
liulichao123/fangkuaishou
快手/快手/classes/右侧/首页/model/Video.swift
1
1132
// // Video.swift // swift上传 // // Created by liulichao on 16/5/13. // Copyright © 2016年 刘立超. All rights reserved. // import UIKit /**获取的网络数据video模型**/ class Video: NSObject { var id: Int? var name: String? var pubDate: String? var scale: Float? var shotUrlPath: String? var urlPath: String? var size: Float? var status: Int? var timeLength: Float? var likes: Int? var user: User? static func instanceWithDict(dict: NSDictionary) -> Video { let v = Video() v.id = dict["id"]?.integerValue v.name = dict["name"] as? String v.pubDate = dict["pubDate"] as? String v.scale = dict["scale"] as? Float v.shotUrlPath = dict["shotUrlPath"] as? String v.urlPath = dict["urlPath"] as? String v.size = dict["size"] as? Float v.status = dict["status"] as? Int v.timeLength = dict["timeLength"] as? Float v.likes = dict["likes"] as? Int let userDict = dict["user"] as? NSDictionary v.user = User.instanceWithDict(userDict!) return v } }
apache-2.0
bcfaae653cda5a89d481579966f5e5d8
25.853659
62
0.585831
3.551613
false
false
false
false
brentdax/swift
test/Inputs/conditional_conformance_subclass.swift
1
13173
public func takes_p1<T: P1>(_: T.Type) {} public protocol P1 { func normal() func generic<T: P3>(_: T) } public protocol P2 {} public protocol P3 {} public struct IsP2: P2 {} public class Base<A> {} extension Base: P1 where A: P2 { public func normal() {} public func generic<T: P3>(_: T) {} } // witness method for Base.normal // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlAaEP6normalyyFTW"(%T32conditional_conformance_subclass4BaseC.0** noalias nocapture swiftself dereferenceable(8), %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[A_P2:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8 // CHECK-NEXT: %"\CF\84_0_0.P2" = bitcast i8* [[A_P2]] to i8** // CHECK-NEXT: [[SELF:%.]] = load %T32conditional_conformance_subclass4BaseC.0*, %T32conditional_conformance_subclass4BaseC.0** %0 // CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass4BaseCA2A2P2RzlE6normalyyF"(i8** %"\CF\84_0_0.P2", %T32conditional_conformance_subclass4BaseC.0* swiftself [[SELF]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // witness method for Base.generic // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW"(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T32conditional_conformance_subclass4BaseC.1** noalias nocapture swiftself dereferenceable(8), %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[A_P2:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8 // CHECK-NEXT: %"\CF\84_0_0.P2" = bitcast i8* [[A_P2]] to i8** // CHECK-NEXT: [[SELF:%.]] = load %T32conditional_conformance_subclass4BaseC.1*, %T32conditional_conformance_subclass4BaseC.1** %1, align 8 // CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass4BaseCA2A2P2RzlE7genericyyqd__AA2P3Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_0_0.P2", i8** %"\CF\84_1_0.P3", %T32conditional_conformance_subclass4BaseC.1* swiftself [[SELF]]) // CHECK-NEXT: ret void // CHECK-NEXT: } public class SubclassGeneric<T>: Base<T> {} public class SubclassConcrete: Base<IsP2> {} public class SubclassGenericConcrete: SubclassGeneric<IsP2> {} public func subclassgeneric_generic<T: P2>(_: T.Type) { takes_p1(SubclassGeneric<T>.self) } // CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s32conditional_conformance_subclass23subclassgeneric_genericyyxmAA2P2RzlF"(%swift.type*, %swift.type* %T, i8** %T.P2) // CHECK-NEXT: entry: // CHECK: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass15SubclassGenericCMa"(i64 0, %swift.type* %T) // CHECK-NEXT: [[SubclassGeneric_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[T_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** %T.P2, i8*** [[T_P2_PTR]], align 8 // CHECK-NEXT: [[Base_P1:%.*]] = call i8** @"$s32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWa"(%swift.type* [[SubclassGeneric_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]]) // CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassGeneric_TYPE]], %swift.type* [[SubclassGeneric_TYPE]], i8** [[Base_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // witness table accessor for Base : P1 // CHECK-LABEL: define{{( dllexport| protected)?}} i8** @"$s32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWa"(%swift.type*, i8***) // CHECK-NEXT: entry: // CHECK-NEXT: [[TABLE:%.*]] = call i8** @swift_getGenericWitnessTable(%swift.generic_witness_table_cache* @"$s32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWG", %swift.type* %0, i8*** %1) // CHECK-NEXT: ret i8** [[TABLE]] // CHECK-NEXT: } public func subclassgeneric_concrete() { takes_p1(SubclassGeneric<IsP2>.self) } // CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s32conditional_conformance_subclass24subclassgeneric_concreteyyF"() // CHECK-NEXT: entry: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMa"(i64 0) // CHECK-NEXT: [[SubclassGeneric_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[Base_P1:%.*]] = call i8** @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWl"() // CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassGeneric_TYPE]], %swift.type* [[SubclassGeneric_TYPE]], i8** [[Base_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // Lazy witness table accessor for the concrete SubclassGeneric<IsP2> : Base. // CHECK-LABEL: define linkonce_odr hidden i8** @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWl"() // CHECK-NEXT: entry: // CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWL", align 8 // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMa"(i64 0) // CHECK-NEXT: [[SubclassGeneric_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s32conditional_conformance_subclass4IsP2VAA0E0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[Base_P1:%.*]] = call i8** @"$s32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWa"(%swift.type* [[SubclassGeneric_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]]) // CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWL" release, align 8 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ] // CHECK-NEXT: ret i8** [[T0]] // CHECK-NEXT: } public func subclassconcrete() { takes_p1(SubclassConcrete.self) } // CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s32conditional_conformance_subclass16subclassconcreteyyF"() // CHECK-NEXT: entry: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass16SubclassConcreteCMa"(i64 0) // CHECK-NEXT: [[SubclassConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[SubclassConcrete_P1:%.*]] = call i8** @"$s32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"() // CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassConcrete_TYPE]], %swift.type* [[SubclassConcrete_TYPE]], i8** [[SubclassConcrete_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK-LABEL: define linkonce_odr hidden i8** @"$s32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"() // CHECK-NEXT: entry: // CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL", align 8 // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass16SubclassConcreteCMa"(i64 0) // CHECK-NEXT: [[SubclassConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s32conditional_conformance_subclass4IsP2VAA0E0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[Base_P1:%.*]] = call i8** @"$s32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWa"(%swift.type* [[SubclassGeneric_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]]) // CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @"$s32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL" release, align 8 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ] // CHECK-NEXT: ret i8** [[T0]] // CHECK-NEXT: } public func subclassgenericconcrete() { takes_p1(SubclassGenericConcrete.self) } // CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s32conditional_conformance_subclass23subclassgenericconcreteyyF"() // CHECK-NEXT: entry: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass23SubclassGenericConcreteCMa"(i64 0) // CHECK-NEXT: [[SubclassGenericConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[SubclassGenericConcrete_P1:%.*]] = call i8** @"$s32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"() // CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassGenericConcrete_TYPE]], %swift.type* [[SubclassGenericConcrete_TYPE]], i8** [[SubclassGenericConcrete_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK-LABEL: define linkonce_odr hidden i8** @"$s32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"() // CHECK-NEXT: entry: // CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL", align 8 // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass23SubclassGenericConcreteCMa"(i64 0) // CHECK-NEXT: [[SubclassGenericConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s32conditional_conformance_subclass4IsP2VAA0E0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[Base_P1:%.*]] = call i8** @"$s32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWa"(%swift.type* [[SubclassGeneric_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]]) // CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @"$s32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL" release, align 8 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ] // CHECK-NEXT: ret i8** [[T0]] // CHECK-NEXT: } // witness tabel instantiation function for Base : P1 // CHECK-LABEL: define internal void @"$s32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWI"(i8**, %swift.type* %"Base<A>", i8**) // CHECK-NEXT: entry: // CHECK-NEXT: [[TABLES:%.*]] = bitcast i8** %1 to i8*** // CHECK-NEXT: [[A_P2_SRC:%.*]] = getelementptr inbounds i8**, i8*** [[TABLES]], i32 0 // CHECK-NEXT: [[A_P2_DEST:%.*]] = getelementptr inbounds i8*, i8** %0, i32 -1 // CHECK-NEXT: [[A_P2:%.*]] = load i8**, i8*** [[A_P2_SRC]], align 8 // CHECK-NEXT: [[CAST_A_P2_DEST:%.*]] = bitcast i8** [[A_P2_DEST]] to i8*** // CHECK-NEXT: store i8** [[A_P2]], i8*** [[CAST_A_P2_DEST]], align 8 // CHECK-NEXT: ret void // CHECK-NEXT: }
apache-2.0
98e405a0e65537f53c1011e313f1967e
66.902062
373
0.68777
3.149175
false
false
false
false
indragiek/Chip8
Chip8Kit/ROM.swift
1
1668
// Copyright © 2015 Indragie Karunaratne. All rights reserved. #if os(Linux) import Glibc #else import Foundation #endif /// ROM (Read Only Memory) data to be loaded into an emulator. public struct ROM { public enum Error: ErrorType { case FileOpenFailed(path: String) case FileReadFailed(path: String) } public let bytes: [UInt8] /// Initializes the receiver using a byte array. public init(bytes: [UInt8]) { self.bytes = bytes } /// Initializes the receiver using a file path. /// /// Throws `Error.FileOpenFailed` if the file cannot be opened, and throws /// `Error.FileReadFailed` if the file cannot be read. public init(path: String) throws { let file = fopen(path, "rb") if file == nil { bytes = [] throw Error.FileOpenFailed(path: path) } defer { fclose(file) } fseek(file, 0, SEEK_END) let fileSize = ftell(file) rewind(file) var buffer = [UInt8](count: fileSize, repeatedValue: 0) let readSize = fread(&buffer, sizeof(UInt8), fileSize, file) if readSize != fileSize { bytes = [] throw Error.FileReadFailed(path: path) } self.bytes = buffer } /// Initializes the receiver using an `NSData` object. #if os(iOS) || os(OSX) public init(data: NSData) { let bytesPtr = unsafeBitCast(data.bytes, UnsafePointer<UInt8>.self) let bytesBufferPtr = UnsafeBufferPointer(start: bytesPtr, count: data.length) self.bytes = Array(bytesBufferPtr) } #endif }
mit
871e55e0e5f61949dc643beaee303f8c
28.245614
85
0.593881
4.198992
false
false
false
false
ProfileCreator/ProfileCreator
ProfileCreator/ProfileCreator/Profile Editor Toolbar/ProfileEditorWindowToolbarItemAdd.swift
1
16890
// // MainWindowToolbarItems.swift // ProfileCreator // // Created by Erik Berglund. // Copyright © 2018 Erik Berglund. All rights reserved. // import Cocoa import ProfilePayloads class ProfileEditorWindowToolbarItemAdd: NSView { // MARK: - // MARK: Variables public weak var profile: Profile? let textFieldTitle = NSTextField() let toolbarItem: NSToolbarItem let disclosureTriangle: NSImageView // MARK: - // MARK: Initialization required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(profile: Profile, editor: ProfileEditor) { // --------------------------------------------------------------------- // Setup Variables // --------------------------------------------------------------------- self.profile = profile // --------------------------------------------------------------------- // Create the size of the toolbar item // --------------------------------------------------------------------- let rect = NSRect(x: 0, y: 0, width: 40, height: 32) // --------------------------------------------------------------------- // Create the actual toolbar item // --------------------------------------------------------------------- self.toolbarItem = NSToolbarItem(itemIdentifier: .editorAdd) self.toolbarItem.toolTip = NSLocalizedString("Add payloads or keys", comment: "") self.toolbarItem.minSize = rect.size self.toolbarItem.maxSize = rect.size // --------------------------------------------------------------------- // Create the disclosure triangle overlay // --------------------------------------------------------------------- self.disclosureTriangle = NSImageView() self.disclosureTriangle.translatesAutoresizingMaskIntoConstraints = false self.disclosureTriangle.image = NSImage(named: "ArrowDown") self.disclosureTriangle.imageScaling = .scaleProportionallyUpOrDown self.disclosureTriangle.isHidden = true // --------------------------------------------------------------------- // Initialize self after the class variables have been instantiated // --------------------------------------------------------------------- super.init(frame: rect) // --------------------------------------------------------------------- // Add the button to the toolbar item view // --------------------------------------------------------------------- self.addSubview(ProfileEditorWindowToolbarItemAddButton(frame: rect, editor: editor)) // --------------------------------------------------------------------- // Add disclosure triangle to the toolbar item view // --------------------------------------------------------------------- self.addSubview(self.disclosureTriangle) // --------------------------------------------------------------------- // Setup the disclosure triangle constraints // --------------------------------------------------------------------- addConstraintsForDisclosureTriangle() // --------------------------------------------------------------------- // Set the toolbar item view // --------------------------------------------------------------------- self.toolbarItem.view = self } func disclosureTriangle(show: Bool) { self.disclosureTriangle.isHidden = !show } func addConstraintsForDisclosureTriangle() { var constraints = [NSLayoutConstraint]() // Width constraints.append(NSLayoutConstraint(item: self.disclosureTriangle, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 9)) // Height == Width constraints.append(NSLayoutConstraint(item: self.disclosureTriangle, attribute: .height, relatedBy: .equal, toItem: self.disclosureTriangle, attribute: .width, multiplier: 1, constant: 0)) // Bottom constraints.append(NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: self.disclosureTriangle, attribute: .bottom, multiplier: 1, constant: 6)) // Trailing constraints.append(NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: self.disclosureTriangle, attribute: .trailing, multiplier: 1, constant: 3)) NSLayoutConstraint.activate(constraints) } } class ProfileEditorWindowToolbarItemAddButton: NSButton { // MARK: - // MARK: Variables let buttonMenu = NSMenu() let menuDelay = 0.2 var trackingArea: NSTrackingArea? var mouseIsDown = false var menuWasShownForLastMouseDown = false var mouseDownUniquenessCounter = 0 weak var profileEditor: ProfileEditor? var selectedPayloadPlaceholder: PayloadPlaceholder? // MARK: - // MARK: Initialization required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(frame frameRect: NSRect, editor: ProfileEditor) { self.profileEditor = editor self.selectedPayloadPlaceholder = editor.selectedPayloadPlaceholder super.init(frame: frameRect) // --------------------------------------------------------------------- // Setup Notification Observers // --------------------------------------------------------------------- editor.addObserver(self, forKeyPath: editor.selectedPayloadPlaceholderUpdatedSelector, options: .new, context: nil) // --------------------------------------------------------------------- // Setup Self (Toolbar Item) // --------------------------------------------------------------------- self.bezelStyle = .texturedRounded self.image = NSImage(named: NSImage.addTemplateName) self.target = self self.action = #selector(self.clicked(button:)) self.imageScaling = .scaleProportionallyDown self.imagePosition = .imageOnly // --------------------------------------------------------------------- // Setup the button menu // --------------------------------------------------------------------- setupButtonMenu() } deinit { if let editor = self.profileEditor { editor.removeObserver(self, forKeyPath: editor.selectedPayloadPlaceholderUpdatedSelector, context: nil) } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { guard let editor = self.profileEditor else { return } if keyPath == editor.selectedPayloadPlaceholderUpdatedSelector { self.selectedPayloadPlaceholder = editor.selectedPayloadPlaceholder } else { Log.shared.error(message: "ERROR", category: String(describing: self)) } } func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { if let selectedPayloadPlaceholder = self.selectedPayloadPlaceholder { switch menuItem.identifier { case NSUserInterfaceItemIdentifier.editorMenuItemAddPayload: return !selectedPayloadPlaceholder.payload.unique case NSUserInterfaceItemIdentifier.editorMenuItemAddPayloadKey: return selectedPayloadPlaceholder.payloadType != .manifestsApple default: return true } } return true } func setupButtonMenu() { self.buttonMenu.delegate = self // --------------------------------------------------------------------- // Add item: "Add Payload" // --------------------------------------------------------------------- let menuItemAddPayload = NSMenuItem() menuItemAddPayload.title = NSLocalizedString("Add Payload", comment: "") menuItemAddPayload.identifier = .editorMenuItemAddPayload menuItemAddPayload.isEnabled = true // menuItemAddPayload.target = self //menuItemAddPayload.action = #selector(self.addPayload(menuItem:)) self.buttonMenu.addItem(menuItemAddPayload) // --------------------------------------------------------------------- // Add item: "Add Payload Key" // --------------------------------------------------------------------- let menuItemAddPayloadKey = NSMenuItem() menuItemAddPayloadKey.title = NSLocalizedString("Add Payload Key", comment: "") menuItemAddPayloadKey.identifier = .editorMenuItemAddPayloadKey menuItemAddPayloadKey.isEnabled = true // menuItemAddPayloadKey.target = self //menuItemAddPayloadKey.action = #selector(self.addPayloadKey(menuItem:)) self.buttonMenu.addItem(menuItemAddPayloadKey) } // MARK: - // MARK: Button/Menu Actions @objc func clicked(button: NSButton) { if let selectedPayloadPlaceholder = self.selectedPayloadPlaceholder, !selectedPayloadPlaceholder.payload.unique { self.profileEditor?.addTab(addSettings: true) } } @objc func addPayload(menuItem: NSMenuItem?) { if let selectedPayloadPlaceholder = self.selectedPayloadPlaceholder, !selectedPayloadPlaceholder.payload.unique { self.profileEditor?.addTab(addSettings: true) } } @objc func addPayloadKey(menuItem: NSMenuItem?) { if let selectedPayloadPlaceholder = self.selectedPayloadPlaceholder { self.profileEditor?.addKey(forPayloadPlaceholder: selectedPayloadPlaceholder) } } // MARK: - // MARK: NSControl/NSResponder Methods override func mouseEntered(with event: NSEvent) { if let parent = self.superview, let toolbarItemAdd = parent as? ProfileEditorWindowToolbarItemAdd { toolbarItemAdd.disclosureTriangle(show: true) } } override func mouseExited(with event: NSEvent) { if !self.mouseIsDown { if let parent = self.superview, let toolbarItemAdd = parent as? ProfileEditorWindowToolbarItemAdd { toolbarItemAdd.disclosureTriangle(show: false) } } } override func mouseDown(with event: NSEvent) { // --------------------------------------------------------------------- // Reset mouse variables // --------------------------------------------------------------------- self.mouseIsDown = true self.menuWasShownForLastMouseDown = false self.mouseDownUniquenessCounter += 1 let mouseDownUniquenessCounterCopy = self.mouseDownUniquenessCounter // --------------------------------------------------------------------- // Show the button is being pressed // --------------------------------------------------------------------- self.highlight(true) // --------------------------------------------------------------------- // Wait 'menuDelay' before showing the context menu // If button has been released before time runs out, it's considered a normal button press // --------------------------------------------------------------------- DispatchQueue.main.asyncAfter(deadline: .now() + self.menuDelay) { if self.mouseIsDown && mouseDownUniquenessCounterCopy == self.mouseDownUniquenessCounter { self.menuWasShownForLastMouseDown = true guard let menuOrigin = self.superview?.convert(NSPoint(x: self.frame.origin.x + self.frame.size.width - 16, y: self.frame.origin.y + 2), to: nil) else { return } guard let event = NSEvent.mouseEvent(with: event.type, location: menuOrigin, modifierFlags: event.modifierFlags, timestamp: event.timestamp, windowNumber: event.windowNumber, context: nil, eventNumber: event.eventNumber, clickCount: event.clickCount, pressure: event.pressure) else { return } NSMenu.popUpContextMenu(self.buttonMenu, with: event, for: self) } } } override func mouseUp(with event: NSEvent) { // --------------------------------------------------------------------- // Reset mouse variables // --------------------------------------------------------------------- self.mouseIsDown = false if !self.menuWasShownForLastMouseDown { if let parent = self.superview, let toolbarItemAdd = parent as? MainWindowToolbarItemAdd { toolbarItemAdd.disclosureTriangle(show: false) } self.sendAction(self.action, to: self.target) } // --------------------------------------------------------------------- // Hide the button is being pressed // --------------------------------------------------------------------- self.highlight(false) } // MARK: - // MARK: NSView Methods override func updateTrackingAreas() { // --------------------------------------------------------------------- // Remove previous tracking area if it was set // --------------------------------------------------------------------- if let trackingArea = self.trackingArea { self.removeTrackingArea(trackingArea) } // --------------------------------------------------------------------- // Create a new tracking area // --------------------------------------------------------------------- let trackingOptions = NSTrackingArea.Options(rawValue: (NSTrackingArea.Options.mouseEnteredAndExited.rawValue | NSTrackingArea.Options.activeAlways.rawValue)) self.trackingArea = NSTrackingArea(rect: self.bounds, options: trackingOptions, owner: self, userInfo: nil) // --------------------------------------------------------------------- // Add the new tracking area to the button // --------------------------------------------------------------------- self.addTrackingArea(self.trackingArea!) } } // MARK: - // MARK: NSMenuDelegate extension ProfileEditorWindowToolbarItemAddButton: NSMenuDelegate { func menuDidClose(_ menu: NSMenu) { // --------------------------------------------------------------------- // Reset mouse variables // --------------------------------------------------------------------- self.mouseIsDown = false self.menuWasShownForLastMouseDown = false self.mouseDownUniquenessCounter = 0 // --------------------------------------------------------------------- // Turn of highlighting and disclosure triangle when the menu closes // --------------------------------------------------------------------- self.highlight(false) if let parent = self.superview, let toolbarItemAdd = parent as? ProfileEditorWindowToolbarItemAdd { toolbarItemAdd.disclosureTriangle(show: false) } } }
mit
f8f3ccfe15d84c3c88ebd0969600266e
41.865482
166
0.44976
6.896284
false
false
false
false
bazscsa/sample-apps-ios-with-bitrise-yml
BitriseSampleWithYML/AppDelegate.swift
2
7639
// // AppDelegate.swift // BitriseSampleWithYML // // Created by Viktor Benei on 7/29/15. // Copyright (c) 2015 Bitrise. All rights reserved. // import UIKit import CoreData @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 let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController let controller = masterNavigationController.topViewController as! MasterViewController controller.managedObjectContext = self.managedObjectContext return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool { if let secondaryAsNavController = secondaryViewController as? UINavigationController { if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController { 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 } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.bitrise.BitriseSampleWithYML" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("BitriseSampleWithYML", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("BitriseSampleWithYML.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
3f53a8438908267f03fe27b5c5a00c13
56.871212
290
0.725226
6.091707
false
false
false
false
koroff/Charts
Charts/Classes/Components/ChartLegend.swift
2
17184
// // ChartLegend.swift // Charts // // Created by Daniel Cohen Gindi on 24/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 #if !os(OSX) import UIKit #endif public class ChartLegend: ChartComponentBase { @objc public enum ChartLegendPosition: Int { case RightOfChart case RightOfChartCenter case RightOfChartInside case LeftOfChart case LeftOfChartCenter case LeftOfChartInside case BelowChartLeft case BelowChartRight case BelowChartCenter case AboveChartLeft case AboveChartRight case AboveChartCenter case PiechartCenter } @objc public enum ChartLegendForm: Int { case Square case Circle case Line } @objc public enum ChartLegendDirection: Int { case LeftToRight case RightToLeft } /// the legend colors array, each color is for the form drawn at the same index public var colors = [NSUIColor?]() // the legend text array. a nil label will start a group. public var labels = [String?]() internal var _extraColors = [NSUIColor?]() internal var _extraLabels = [String?]() /// colors that will be appended to the end of the colors array after calculating the legend. public var extraColors: [NSUIColor?] { return _extraColors; } /// labels that will be appended to the end of the labels array after calculating the legend. a nil label will start a group. public var extraLabels: [String?] { return _extraLabels; } /// Are the legend labels/colors a custom value or auto calculated? If false, then it's auto, if true, then custom. /// /// **default**: false (automatic legend) private var _isLegendCustom = false public var position = ChartLegendPosition.BelowChartLeft public var direction = ChartLegendDirection.LeftToRight public var font: NSUIFont = NSUIFont.systemFontOfSize(10.0) public var textColor = NSUIColor.blackColor() public var form = ChartLegendForm.Square public var formSize = CGFloat(8.0) public var formLineWidth = CGFloat(1.5) public var xEntrySpace = CGFloat(6.0) public var yEntrySpace = CGFloat(0.0) public var formToTextSpace = CGFloat(5.0) public var stackSpace = CGFloat(3.0) public var calculatedLabelSizes = [CGSize]() public var calculatedLabelBreakPoints = [Bool]() public var calculatedLineSizes = [CGSize]() public override init() { super.init() self.xOffset = 5.0 self.yOffset = 3.0 } public init(colors: [NSUIColor?], labels: [String?]) { super.init() self.colors = colors self.labels = labels } public init(colors: [NSObject], labels: [NSObject]) { super.init() self.colorsObjc = colors self.labelsObjc = labels } public func getMaximumEntrySize(font: NSUIFont) -> CGSize { var maxW = CGFloat(0.0) var maxH = CGFloat(0.0) var labels = self.labels for i in 0 ..< labels.count { if (labels[i] == nil) { continue } let size = (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: font]) if (size.width > maxW) { maxW = size.width } if (size.height > maxH) { maxH = size.height } } return CGSize( width: maxW + formSize + formToTextSpace, height: maxH ) } public func getLabel(index: Int) -> String? { return labels[index] } public func getFullSize(labelFont: NSUIFont) -> CGSize { var width = CGFloat(0.0) var height = CGFloat(0.0) var labels = self.labels let count = labels.count for i in 0 ..< count { if (labels[i] != nil) { // make a step to the left if (colors[i] != nil) { width += formSize + formToTextSpace } let size = (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: labelFont]) width += size.width height += size.height if (i < count - 1) { width += xEntrySpace height += yEntrySpace } } else { width += formSize + stackSpace if (i < count - 1) { width += stackSpace } } } return CGSize(width: width, height: height) } public var neededWidth = CGFloat(0.0) public var neededHeight = CGFloat(0.0) public var textWidthMax = CGFloat(0.0) public var textHeightMax = CGFloat(0.0) /// flag that indicates if word wrapping is enabled /// this is currently supported only for: `BelowChartLeft`, `BelowChartRight`, `BelowChartCenter`. /// note that word wrapping a legend takes a toll on performance. /// you may want to set maxSizePercent when word wrapping, to set the point where the text wraps. /// /// **default**: false public var wordWrapEnabled = false /// if this is set, then word wrapping the legend is enabled. public var isWordWrapEnabled: Bool { return wordWrapEnabled } /// The maximum relative size out of the whole chart view in percent. /// If the legend is to the right/left of the chart, then this affects the width of the legend. /// If the legend is to the top/bottom of the chart, then this affects the height of the legend. /// If the legend is the center of the piechart, then this defines the size of the rectangular bounds out of the size of the "hole". /// /// **default**: 0.95 (95%) public var maxSizePercent: CGFloat = 0.95 public func calculateDimensions(labelFont labelFont: NSUIFont, viewPortHandler: ChartViewPortHandler) { if (position == .RightOfChart || position == .RightOfChartCenter || position == .LeftOfChart || position == .LeftOfChartCenter || position == .PiechartCenter) { let maxEntrySize = getMaximumEntrySize(labelFont) let fullSize = getFullSize(labelFont) neededWidth = maxEntrySize.width neededHeight = fullSize.height textWidthMax = maxEntrySize.width textHeightMax = maxEntrySize.height } else if (position == .BelowChartLeft || position == .BelowChartRight || position == .BelowChartCenter || position == .AboveChartLeft || position == .AboveChartRight || position == .AboveChartCenter) { var labels = self.labels var colors = self.colors let labelCount = labels.count let labelLineHeight = labelFont.lineHeight let formSize = self.formSize let formToTextSpace = self.formToTextSpace let xEntrySpace = self.xEntrySpace let stackSpace = self.stackSpace let wordWrapEnabled = self.wordWrapEnabled let contentWidth: CGFloat = viewPortHandler.contentWidth // Prepare arrays for calculated layout if (calculatedLabelSizes.count != labelCount) { calculatedLabelSizes = [CGSize](count: labelCount, repeatedValue: CGSize()) } if (calculatedLabelBreakPoints.count != labelCount) { calculatedLabelBreakPoints = [Bool](count: labelCount, repeatedValue: false) } calculatedLineSizes.removeAll(keepCapacity: true) // Start calculating layout let labelAttrs = [NSFontAttributeName: labelFont] var maxLineWidth: CGFloat = 0.0 var currentLineWidth: CGFloat = 0.0 var requiredWidth: CGFloat = 0.0 var stackedStartIndex: Int = -1 for i in 0 ..< labelCount { let drawingForm = colors[i] != nil calculatedLabelBreakPoints[i] = false if (stackedStartIndex == -1) { // we are not stacking, so required width is for this label only requiredWidth = 0.0 } else { // add the spacing appropriate for stacked labels/forms requiredWidth += stackSpace } // grouped forms have null labels if (labels[i] != nil) { calculatedLabelSizes[i] = (labels[i] as NSString!).sizeWithAttributes(labelAttrs) requiredWidth += drawingForm ? formToTextSpace + formSize : 0.0 requiredWidth += calculatedLabelSizes[i].width } else { calculatedLabelSizes[i] = CGSize() requiredWidth += drawingForm ? formSize : 0.0 if (stackedStartIndex == -1) { // mark this index as we might want to break here later stackedStartIndex = i } } if (labels[i] != nil || i == labelCount - 1) { let requiredSpacing = currentLineWidth == 0.0 ? 0.0 : xEntrySpace if (!wordWrapEnabled || // No word wrapping, it must fit. currentLineWidth == 0.0 || // The line is empty, it must fit. (contentWidth - currentLineWidth >= requiredSpacing + requiredWidth)) // It simply fits { // Expand current line currentLineWidth += requiredSpacing + requiredWidth } else { // It doesn't fit, we need to wrap a line // Add current line size to array calculatedLineSizes.append(CGSize(width: currentLineWidth, height: labelLineHeight)) maxLineWidth = max(maxLineWidth, currentLineWidth) // Start a new line calculatedLabelBreakPoints[stackedStartIndex > -1 ? stackedStartIndex : i] = true currentLineWidth = requiredWidth } if (i == labelCount - 1) { // Add last line size to array calculatedLineSizes.append(CGSize(width: currentLineWidth, height: labelLineHeight)) maxLineWidth = max(maxLineWidth, currentLineWidth) } } stackedStartIndex = labels[i] != nil ? -1 : stackedStartIndex } let maxEntrySize = getMaximumEntrySize(labelFont) textWidthMax = maxEntrySize.width textHeightMax = maxEntrySize.height neededWidth = maxLineWidth neededHeight = labelLineHeight * CGFloat(calculatedLineSizes.count) + yEntrySpace * CGFloat(calculatedLineSizes.count == 0 ? 0 : (calculatedLineSizes.count - 1)) } else { let maxEntrySize = getMaximumEntrySize(labelFont) let fullSize = getFullSize(labelFont) /* RightOfChartInside, LeftOfChartInside */ neededWidth = fullSize.width neededHeight = maxEntrySize.height textWidthMax = maxEntrySize.width textHeightMax = maxEntrySize.height } } /// MARK: - Custom legend /// colors and labels that will be appended to the end of the auto calculated colors and labels after calculating the legend. /// (if the legend has already been calculated, you will need to call notifyDataSetChanged() to let the changes take effect) public func setExtra(colors colors: [NSUIColor?], labels: [String?]) { self._extraLabels = labels self._extraColors = colors } /// Sets a custom legend's labels and colors arrays. /// The colors count should match the labels count. /// * Each color is for the form drawn at the same index. /// * A nil label will start a group. /// * A nil color will avoid drawing a form, and a clearColor will leave a space for the form. /// This will disable the feature that automatically calculates the legend labels and colors from the datasets. /// Call `resetCustom(...)` to re-enable automatic calculation (and then `notifyDataSetChanged()` is needed). public func setCustom(colors colors: [NSUIColor?], labels: [String?]) { self.labels = labels self.colors = colors _isLegendCustom = true } /// Calling this will disable the custom legend labels (set by `setLegend(...)`). Instead, the labels will again be calculated automatically (after `notifyDataSetChanged()` is called). public func resetCustom() { _isLegendCustom = false } /// **default**: false (automatic legend) /// - returns: true if a custom legend labels and colors has been set public var isLegendCustom: Bool { return _isLegendCustom } /// MARK: - ObjC compatibility /// colors that will be appended to the end of the colors array after calculating the legend. public var extraColorsObjc: [NSObject] { return ChartUtils.bridgedObjCGetNSUIColorArray(swift: _extraColors); } /// labels that will be appended to the end of the labels array after calculating the legend. a nil label will start a group. public var extraLabelsObjc: [NSObject] { return ChartUtils.bridgedObjCGetStringArray(swift: _extraLabels); } /// the legend colors array, each color is for the form drawn at the same index /// (ObjC bridging functions, as Swift 1.2 does not bridge optionals in array to `NSNull`s) public var colorsObjc: [NSObject] { get { return ChartUtils.bridgedObjCGetNSUIColorArray(swift: colors); } set { self.colors = ChartUtils.bridgedObjCGetNSUIColorArray(objc: newValue); } } // the legend text array. a nil label will start a group. /// (ObjC bridging functions, as Swift 1.2 does not bridge optionals in array to `NSNull`s) public var labelsObjc: [NSObject] { get { return ChartUtils.bridgedObjCGetStringArray(swift: labels); } set { self.labels = ChartUtils.bridgedObjCGetStringArray(objc: newValue); } } /// colors and labels that will be appended to the end of the auto calculated colors and labels after calculating the legend. /// (if the legend has already been calculated, you will need to call `notifyDataSetChanged()` to let the changes take effect) public func setExtra(colors colors: [NSObject], labels: [NSObject]) { if (colors.count != labels.count) { fatalError("ChartLegend:setExtra() - colors array and labels array need to be of same size") } self._extraLabels = ChartUtils.bridgedObjCGetStringArray(objc: labels) self._extraColors = ChartUtils.bridgedObjCGetNSUIColorArray(objc: colors) } /// Sets a custom legend's labels and colors arrays. /// The colors count should match the labels count. /// * Each color is for the form drawn at the same index. /// * A nil label will start a group. /// * A nil color will avoid drawing a form, and a clearColor will leave a space for the form. /// This will disable the feature that automatically calculates the legend labels and colors from the datasets. /// Call `resetLegendToAuto(...)` to re-enable automatic calculation, and then if needed - call `notifyDataSetChanged()` on the chart to make it refresh the data. public func setCustom(colors colors: [NSObject], labels: [NSObject]) { if (colors.count != labels.count) { fatalError("ChartLegend:setCustom() - colors array and labels array need to be of same size") } self.labelsObjc = labels self.colorsObjc = colors _isLegendCustom = true } }
apache-2.0
a9d5d541328d78f5e12a9be6bf9c56f6
36.194805
188
0.572044
5.458704
false
false
false
false
BoutFitness/Concept2-SDK
Pod/Classes/Models/RowingStatusSampleRate.swift
1
1073
// // RowingStatusSampleRate.swift // Pods // // Created by Jesse Curry on 10/27/15. // // struct RowingStatusSampleRate: CharacteristicModel, CustomDebugStringConvertible { let DataLength = 1 /* */ var sampleRate:RowingStatusSampleRateType? init(fromData data: Data) { var arr = [UInt8](repeating: 0, count: DataLength) (data as NSData).getBytes(&arr, length: DataLength) sampleRate = RowingStatusSampleRateType(rawValue: arr[0]) } // MARK: PerformanceMonitor func updatePerformanceMonitor(performanceMonitor:PerformanceMonitor) { performanceMonitor.sampleRate.value = sampleRate } // MARK: - var debugDescription:String { return "[RowingStatusSampleRate]\n\tsampleRate: \(String(describing: sampleRate))" } } /* NSData extension to allow writing of this value */ extension NSData { convenience init(rowingStatusSampleRate:RowingStatusSampleRateType) { let arr:[UInt8] = [rowingStatusSampleRate.rawValue]; self.init(bytes: arr, length: arr.count * MemoryLayout<UInt8>.size) } }
mit
08a392966aee272e6bd6d58298efd622
22.844444
88
0.71109
4.207843
false
false
false
false
benlangmuir/swift
validation-test/compiler_crashers_fixed/00119-swift-dependentmembertype-get.swift
65
1489
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func sr<ml>() -> (ml, ml -> ml) -> ml { a sr a.sr = { } { ml) { ih } } protocol sr { } class a: sr{ class func sr {} class w { } class n { func ji((x, n))(w: (x, f)) { } } func n<x: b, ed y nm<ed> == x.x.n>(rq : x) -> ed? { fe (w : ed?) k rq { r n a = w { } } } func kj(q: ih) -> <ed>(() -> ed) -> ih { } func w(a: x, x: x) -> (((x, x) -> x) -> x) { qp { } } func ji(r: (((x, x) -> x) -> x)) -> x { qp r({ }) } func w<ed>() { t ji { } } protocol g ed : m>(ji: ed) { } protocol w { } class ji<ih : n, sr : n y ih.ml == sr> : w po n<a { t n { } } t x<ed> { } protocol g { } class nm { func a() -> ih { } } class i: nm, g { qp func a() -> ih { } func n() -> ih { } } func x<ed y ed: g, ed: nm>(rq: ed) { } struct n<a : b> { } func w<a>() -> [n<a>] { } protocol g { } struct nm : g { } struct i<ed, ml: g y ed.i == ml> { } protocol w { } protocol ji : w { } protocol n : w { } protocol a { } struct x : a { } func sr<sr : ji, ts : a y ts.sr == sr> (sr: ts) { } func ji { } struct n<ih : ji
apache-2.0
68145c2f958cc46c3ca9ac6cd0aebbaa
15.010753
79
0.491605
2.477537
false
false
false
false
google/iosched-ios
Source/IOsched/Screens/Explore/ExploreOfflineView.swift
1
6619
// // Copyright (c) 2019 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit public class ExploreOfflineView: UIView { private enum Constants { static let title = NSLocalizedString("Could not load Explore mode", comment: "Title for the AR Explore screen if the user's phone failed to load") static let subtext = NSLocalizedString("Your device appears to be offline. To use Explore mode, try connecting to the conference WiFi:\n\nSSID: io2019\nPassword: makegoodthings", comment: "Subtext offering suggestions on how to connect to WiFi if the user's device is offline") } private let titleLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textColor = UIColor(red: 32 / 255, green: 33 / 255, blue: 36 / 255, alpha: 1) label.font = UIFont.preferredFont(forTextStyle: .headline) label.textAlignment = .center label.numberOfLines = 0 label.enableAdjustFontForContentSizeCategory() label.text = Constants.title return label }() private let subtextLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textColor = UIColor(red: 65 / 255, green: 69 / 255, blue: 73 / 255, alpha: 1) label.font = UIFont.preferredFont(forTextStyle: .subheadline) label.textAlignment = .center label.numberOfLines = 0 label.enableAdjustFontForContentSizeCategory() label.text = Constants.subtext return label }() private let imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.image = UIImage(named: "ar_offline") imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() public override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white addSubview(titleLabel) addSubview(subtextLabel) addSubview(imageView) setupConstraints() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override var isAccessibilityElement: Bool { get { return true } set {} } public override var accessibilityLabel: String? { set {} get { return Constants.title + "\n" + Constants.subtext } } private func setupConstraints() { let constraints = [ NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 18), NSLayoutConstraint(item: titleLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0), NSLayoutConstraint(item: titleLabel, attribute: .leading, relatedBy: .greaterThanOrEqual, toItem: self, attribute: .leading, multiplier: 1, constant: 16), NSLayoutConstraint(item: titleLabel, attribute: .trailing, relatedBy: .lessThanOrEqual, toItem: self, attribute: .trailing, multiplier: 1, constant: -16), NSLayoutConstraint(item: subtextLabel, attribute: .top, relatedBy: .equal, toItem: titleLabel, attribute: .bottom, multiplier: 1, constant: 12), NSLayoutConstraint(item: subtextLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0), NSLayoutConstraint(item: subtextLabel, attribute: .leading, relatedBy: .greaterThanOrEqual, toItem: titleLabel, attribute: .leading, multiplier: 1, constant: 16), NSLayoutConstraint(item: subtextLabel, attribute: .trailing, relatedBy: .lessThanOrEqual, toItem: titleLabel, attribute: .trailing, multiplier: 1, constant: -16), NSLayoutConstraint(item: imageView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: -28), NSLayoutConstraint(item: imageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0), NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 162), NSLayoutConstraint(item: imageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 175) ] addConstraints(constraints) } }
apache-2.0
b74ccfd6c026f272d01b2e1ba979532f
35.977654
281
0.527874
5.801052
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift
1
3181
import XCTest import GRDB private class Reader : Record { var id: Int64? let name: String let age: Int? init(id: Int64?, name: String, age: Int?) { self.id = id self.name = name self.age = age super.init() } required init(row: Row) throws { self.id = row["id"] self.name = row["name"] self.age = row["age"] try super.init(row: row) } override class var databaseTableName: String { "readers" } override func encode(to container: inout PersistenceContainer) throws { container["id"] = id container["name"] = name container["age"] = age } override func didInsert(_ inserted: InsertionSuccess) { super.didInsert(inserted) id = inserted.rowID } } class RecordQueryInterfaceRequestTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createReaders") { db in try db.execute(sql: """ CREATE TABLE readers ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INT) """) } try migrator.migrate(dbWriter) } // MARK: - Fetch Record func testFetch() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let arthur = Reader(id: nil, name: "Arthur", age: 42) try arthur.insert(db) let barbara = Reader(id: nil, name: "Barbara", age: 36) try barbara.insert(db) let request = Reader.all() do { let readers = try request.fetchAll(db) XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(readers.count, 2) XCTAssertEqual(readers[0].id!, arthur.id!) XCTAssertEqual(readers[0].name, arthur.name) XCTAssertEqual(readers[0].age, arthur.age) XCTAssertEqual(readers[1].id!, barbara.id!) XCTAssertEqual(readers[1].name, barbara.name) XCTAssertEqual(readers[1].age, barbara.age) } do { let reader = try request.fetchOne(db)! XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\" LIMIT 1") XCTAssertEqual(reader.id!, arthur.id!) XCTAssertEqual(reader.name, arthur.name) XCTAssertEqual(reader.age, arthur.age) } do { let cursor = try request.fetchCursor(db) let names = cursor.map(\.name) XCTAssertEqual(try names.next()!, arthur.name) XCTAssertEqual(try names.next()!, barbara.name) XCTAssertTrue(try names.next() == nil) // validate query *after* cursor has retrieved a record XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") } } } }
mit
a60832da3767a4f7db0d4afa49f77555
30.81
81
0.52342
4.863914
false
false
false
false
RikkiGibson/Corvallis-Bus-iOS
TodayExtensionMac/ListRowViewController.swift
1
2375
// // ListRowViewController.swift // TodayExtensionMac // // Created by Rikki Gibson on 6/12/16. // Copyright © 2016 Rikki Gibson. All rights reserved. // import Cocoa class ListRowViewController: NSViewController { var hasDarkAppearance = false var stopID: Int? @IBOutlet weak var labelStopName: NSTextField! @IBOutlet weak var labelFirstRouteName: NSTextField! @IBOutlet weak var labelFirstRouteArrivals: NSTextField! @IBOutlet weak var labelSecondRouteName: NSTextField! @IBOutlet weak var labelSecondRouteArrivals: NSTextField! @IBOutlet weak var imageNearestStop: NSImageView! @IBOutlet weak var labelDistanceFromUser: NSTextField! override var nibName: NSNib.Name? { return NSNib.Name(rawValue: "ListRowViewController") } override func loadView() { super.loadView() view.setFrameSize(NSSize(width: 0, height: 80)) preferredContentSize = view.frame.size labelFirstRouteName.wantsLayer = true labelFirstRouteName.layer!.cornerRadius = 5 labelSecondRouteName.wantsLayer = true labelSecondRouteName.layer!.cornerRadius = 5 if hasDarkAppearance { imageNearestStop.image = NSImage(named: NSImage.Name(rawValue: "ListCurrentLocWhite")) } } override func viewWillAppear() { guard let box = representedObject as? Box<FavoriteStopViewModel> else { return } let model = box.value stopID = model.stopId labelStopName.stringValue = model.stopName labelFirstRouteName.stringValue = model.firstRouteName labelFirstRouteName.backgroundColor = model.firstRouteColor labelFirstRouteArrivals.stringValue = model.firstRouteArrivals labelSecondRouteName.stringValue = model.secondRouteName labelSecondRouteName.backgroundColor = model.secondRouteColor labelSecondRouteArrivals.stringValue = model.secondRouteArrivals imageNearestStop.isHidden = !model.isNearestStop labelDistanceFromUser.stringValue = model.distanceFromUser } override func mouseUp(with theEvent: NSEvent) { if let stopID = stopID, let url = URL(string: "CorvallisBus://?\(stopID)") { NSWorkspace.shared.open(url) } } }
mit
a190427ad16885355e0423972c10294a
32.43662
98
0.681129
4.77666
false
false
false
false
alejandrogarin/ADGCloudKit
Example/ADGCloudKit/UIViewControllerExt.swift
1
7207
// // CloudContext.swift // ADGCloudKit // // Created by Alejandro Diego Garin // The MIT License (MIT) // // Copyright (c) 2015 Alejandro Garin @alejandrogarin // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit extension UIViewController { func adg_randomStringWithLength(len: Int) -> String { let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let randomString : NSMutableString = NSMutableString(capacity: len) for (var i=0; i < len; i++) { let length = UInt32(letters.length) let rand = arc4random_uniform(length) randomString.appendFormat("%C", letters.characterAtIndex(Int(rand))) } return randomString as String } /*! * @brief var aRandomInt = adg_random(-500...100) */ func adg_random(range: Range<Int> ) -> Int { var offset = 0 if range.startIndex < 0 // allow negative ranges { offset = abs(range.startIndex) } let mini = UInt32(range.startIndex + offset) let maxi = UInt32(range.endIndex + offset) return Int(mini + arc4random_uniform(maxi - mini)) - offset } func adg_showError(error: NSError) { let errorDesc = error.localizedDescription; let alertController: UIAlertController = UIAlertController(title: "Error", message: errorDesc, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } func adg_showError(message message: String) { let alertController: UIAlertController = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } class func adg_window() -> UIWindow { let arrayOfWindows = UIApplication.sharedApplication().windows; for aWindow in arrayOfWindows { if (aWindow.windowLevel == UIWindowLevelNormal) { return aWindow; } } return UIApplication.sharedApplication().keyWindow! } class func adg_topMostController() -> UIViewController? { var topWindow = UIApplication.sharedApplication().keyWindow! if (topWindow.windowLevel != UIWindowLevelNormal) { topWindow = self.adg_window() } var topController = topWindow.rootViewController; if (topController == nil) { if let topWindowFromDelegate = UIApplication.sharedApplication().delegate?.window { if let actualWindowFromDelegate = topWindowFromDelegate { topWindow = actualWindowFromDelegate } } topController = topWindow.rootViewController } if let actualTopController = topController { while ((actualTopController.presentedViewController) != nil) { topController = actualTopController.presentedViewController } } if let actualTopController = topController { if let navigation = actualTopController as? UINavigationController, actualTopController = navigation.viewControllers.last { while ((actualTopController.presentedViewController) != nil) { topController = actualTopController.presentedViewController } } } return topController } class func adg_constraintAddTopLeftBottomRight(fromView view:UIView, toSuperview superview: UIView) { let top = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0) let left = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0) let right = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 0) let bottom = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0) superview.addConstraints([top, left, right, bottom]) } class func adg_constraintCenterXY(fromView view: UIView, toSuperView superview: UIView) { let centerX = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0) let centerY = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0) superview.addConstraints([centerX, centerY]) } class func adg_showLoadingIndicatorView(loadingView: UIView) { if let controller = UIViewController.adg_topMostController(), view = controller.view { view.addSubview(loadingView) UIViewController.adg_constraintAddTopLeftBottomRight(fromView: loadingView, toSuperview: view) let indicator = UIActivityIndicatorView(); indicator.startAnimating() indicator.translatesAutoresizingMaskIntoConstraints = false loadingView.addSubview(indicator) UIViewController.adg_constraintCenterXY(fromView: indicator, toSuperView: loadingView) } } class func adg_removeLoadingIndicatorView(loadingView: UIView) { loadingView.removeFromSuperview() } }
mit
17e2e0a836484613b753bc26cd5782f7
47.702703
212
0.689885
5.218682
false
false
false
false
karivalkama/Agricola-Scripture-Editor
TranslationEditor/TextWithNotes.swift
1
9712
// // TextWithFootnotes.swift // TranslationEditor // // Created by Mikko Hilpinen on 25.4.2017. // Copyright © 2017 SIL. All rights reserved. // import Foundation // This element contains both text element, cross reference and footnote data // The elements are ordered in a very specific way final class TextWithNotes: USXConvertible, JSONConvertible, AttributedStringConvertible, Copyable { // ATTRIBUTES ------------ var crossReferences: [CrossReference] private(set) var textElements: [TextElement] private(set) var footNotes: [FootNote] // COMPUTED PROPERTIES ---- var content: [ParaContent] { var content = [ParaContent]() var nextTextIndex = 0 for footNote in footNotes { // A text element is added before each foot note if textElements.count > nextTextIndex { content.add(textElements[nextTextIndex]) nextTextIndex += 1 } content.add(footNote) } // Adds the remaining text element(s) for i in nextTextIndex ..< textElements.count { content.add(textElements[i]) } return content } var toUSX: String { return crossReferences.reduce("", { $0 + $1.toUSX }) + content.reduce("", { $0 + $1.toUSX }) } var properties: [String : PropertyValue] { return ["text": textElements.value, "notes": footNotes.value, "cross_references": crossReferences.value] } var text: String { return content.reduce("", { $0 + $1.text }) } // Whether all of this element contains text (doesn't require notes to contain any text) var isFilled: Bool { return textElements.contains(where: { !$0.isEmpty } ) } // Whether the element is completely empty of any text and doesn't contain a single note element var isEmpty: Bool { return textElements.forAll { $0.isEmpty } && footNotes.isEmpty && crossReferences.isEmpty } // Whether this element contains any notes (empty or not) var containsNotes: Bool { return !crossReferences.isEmpty || !footNotes.isEmpty } // INIT -------------------- init() { self.textElements = [TextElement.empty()] self.footNotes = [] self.crossReferences = [] } init(text: String) { self.textElements = [TextElement(charData: [CharData(text: text)])] self.footNotes = [] self.crossReferences = [] } init(textElements: [TextElement], footNotes: [FootNote], crossReferences: [CrossReference] = []) { self.textElements = textElements self.footNotes = footNotes self.crossReferences = crossReferences } static func parse(from properties: PropertySet) -> TextWithNotes { return TextWithNotes(textElements: TextElement.parseArray(from: properties["text"].array(), using: TextElement.parse), footNotes: FootNote.parseArray(from: properties["notes"].array(), using: FootNote.parse), crossReferences: CrossReference.parseArray(from: properties["cross_references"].array(), using: CrossReference.parse)) } // IMPLEMENTED METHODS --- func toAttributedString(options: [String : Any]) -> NSAttributedString { let attStr = NSMutableAttributedString() content.forEach { attStr.append($0.toAttributedString(options: options)) } return attStr } func copy() -> TextWithNotes { return TextWithNotes(textElements: textElements.map { $0.copy() }, footNotes: footNotes.map { $0.copy() }, crossReferences: crossReferences) } // OPERATORS ----------- static func +(_ left: TextWithNotes, _ right: TextWithNotes) -> TextWithNotes { // The last text element of the left hand side is combined with the first text element on the right hand side so that there won't be two consecutive text elements var newTextElements = [TextElement]() if left.textElements.isEmpty { newTextElements = right.textElements.copy() } else if right.textElements.isEmpty { newTextElements = left.textElements.copy() } else { newTextElements.append(contentsOf: left.textElements.dropLast().map { $0.copy() }) newTextElements.add(left.textElements.last! + right.textElements.first!) newTextElements.append(contentsOf: right.textElements.dropFirst().map { $0.copy() }) } return TextWithNotes(textElements: newTextElements, footNotes: left.footNotes.copy() + right.footNotes.copy(), crossReferences: left.crossReferences + right.crossReferences) } // OTHER METHODS ------- func emptyCopy() -> TextWithNotes { return TextWithNotes(textElements: textElements.map { $0.emptyCopy() }, footNotes: footNotes.map { $0.emptyCopy() }, crossReferences: crossReferences) } func contentEquals(with other: TextWithNotes) -> Bool { /* print("STATUS: Comparing two texts: '\(text)' and '\(other.text)'") print("STATUS: Text elements are equal: \(textElements.contentEquals(with: other.textElements))") print("STATUS: Footnotes are equal: \(footNotes.contentEquals(with: other.footNotes))") print("STATUS: Cross references are equal: \(crossReferences == other.crossReferences)") */ return textElements.contentEquals(with: other.textElements) && footNotes.contentEquals(with: other.footNotes) && crossReferences == other.crossReferences } func clearText() { textElements.forEach { $0.charData = [] } footNotes.forEach { $0.charData = [] } } func update(with attString: NSAttributedString, cutOutCrossReferencesOutside rangeLimit: VerseRange? = nil) -> TextWithNotes? { // Finds all the notes markers from the string first var notesRanges = [(startMarker: NSRange, endMarker: NSRange)]() // Note start range, note end range var openStartMarker: NSRange? attString.enumerateAttribute(NoteMarkerAttributeName, in: NSMakeRange(0, attString.length), options: []) { isNoteStart, range, _ in if let isNoteStart = isNoteStart as? Bool { // The previous note must be ended before a new one can begin if isNoteStart { if openStartMarker == nil { openStartMarker = range } } else if let startMarker = openStartMarker { notesRanges.add((startMarker: startMarker, endMarker: range)) openStartMarker = nil } } } let breakMarkers = notesRanges.flatMap { [$0.startMarker, $0.endMarker] } // Parses the character data var charData = [[CharData]]() var textStartIndex = 0 for breakMarker in breakMarkers { charData.add(parseCharData(from: attString, range: NSMakeRange(textStartIndex, breakMarker.location - textStartIndex))) textStartIndex = breakMarker.location + breakMarker.length } charData.add(parseCharData(from: attString, range: NSMakeRange(textStartIndex, attString.length - textStartIndex))) // Updates the content with the new data var content = self.content for i in 0 ..< self.content.count { if i < charData.count { content[i].charData = CharData.update(self.content[i].charData, with: charData[i]) } else { break } } // Finds out which cross references to keep and which to cut var cutCrossReferences: [CrossReference]? if let rangeLimit = rangeLimit { cutCrossReferences = crossReferences.filter { $0.originVerseIndex != nil && !rangeLimit.contains(index: $0.originVerseIndex!) } crossReferences = crossReferences - cutCrossReferences! } // If there was less data provided than what there were slots in this element, // cuts the remaining elements and returns a new element based on that data if charData.count < content.count { // TODO: Distribute cross reference instances between the two parts // If the last included element was a footnote, adds an empty text data element to the end of this element if charData.count % 2 == 0 { let splitIndex = charData.count / 2 let cutElement = TextWithNotes(textElements: Array(textElements.dropFirst(splitIndex)), footNotes: Array(footNotes.dropFirst(splitIndex)), crossReferences: cutCrossReferences ?? []) textElements = Array(textElements.prefix(splitIndex)) + TextElement.empty() footNotes = Array(footNotes.prefix(splitIndex)) return cutElement } // If the last included element was text data, adds an empty text data element to the beginning of the generated element else { let noteSplitIndex = charData.count / 2 let textSplitIndex = noteSplitIndex + 1 let cutElement = TextWithNotes(textElements: TextElement.empty() + Array(textElements.dropFirst(textSplitIndex)), footNotes: Array(footNotes.dropFirst(noteSplitIndex)), crossReferences: cutCrossReferences ?? []) textElements = Array(textElements.prefix(textSplitIndex)) footNotes = Array(footNotes.prefix(noteSplitIndex)) return cutElement } } // TODO: Handle cases where new chardata count is smaller than previous content count if let cutCrossReferences = cutCrossReferences { return TextWithNotes(textElements: [TextElement.empty()], footNotes: [], crossReferences: cutCrossReferences) } else { return nil } } private func parseCharData(from attStr: NSAttributedString, range: NSRange) -> [CharData] { // Function for parsing character data from the provided usxString // The array will contain the parsed data. Should be emptied after each iteration. var parsedData = [CharData]() attStr.enumerateAttribute(CharStyleAttributeName, in: range, options: []) { style, range, _ in let text = (attStr.string as NSString).substring(with: range) let style = style as? CharStyle // If the consecutive chardata elements would have the same styling, they are appended to each other if let lastData = parsedData.last, lastData.style == style { parsedData[parsedData.count - 1] = CharData(text: lastData.text.appending(text), style: style) } else { parsedData.append(CharData(text: text, style: style)) } } return parsedData } }
mit
79b6111836508a7dfd8d561d6aeceae1
32.143345
329
0.710946
3.690992
false
false
false
false
tectijuana/patrones
Bloque1SwiftArchivado/PracticasSwift/LardizabalJuan/practica4.swift
1
605
/* .__ _____ __ ________ _ _|__|/ ____\/ |_ / ___/\ \/ \/ / \ __\\ __\ \___ \ \ /| || | | | /____ > \/\_/ |__||__| |__| \/ Programa 4 Descripcion : Resolver el siguiente sistema de ecuaciones: x+6y+1=0 2x-y+5=0 -24+13y-6=0 sea x= 2,4,6,8, ...,50 Nombre: Lardizabal Ramirez Juan Carlos */ var x = 0 for c in 0 ... 25 { x = x + 2 var ecuacion1 = (-1 - x) / 6 var ecuacion2 = 5 - (2 * x) print ("Ecuacion1 y=",ecuacion1) print ("Ecuacion2 y=",ecuacion2) } var ecuacion3 = (6 + 43)/13 print("Ecuacion3 y=",ecuacion3)
gpl-3.0
cfbf7d3949d70b1a55b2b2cb0ca1c14e
19.896552
58
0.419835
2.283019
false
false
false
false
Skyus/Oak
OakSim/main.swift
1
8778
import Foundation import Oak import Guaka extension Array { public func print() { for element in self { Swift.print(element) } } } class ExecutionTimer { var printIPS = false var elapsed: Double? var adjust: Double = 0.0 var wait: Double = 0.0 var counter: Int = 0 func reset() { adjust = Date().timeIntervalSince1970 counter = 0 wait = 0 elapsed = nil } func pause() { wait = Date().timeIntervalSince1970 } func resume() { elapsed = nil adjust += (Date().timeIntervalSince1970 - wait) wait = 0 } func stop() { elapsed = Date().timeIntervalSince1970 - adjust } func print() { let time = elapsed ?? (Date().timeIntervalSince1970 - adjust) Swift.print("") NSLog("Time taken: %.02f seconds.", time) if printIPS { NSLog("IPS: %.02f.", Double(counter) / time) } Swift.print("") } init(printIPS: Bool = false) { self.printIPS = printIPS } } var timer = ExecutionTimer(printIPS: true) var interactive = false signal(SIGINT) { (s: Int32) in if (!interactive) { if 1...6 ~= s { print("") timer.stop() timer.print() exit(9) } } } let command = Command( usage: "oak", flags: [ Flag(shortName: "o", longName: "output", type: String.self, description: "Assemble only, specify file path for binary dump."), Flag(shortName: "v", longName: "version", value: false, description: "Prints the current version."), Flag(shortName: "a", longName: "arch", value: "rv32i", description: "Picks the instruction set architecture."), Flag(shortName: "s", longName: "simulate", value: false, description: "Simulate only. The arguments will be treated as binary files."), Flag(shortName: "d", longName: "disassemble", value: false, description: "Disassemble while simulating."), Flag(shortName: "i", longName: "interactive", value: false, description: "Interactive debugging mode.") ] ) { (flags, arguments) in if flags.getBool(name: "version") ?? false { print("Oak · Alpha 0.4") print("All rights reserved.") print("You should have obtained a copy of the Mozilla Public License with your app.") print("If you did not, a verbatim copy should be available at https://www.mozilla.org/en-US/MPL/2.0/.") return } var disassemble = flags.getBool(name: "disassemble") ?? false var isaChoice: String = "rv32i" if let arch = flags.getString(name: "arch"), !arch.isEmpty { isaChoice = arch } var assembleOnly = false var outputPath: String? if let output = flags.getString(name: "output"), !output.isEmpty { assembleOnly = true outputPath = output } var simulateOnly = flags.getBool(name: "simulate") ?? false if assembleOnly && simulateOnly { print("Error: --simulate and --output are mutually exclusive.") exit(64) } interactive = flags.getBool(name: "interactive") ?? false var coreChoice: Core? switch(isaChoice.lowercased()) { case "riscv": fallthrough case "rv32i": coreChoice = RV32iCore() case "armv7": print("\("Oak Error"): ARMv7 not yet implemented.") exit(64) case "mips": print("\("Oak Warning"): MIPS is unfinished. Only R-Types are supported.") coreChoice = MIPSCore() default: print("Unknown instruction set \(isaChoice).") return } var core = coreChoice! var machineCode: [UInt8] if arguments.count != 1 { print("Error: Oak needs at least/at most one file.") exit(64) } guard let defile = Defile(arguments[0], mode: .read) else { print("Error: Opening file \(arguments[0]) failed.") exit(66) } if simulateOnly { machineCode = try! defile.dumpBytes() } else { let assembler = Assembler(for: core.instructionSet) let file = try! defile.dumpString() let lexed = assembler.lex(file) if lexed.errorMessages.count != 0 { lexed.errorMessages.print() exit(0xBAD) } let assembled = assembler.assemble(lexed.lines, labels: lexed.labels) if assembled.errorMessages.count != 0 { assembled.errorMessages.print() exit(0xBAD) } machineCode = assembled.machineCode } if assembleOnly { let binPath = outputPath ?? arguments[0].replacing([".S", ".s", ".asm"], with: ".bin") guard let defile = Defile(binPath, mode: .write) else { print("Error: Opening file \(binPath) for writing failed.") exit(73) } do { try defile.write(bytes:machineCode) } catch { print("\(error)") exit(73) } } else { do { try core.loadProgram(machineCode: machineCode) } catch { print("Error while loading program: \(error).") exit(65) } timer.reset() while true { while core.state == .running { do { try core.fetch() let disassembly = try core.decode() if (interactive) { var resume = false while (!resume) { print("Program Counter: 0x\(String(core.pc, radix: 16)) | \(disassembly) > ", terminator: "") let input = readLine() if (input == "r") { print(core.registerDump()) } else if (input == "c") { resume = true } else if (input == nil) { print("") exit(9) } } } else if (disassemble) { print(disassembly) } timer.counter += 1 if timer.counter == (1 << 14) { print("\("Oak Warning"): This program has taken over \(1 << 14) instructions and may be an infinite loop. You may want to interrupt the program.") } try core.execute() } catch { print("Error: \(error).") timer.stop() timer.print() exit(0xBAD) } } if core.state == .environmentCall { timer.pause() let service = core.service switch (service[0]) { case 1: print(">", service[1]) case 4: var cString = [UInt8]() var offset: UInt = 0 var byte = try! core.memory.copy(service[1] + offset, count: 1)[0] while byte != 0 { cString.append(byte) offset += 1 byte = try! core.memory.copy(service[1] + offset, count: 1)[0] } cString.append(0) if let string = String(bytes: cString, encoding: String.Encoding.utf8) { print(">", string) } case 10: print("Execution complete.") timer.stop() timer.print() return default: print("\("Warning"): Ignored unknown environment call service number \(core.service[0]).") } core.state = .running timer.resume() } } } } command.execute()
mpl-2.0
a4a10b55e4cd4a5442866c5e506badf8
26.690852
170
0.452319
4.835813
false
false
false
false
atl009/WordPress-iOS
WordPress/Classes/ViewRelated/NUX/LoginSocialErrorCell.swift
1
2607
class LoginSocialErrorCell: UITableViewCell { private let errorTitle: String private let errorDescription: String private let titleLabel: UILabel private let descriptionLabel: UILabel private let labelStack: UIStackView private struct Constants { static let labelSpacing: CGFloat = 15.0 static let labelVerticalMargin: CGFloat = 20.0 static let descriptionMinHeight: CGFloat = 14.0 } init(title: String, description: String) { errorTitle = title errorDescription = description titleLabel = UILabel() descriptionLabel = UILabel() labelStack = UIStackView() super.init(style: .default, reuseIdentifier: "LoginSocialErrorCell") layoutLabels() } required init?(coder aDecoder: NSCoder) { errorTitle = aDecoder.value(forKey: "errorTitle") as? String ?? "" errorDescription = aDecoder.value(forKey: "errorDescription") as? String ?? "" titleLabel = UILabel() descriptionLabel = UILabel() labelStack = UIStackView() super.init(coder: aDecoder) layoutLabels() } private func layoutLabels() { contentView.addSubview(labelStack) labelStack.translatesAutoresizingMaskIntoConstraints = false labelStack.addArrangedSubview(titleLabel) labelStack.addArrangedSubview(descriptionLabel) labelStack.axis = .vertical labelStack.spacing = Constants.labelSpacing titleLabel.font = WPStyleGuide.fontForTextStyle(.footnote) titleLabel.textColor = WPStyleGuide.greyDarken30() descriptionLabel.font = WPStyleGuide.mediumWeightFont(forStyle: .subheadline) descriptionLabel.textColor = WPStyleGuide.darkGrey() descriptionLabel.numberOfLines = 0 descriptionLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Constants.descriptionMinHeight).isActive = true contentView.addConstraints([ contentView.topAnchor.constraint(equalTo: labelStack.topAnchor, constant: Constants.labelVerticalMargin * -1.0), contentView.bottomAnchor.constraint(equalTo: labelStack.bottomAnchor, constant: Constants.labelVerticalMargin), contentView.layoutMarginsGuide.leadingAnchor.constraint(equalTo: labelStack.leadingAnchor), contentView.layoutMarginsGuide.trailingAnchor.constraint(equalTo: labelStack.trailingAnchor) ]) titleLabel.text = errorTitle.localizedUppercase descriptionLabel.text = errorDescription backgroundColor = WPStyleGuide.greyLighten30() } }
gpl-2.0
12802fae331ab3956940bc39e4bd3735
39.107692
126
0.709628
5.89819
false
false
false
false
Sol88/GASSwiftExtensions
GASSwiftExtensions/Sources/UIView+CreateFromNib.swift
1
1272
// Created by Виктор Заикин on 02.06.16. // Copyright © 2016 Виктор Заикин. All rights reserved. import UIKit public extension UIView { public class func fromNib(_ nibNameOrNil: String? = nil) -> Self { return _fromNib(nibNameOrNil) } public class func _fromNib<T : UIView>(_ nibNameOrNil: String? = nil) -> T { let v: T? = _fromNib(nibNameOrNil) return v! } public class func _fromNib<T : UIView>(_ nibNameOrNil: String? = nil) -> T? { var view: T? let name: String if let nibName = nibNameOrNil { name = nibName } else { name = nibName } let nibViews = Bundle.main.loadNibNamed(name, owner: nil, options: nil) for v in nibViews! { if let tog = v as? T { view = tog } } return view } public class var nibName: String { let name = "\(self)".components(separatedBy: ".").first ?? "" return name } public class var nib: UINib? { if let _ = Bundle.main.path(forResource: nibName, ofType: "nib") { return UINib(nibName: nibName, bundle: nil) } else { return nil } } }
mit
cf1cdad8368be0501161bff2f7b5f60a
27.340909
81
0.534082
4.101974
false
false
false
false
jeffreybergier/Hipstapaper
Hipstapaper/Packages/V3Localize/Sources/V3Localize/Raw/Nouns.swift
1
3393
// // Created by Jeffrey Bergier on 2020/12/24. // // MIT License // // Copyright (c) 2021 Jeffrey Bergier // // 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 SwiftUI import Umbrella public enum Noun: LocalizationKey { case search = "Noun.Search" case readingList = "Noun.ReadingList" case tags = "Noun.Tags" case website = "Noun.Website" case untitled = "Noun.Untitled" case allItems = "Noun.AllItems" case unreadItems = "Noun.UnreadItems" case autofillURL = "Noun.AutofillURL" case filledURL = "Noun.FilledURL" case originalURL = "Noun.OriginalURL" case resolvedURL = "Noun.ResolvedURL" case websiteTitle = "Noun.WebsiteTitle" case hipstapaper = "Noun.Hipstapaper" case tagName = "Noun.TagName" case addChoice = "Noun.AddChoice" case addTag = "Noun.AddTag" case editTags = "Noun.EditTags" case addWebsite = "Noun.AddWebsite" case editWebsite = "Noun.EditWebsite" case tagApply = "Noun.ApplyTags" case sort = "Noun.Sort" case share = "Noun.Share" case filter = "Noun.Filter" case error = "Noun.Error" case errors = "Noun.Errors" case errorDatabase = "Noun.ErrorDatabase" case erroriCloud = "Noun.iCloud" case deleteTag = "Noun.DeleteTag" case deleteWebsite = "Noun.DeleteWebsite" case thumbnail = "Noun.Thumbnail" case title = "Noun.Title" case url = "Noun.URL" case dateCreated = "Noun.DateCreated" case dateModified = "Noun.DateModified" case dash = "Noun.Dash" case sortDateModifiedNewest = "Noun.SortDateModifiedNewest" case sortDateModifiedOldest = "Noun.SortDateModifiedOldest" case sortDateCreatedNewest = "Noun.SortDateCreatedNewest" case sortDateCreatedOldest = "Noun.SortDateCreatedOldest" case sortTitleA = "Noun.SortTitleA" case sortTitleZ = "Noun.SortTitleZ" }
mit
36890d374c26d75a18ecffeaed980cb4
46.125
82
0.612732
4.34443
false
false
false
false
tarun-talentica/TalNet
Source/Response/QueryResponse.swift
2
2385
// // Response.swift // Pod-In-Playground // // Created by Tarun Sharma on 12/05/16. // Copyright © 2016 Tarun Sharma. All rights reserved. // import Foundation public struct QueryResponse<Value,Error:ErrorType> { /// The URL request sent to the server. public let request: NSURLRequest? /// The server's response to the URL request. public let response: NSHTTPURLResponse? /// HttpResponse status code public let statusCode:Int? /// The result of response serialization. public let result: QueryResult<Value, Error> public init(request: NSURLRequest? = nil, response: NSHTTPURLResponse? = nil, statusCode:Int? = nil, result:QueryResult<Value, Error>) { self.request = request self.response = response self.statusCode = statusCode self.result = result } } // MARK: - CustomDebugStringConvertible extension QueryResponse: CustomDebugStringConvertible { /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the server data and the response serialization result. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!)" : "[Request]: NIL") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: NIL") output.append(statusCode != nil ? "[Status Code]: \(statusCode)" : "[Status Code]: NIL") output.append("[Result]: \(result.debugDescription)") return output.joinWithSeparator("\n") } } public struct StringResponse: StringSerializable { public var encoding: NSStringEncoding? public init(encoding: NSStringEncoding? = nil) { self.encoding = encoding } } public struct JSONResponse: JsonSerializable { public var jsonOptions: NSJSONReadingOptions public init(jsonOptions: NSJSONReadingOptions = .AllowFragments) { self.jsonOptions = jsonOptions } } public struct ObjectResponse<T:ObjectMappable>: ObjectSerializable { public typealias ObjectType = T public init() {} } public struct ObjectArrayResponse<T:ObjectMappable>: ObjectArraySerializable { public typealias ObjectType = T public var keyPath: String? public init(keyPath:String? = nil) { self.keyPath = keyPath } }
mit
2bb7ad0eb3d698ecdb4c339d3185bdd5
29.961039
119
0.680369
4.67451
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/SearchVC/KidsPicker/HLKidsPickerTableCell.swift
1
7030
import UIKit enum HLKidsPickerTableCellState { case disabled case ready case selected } class HLKidsPickerTableCell: UITableViewCell { var deleteCellHandler:((_ cell: HLKidsPickerTableCell) -> Void)? var willBeginEditingCellHandler:((_ cell: HLKidsPickerTableCell) -> Void)? var didEndEditingCellHandler:((_ cell: HLKidsPickerTableCell) -> Void)? var kidNumber: Int = 1 { didSet { self.kidCountLabel?.text = "\(kidNumber)" } } var kidAge: Int = 0 { didSet { self.updateControl() } } var state: HLKidsPickerTableCellState = HLKidsPickerTableCellState.ready { didSet { self.updateControl() } } lazy private var panGestureRecognizer: HLPanGestureRecognizer = { [unowned self] in let recognizer = HLPanGestureRecognizer(target: self, action: #selector(HLKidsPickerTableCell.onPan(_:))) recognizer.direction = HLPanGestureRecognizerDirectionHorizontal return recognizer }() @IBOutlet fileprivate weak var titleLabel: UILabel! @IBOutlet fileprivate weak var kidCountLabel: UILabel! @IBOutlet fileprivate weak var kidCountIcon: UIImageView! @IBOutlet fileprivate weak var disclosureIcon: UIImageView! @IBOutlet fileprivate weak var rightDeleteButtonConstraint: NSLayoutConstraint! @IBOutlet fileprivate weak var leftKidCountIconConstraint: NSLayoutConstraint! @IBOutlet weak var deleteButton: UIButton! private let disclosureImage = UIImage(named: "cellDisclosureIcon")!.imageTinted(with: JRColorScheme.actionColor()) private let disclosureImageDisabled = UIImage(named: "cellDisclosureIcon")! private let kidCountImage = UIImage(named: "searchFormButton")! private let kidCountImageSelected = UIImage(named: "searchFormButtonSelected")!.imageTinted(with: JRColorScheme.actionColor()) private let kidCountImageDisabled = UIImage(named: "searchFormButton")!.imageTinted(with: JRColorScheme.lightBackgroundColor()) private let kKidCountIconLeftConstraint: CGFloat = 20.0 private let kDeleteButtonRightConstraint: CGFloat = -80.0 // MARK: - Override methods override func awakeFromNib() { super.awakeFromNib() kidCountIcon.highlightedImage = UIImage(named: "searchFormButton")!.imageTinted(with: JRColorScheme.mainBackgroundColor()) } override func setSelected(_ selected: Bool, animated: Bool) { if isEditing || state == HLKidsPickerTableCellState.disabled { return } super.setSelected(selected, animated: animated) } override func setHighlighted(_ highlighted: Bool, animated: Bool) { if isEditing || state == HLKidsPickerTableCellState.disabled { hideDeleteButton(true) return } super.setHighlighted(highlighted, animated: animated) disclosureIcon.isHighlighted = highlighted titleLabel.isHighlighted = highlighted kidCountLabel.isHighlighted = highlighted kidCountIcon.isHighlighted = highlighted } // MARK: - Public methods func showDeleteButton(_ animated: Bool) { if isEditing { return } willBeginEditingCellHandler?(self) let duration = animated ? 0.3 : 0.0 UIView.animate(withDuration: duration, delay: 0.0, options: UIView.AnimationOptions(), animations: { [unowned self] () -> Void in self.rightDeleteButtonConstraint.constant = 0.0 self.leftKidCountIconConstraint.constant = self.kKidCountIconLeftConstraint + self.kDeleteButtonRightConstraint self.layoutIfNeeded() }, completion: { [unowned self] (finished) -> Void in self.isEditing = true }) } func hideDeleteButton(_ animated: Bool) { let duration = animated ? 0.3 : 0.0 UIView.animate(withDuration: duration, delay: 0.0, options: UIView.AnimationOptions(), animations: { [unowned self] () -> Void in self.rightDeleteButtonConstraint.constant = self.kDeleteButtonRightConstraint self.leftKidCountIconConstraint.constant = self.kKidCountIconLeftConstraint self.layoutIfNeeded() }, completion: { [unowned self] (finished) -> Void in self.didEndEditingCellHandler?(self) self.isEditing = false }) } // MARK: - Private methods private func updateControl() { switch state { case HLKidsPickerTableCellState.disabled: disclosureIcon?.image = disclosureImageDisabled kidCountIcon.image = kidCountImageDisabled titleLabel?.text = NSLS("HL_KIDS_PICKER_CELL_SELECT_AGE_TITLE") titleLabel?.textColor = JRColorScheme.inactiveLightTextColor() kidCountLabel?.textColor = JRColorScheme.inactiveLightTextColor() removeGestureRecognizer(panGestureRecognizer) isUserInteractionEnabled = false case HLKidsPickerTableCellState.ready: disclosureIcon?.image = disclosureImage kidCountIcon.image = kidCountImage titleLabel?.text = NSLS("HL_KIDS_PICKER_CELL_SELECT_AGE_TITLE") titleLabel?.textColor = JRColorScheme.darkTextColor() kidCountLabel?.textColor = JRColorScheme.darkTextColor() removeGestureRecognizer(panGestureRecognizer) isUserInteractionEnabled = true case HLKidsPickerTableCellState.selected: disclosureIcon?.image = disclosureImage kidCountIcon.image = kidCountImageSelected titleLabel.text = StringUtils.kidAgeText(withAge: kidAge) titleLabel.textColor = JRColorScheme.darkTextColor() kidCountLabel.textColor = UIColor.white addGestureRecognizer(panGestureRecognizer) isUserInteractionEnabled = true } } @objc private func onPan(_ gestureRecognizer: HLPanGestureRecognizer) { let velocity = gestureRecognizer.velocity(in: self) let translation = gestureRecognizer.translation(in: self) let startRightPosition = isEditing ? 0.0 : kDeleteButtonRightConstraint var constraint = startRightPosition - translation.x constraint = max(min(constraint, 0.0), kDeleteButtonRightConstraint) switch gestureRecognizer.state { case UIGestureRecognizer.State.changed: rightDeleteButtonConstraint.constant = constraint leftKidCountIconConstraint.constant = kDeleteButtonRightConstraint + kKidCountIconLeftConstraint - constraint layoutIfNeeded() case UIGestureRecognizer.State.ended: velocity.x < 0 ? showDeleteButton(true) : hideDeleteButton(true) case UIGestureRecognizer.State.cancelled: hideDeleteButton(true) default: break } } // MARK: - IBActions methods @IBAction func onDelete(_ sender: AnyObject) { deleteCellHandler?(self) } }
mit
2781b12efe104d718edbb2631fe3b5b1
37
137
0.681223
5.215134
false
false
false
false
GirAppe/BTracker
BTracker/ViewController.swift
1
2223
// // ViewController.swift // BTracker // // Created by git on 05/29/2017. // Copyright (c) 2017 git. All rights reserved. // import UIKit import BTracker class ViewController: UIViewController { let manager = TrackingManager() override func viewDidLoad() { super.viewDidLoad() manager.start() let beacon = Beacon(identifier: "ice", proximityUUID: "B9407F30-F5F8-466E-AFF9-25556B57FE6A", major: 33, minor: 33, motionUUID: "39407F30-F5F8-466E-AFF9-25556B57FE6A")! let beacon2 = Beacon(identifier: "blueberry", proximityUUID: "B9407F30-F5F8-466E-AFF9-25556B57FE6A", major: 1, minor: 1)! manager.track(beacon).onEvent { event in switch event { case .regionDidEnter: print("ICE Region did enter") case .regionDidExit: print("ICE Region did exit") case .motionDidStart: print("ICE Motion did start") case .motionDidEnd: print("ICE Motion did end") case .proximityDidChange(let proximity): if let proximity = proximity { print("ICE Proximity changed: \(proximity)") } else { print("ICE Proximity changed: unknown") } // default: break } } manager.track(beacon2).onEvent { event in switch event { case .regionDidEnter: print("BLUEBERRY Region did enter") case .regionDidExit: print("BLUEBERRY Region did exit") case .motionDidStart: print("BLUEBERRY Motion did start") case .motionDidEnd: print("BLUEBERRY Motion did end") case .proximityDidChange(let proximity): if let proximity = proximity { print("BLUEBERRY Proximity changed: \(proximity)") } else { print("BLUEBERRY Proximity changed: unknown") } // default: break } } } }
mit
81e2acae9c53f57fd7a46b6096bf84a1
34.285714
176
0.51507
4.811688
false
false
false
false
kevinmbeaulieu/Signal-iOS
Signal/src/call/PeerConnectionClient.swift
1
33862
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation import PromiseKit import WebRTC // HACK - Seeing crazy SEGFAULTs on iOS9 when accessing these objc externs. // iOS10 seems unaffected. Reproducible for ~1 in 3 calls. // Binding them to a file constant seems to work around the problem. let kAudioTrackType = kRTCMediaStreamTrackKindAudio let kVideoTrackType = kRTCMediaStreamTrackKindVideo let kMediaConstraintsMinWidth = kRTCMediaConstraintsMinWidth let kMediaConstraintsMaxWidth = kRTCMediaConstraintsMaxWidth let kMediaConstraintsMinHeight = kRTCMediaConstraintsMinHeight let kMediaConstraintsMaxHeight = kRTCMediaConstraintsMaxHeight /** * The PeerConnectionClient notifies it's delegate (the CallService) of key events in the call signaling life cycle * * The delegate's methods will always be called on the main thread. */ protocol PeerConnectionClientDelegate: class { /** * The connection has been established. The clients can now communicate. */ func peerConnectionClientIceConnected(_ peerconnectionClient: PeerConnectionClient) /** * The connection failed to establish. The clients will not be able to communicate. */ func peerConnectionClientIceFailed(_ peerconnectionClient: PeerConnectionClient) /** * During the Signaling process each client generates IceCandidates locally, which contain information about how to * reach the local client via the internet. The delegate must shuttle these IceCandates to the other (remote) client * out of band, as part of establishing a connection over WebRTC. */ func peerConnectionClient(_ peerconnectionClient: PeerConnectionClient, addedLocalIceCandidate iceCandidate: RTCIceCandidate) /** * Once the peerconnection is established, we can receive messages via the data channel, and notify the delegate. */ func peerConnectionClient(_ peerconnectionClient: PeerConnectionClient, received dataChannelMessage: OWSWebRTCProtosData) /** * Fired whenever the local video track become active or inactive. */ func peerConnectionClient(_ peerconnectionClient: PeerConnectionClient, didUpdateLocal videoTrack: RTCVideoTrack?) /** * Fired whenever the remote video track become active or inactive. */ func peerConnectionClient(_ peerconnectionClient: PeerConnectionClient, didUpdateRemote videoTrack: RTCVideoTrack?) } /** * `PeerConnectionClient` is our interface to WebRTC. * * It is primarily a wrapper around `RTCPeerConnection`, which is responsible for sending and receiving our call data * including audio, video, and some post-connected signaling (hangup, add video) */ class PeerConnectionClient: NSObject, RTCPeerConnectionDelegate, RTCDataChannelDelegate { let TAG = "[PeerConnectionClient]" enum Identifiers: String { case mediaStream = "ARDAMS", videoTrack = "ARDAMSv0", audioTrack = "ARDAMSa0", dataChannelSignaling = "signaling" } // A state in this class should only be accessed on this queue in order to // serialize access. // // This queue is also used to perform expensive calls to the WebRTC API. private static let signalingQueue = DispatchQueue(label: "CallServiceSignalingQueue") // Delegate is notified of key events in the call lifecycle. private weak var delegate: PeerConnectionClientDelegate! func setDelegate(delegate: PeerConnectionClientDelegate?) { PeerConnectionClient.signalingQueue.async { self.delegate = delegate } } // Connection private var peerConnection: RTCPeerConnection! private let iceServers: [RTCIceServer] private let connectionConstraints: RTCMediaConstraints private let configuration: RTCConfiguration private let factory = RTCPeerConnectionFactory() // DataChannel private var dataChannel: RTCDataChannel? // Audio private var audioSender: RTCRtpSender? private var audioTrack: RTCAudioTrack? private var audioConstraints: RTCMediaConstraints static private let sharedAudioSession = CallAudioSession() // Video private var videoCaptureSession: AVCaptureSession? private var videoSender: RTCRtpSender? private var localVideoTrack: RTCVideoTrack? // RTCVideoTrack is fragile and prone to throwing exceptions and/or // causing deadlock in its destructor. Therefore we take great care // with this property. // // We synchronize access to this property and ensure that we never // set or use a strong reference to the remote video track if // peerConnection is nil. private var remoteVideoTrack: RTCVideoTrack? private var cameraConstraints: RTCMediaConstraints init(iceServers: [RTCIceServer], delegate: PeerConnectionClientDelegate, callDirection: CallDirection, useTurnOnly: Bool) { AssertIsOnMainThread() self.iceServers = iceServers self.delegate = delegate configuration = RTCConfiguration() configuration.iceServers = iceServers configuration.bundlePolicy = .maxBundle configuration.rtcpMuxPolicy = .require if useTurnOnly { Logger.debug("\(TAG) using iceTransportPolicy: relay") configuration.iceTransportPolicy = .relay } else { Logger.debug("\(TAG) using iceTransportPolicy: default") } let connectionConstraintsDict = ["DtlsSrtpKeyAgreement": "true"] connectionConstraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: connectionConstraintsDict) audioConstraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints:nil) cameraConstraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil) super.init() // Configure audio session so we don't prompt user with Record permission until call is connected. type(of: self).configureAudioSession() peerConnection = factory.peerConnection(with: configuration, constraints: connectionConstraints, delegate: self) createAudioSender() createVideoSender() if callDirection == .outgoing { // When placing an outgoing call, it's our responsibility to create the DataChannel. // Recipient will not have to do this explicitly. createSignalingDataChannel() } } // MARK: - Media Streams private func createSignalingDataChannel() { AssertIsOnMainThread() let dataChannel = peerConnection.dataChannel(forLabel: Identifiers.dataChannelSignaling.rawValue, configuration: RTCDataChannelConfiguration()) dataChannel.delegate = self assert(self.dataChannel == nil) self.dataChannel = dataChannel } // MARK: Video fileprivate func createVideoSender() { AssertIsOnMainThread() Logger.debug("\(TAG) in \(#function)") assert(self.videoSender == nil, "\(#function) should only be called once.") guard !Platform.isSimulator else { Logger.warn("\(TAG) Refusing to create local video track on simulator which has no capture device.") return } // TODO: We could cap the maximum video size. let cameraConstraints = RTCMediaConstraints(mandatoryConstraints:nil, optionalConstraints:nil) // TODO: Revisit the cameraConstraints. let videoSource = factory.avFoundationVideoSource(with: cameraConstraints) self.videoCaptureSession = videoSource.captureSession videoSource.useBackCamera = false let localVideoTrack = factory.videoTrack(with: videoSource, trackId: Identifiers.videoTrack.rawValue) self.localVideoTrack = localVideoTrack // Disable by default until call is connected. // FIXME - do we require mic permissions at this point? // if so maybe it would be better to not even add the track until the call is connected // instead of creating it and disabling it. localVideoTrack.isEnabled = false let videoSender = peerConnection.sender(withKind: kVideoTrackType, streamId: Identifiers.mediaStream.rawValue) videoSender.track = localVideoTrack self.videoSender = videoSender } public func setLocalVideoEnabled(enabled: Bool) { AssertIsOnMainThread() PeerConnectionClient.signalingQueue.async { guard self.peerConnection != nil else { Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client") return } guard let localVideoTrack = self.localVideoTrack else { let action = enabled ? "enable" : "disable" Logger.error("\(self.TAG)) trying to \(action) videoTrack which doesn't exist") return } guard let videoCaptureSession = self.videoCaptureSession else { Logger.error("\(self.TAG) videoCaptureSession was unexpectedly nil") assertionFailure() return } localVideoTrack.isEnabled = enabled if enabled { Logger.debug("\(self.TAG) in \(#function) starting videoCaptureSession") videoCaptureSession.startRunning() } else { Logger.debug("\(self.TAG) in \(#function) stopping videoCaptureSession") videoCaptureSession.stopRunning() } if let delegate = self.delegate { DispatchQueue.main.async { [weak self, weak localVideoTrack] in guard let strongSelf = self else { return } guard let strongLocalVideoTrack = localVideoTrack else { return } delegate.peerConnectionClient(strongSelf, didUpdateLocal: enabled ? strongLocalVideoTrack : nil) } } } } // MARK: Audio fileprivate func createAudioSender() { AssertIsOnMainThread() Logger.debug("\(TAG) in \(#function)") assert(self.audioSender == nil, "\(#function) should only be called once.") let audioSource = factory.audioSource(with: self.audioConstraints) let audioTrack = factory.audioTrack(with: audioSource, trackId: Identifiers.audioTrack.rawValue) self.audioTrack = audioTrack // Disable by default until call is connected. // FIXME - do we require mic permissions at this point? // if so maybe it would be better to not even add the track until the call is connected // instead of creating it and disabling it. audioTrack.isEnabled = false let audioSender = peerConnection.sender(withKind: kAudioTrackType, streamId: Identifiers.mediaStream.rawValue) audioSender.track = audioTrack self.audioSender = audioSender } public func setAudioEnabled(enabled: Bool) { AssertIsOnMainThread() PeerConnectionClient.signalingQueue.async { guard self.peerConnection != nil else { Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client") return } guard let audioTrack = self.audioTrack else { let action = enabled ? "enable" : "disable" Logger.error("\(self.TAG) trying to \(action) audioTrack which doesn't exist.") return } audioTrack.isEnabled = enabled } } // MARK: - Session negotiation private var defaultOfferConstraints: RTCMediaConstraints { let mandatoryConstraints = [ "OfferToReceiveAudio": "true", "OfferToReceiveVideo": "true" ] return RTCMediaConstraints(mandatoryConstraints:mandatoryConstraints, optionalConstraints:nil) } public func createOffer() -> Promise<HardenedRTCSessionDescription> { AssertIsOnMainThread() return Promise { fulfill, reject in AssertIsOnMainThread() PeerConnectionClient.signalingQueue.async { guard self.peerConnection != nil else { Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client") reject(NSError(domain:"Obsolete client", code:0, userInfo:nil)) return } self.peerConnection.offer(for: self.defaultOfferConstraints, completionHandler: { (sdp: RTCSessionDescription?, error: Error?) in PeerConnectionClient.signalingQueue.async { guard self.peerConnection != nil else { Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client") reject(NSError(domain:"Obsolete client", code:0, userInfo:nil)) return } guard error == nil else { reject(error!) return } guard let sessionDescription = sdp else { Logger.error("\(self.TAG) No session description was obtained, even though there was no error reported.") let error = OWSErrorMakeUnableToProcessServerResponseError() reject(error) return } fulfill(HardenedRTCSessionDescription(rtcSessionDescription: sessionDescription)) } }) } } } public func setLocalSessionDescriptionInternal(_ sessionDescription: HardenedRTCSessionDescription) -> Promise<Void> { return PromiseKit.wrap { resolve in self.assertOnSignalingQueue() Logger.verbose("\(self.TAG) setting local session description: \(sessionDescription)") self.peerConnection.setLocalDescription(sessionDescription.rtcSessionDescription, completionHandler:resolve) } } public func setLocalSessionDescription(_ sessionDescription: HardenedRTCSessionDescription) -> Promise<Void> { AssertIsOnMainThread() return Promise { fulfill, reject in PeerConnectionClient.signalingQueue.async { guard self.peerConnection != nil else { Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client") reject(NSError(domain:"Obsolete client", code:0, userInfo:nil)) return } Logger.verbose("\(self.TAG) setting local session description: \(sessionDescription)") self.peerConnection.setLocalDescription(sessionDescription.rtcSessionDescription, completionHandler: { _ in fulfill() }) } } } public func negotiateSessionDescription(remoteDescription: RTCSessionDescription, constraints: RTCMediaConstraints) -> Promise<HardenedRTCSessionDescription> { AssertIsOnMainThread() return setRemoteSessionDescription(remoteDescription) .then(on: PeerConnectionClient.signalingQueue) { return self.negotiateAnswerSessionDescription(constraints: constraints) } } public func setRemoteSessionDescription(_ sessionDescription: RTCSessionDescription) -> Promise<Void> { AssertIsOnMainThread() return Promise { fulfill, reject in PeerConnectionClient.signalingQueue.async { guard self.peerConnection != nil else { Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client") reject(NSError(domain:"Obsolete client", code:0, userInfo:nil)) return } Logger.verbose("\(self.TAG) setting remote description: \(sessionDescription)") self.peerConnection.setRemoteDescription(sessionDescription, completionHandler: { _ in fulfill() }) } } } private func negotiateAnswerSessionDescription(constraints: RTCMediaConstraints) -> Promise<HardenedRTCSessionDescription> { assertOnSignalingQueue() return Promise { fulfill, reject in assertOnSignalingQueue() guard self.peerConnection != nil else { Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client") reject(NSError(domain:"Obsolete client", code:0, userInfo:nil)) return } Logger.debug("\(self.TAG) negotiating answer session.") peerConnection.answer(for: constraints, completionHandler: { (sdp: RTCSessionDescription?, error: Error?) in PeerConnectionClient.signalingQueue.async { guard self.peerConnection != nil else { Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client") reject(NSError(domain:"Obsolete client", code:0, userInfo:nil)) return } guard error == nil else { reject(error!) return } guard let sessionDescription = sdp else { Logger.error("\(self.TAG) unexpected empty session description, even though no error was reported.") let error = OWSErrorMakeUnableToProcessServerResponseError() reject(error) return } let hardenedSessionDescription = HardenedRTCSessionDescription(rtcSessionDescription: sessionDescription) self.setLocalSessionDescriptionInternal(hardenedSessionDescription) .then(on: PeerConnectionClient.signalingQueue) { fulfill(hardenedSessionDescription) }.catch { error in reject(error) } } }) } } public func addIceCandidate(_ candidate: RTCIceCandidate) { PeerConnectionClient.signalingQueue.async { guard self.peerConnection != nil else { Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client") return } Logger.debug("\(self.TAG) adding candidate") self.peerConnection.add(candidate) } } public func terminate() { AssertIsOnMainThread() Logger.debug("\(TAG) in \(#function)") PeerConnectionClient.signalingQueue.async { assert(self.peerConnection != nil) self.terminateInternal() } } private func terminateInternal() { assertOnSignalingQueue() Logger.debug("\(TAG) in \(#function)") // Some notes on preventing crashes while disposing of peerConnection for video calls // from: https://groups.google.com/forum/#!searchin/discuss-webrtc/objc$20crash$20dealloc%7Csort:relevance/discuss-webrtc/7D-vk5yLjn8/rBW2D6EW4GYJ // The sequence to make it work appears to be // // [capturer stop]; // I had to add this as a method to RTCVideoCapturer // [localRenderer stop]; // [remoteRenderer stop]; // [peerConnection close]; // audioTrack is a strong property because we need access to it to mute/unmute, but I was seeing it // become nil when it was only a weak property. So we retain it and manually nil the reference here, because // we are likely to crash if we retain any peer connection properties when the peerconnection is released // See the comments on the remoteVideoTrack property. objc_sync_enter(self) localVideoTrack?.isEnabled = false remoteVideoTrack?.isEnabled = false dataChannel = nil audioSender = nil audioTrack = nil videoSender = nil localVideoTrack = nil remoteVideoTrack = nil peerConnection.delegate = nil peerConnection.close() peerConnection = nil objc_sync_exit(self) delegate = nil } // MARK: - Data Channel public func sendDataChannelMessage(data: Data) { AssertIsOnMainThread() PeerConnectionClient.signalingQueue.async { guard self.peerConnection != nil else { Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client") return } guard let dataChannel = self.dataChannel else { Logger.error("\(self.TAG) in \(#function) ignoring sending \(data) for nil dataChannel") return } let buffer = RTCDataBuffer(data: data, isBinary: false) let result = dataChannel.sendData(buffer) if result { Logger.debug("\(self.TAG) sendDataChannelMessage succeeded") } else { Logger.warn("\(self.TAG) sendDataChannelMessage failed") } } } // MARK: RTCDataChannelDelegate /** The data channel state changed. */ internal func dataChannelDidChangeState(_ dataChannel: RTCDataChannel) { Logger.debug("\(TAG) dataChannelDidChangeState: \(dataChannel)") } /** The data channel successfully received a data buffer. */ internal func dataChannel(_ dataChannel: RTCDataChannel, didReceiveMessageWith buffer: RTCDataBuffer) { PeerConnectionClient.signalingQueue.async { guard self.peerConnection != nil else { Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client") return } Logger.debug("\(self.TAG) dataChannel didReceiveMessageWith buffer:\(buffer)") guard let dataChannelMessage = OWSWebRTCProtosData.parse(from:buffer.data) else { // TODO can't proto parsings throw an exception? Is it just being lost in the Objc->Swift? Logger.error("\(self.TAG) failed to parse dataProto") return } if let delegate = self.delegate { DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } delegate.peerConnectionClient(strongSelf, received: dataChannelMessage) } } } } /** The data channel's |bufferedAmount| changed. */ internal func dataChannel(_ dataChannel: RTCDataChannel, didChangeBufferedAmount amount: UInt64) { Logger.debug("\(TAG) didChangeBufferedAmount: \(amount)") } // MARK: - RTCPeerConnectionDelegate /** Called when the SignalingState changed. */ internal func peerConnection(_ peerConnection: RTCPeerConnection, didChange stateChanged: RTCSignalingState) { Logger.debug("\(TAG) didChange signalingState:\(stateChanged.debugDescription)") } /** Called when media is received on a new stream from remote peer. */ internal func peerConnection(_ peerConnection: RTCPeerConnection, didAdd stream: RTCMediaStream) { guard stream.videoTracks.count > 0 else { return } let remoteVideoTrack = stream.videoTracks[0] Logger.debug("\(self.TAG) didAdd stream:\(stream) video tracks: \(stream.videoTracks.count) audio tracks: \(stream.audioTracks.count)") // See the comments on the remoteVideoTrack property. // // We only set the remoteVideoTrack property if peerConnection is non-nil. objc_sync_enter(self) if self.peerConnection != nil { self.remoteVideoTrack = remoteVideoTrack } objc_sync_exit(self) PeerConnectionClient.signalingQueue.async { guard self.peerConnection != nil else { Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client") return } if let delegate = self.delegate { DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } // See the comments on the remoteVideoTrack property. // // We only access the remoteVideoTrack property if peerConnection is non-nil. var remoteVideoTrack: RTCVideoTrack? objc_sync_enter(strongSelf) if strongSelf.peerConnection != nil { remoteVideoTrack = strongSelf.remoteVideoTrack } objc_sync_exit(strongSelf) delegate.peerConnectionClient(strongSelf, didUpdateRemote: remoteVideoTrack) } } } } /** Called when a remote peer closes a stream. */ internal func peerConnection(_ peerConnection: RTCPeerConnection, didRemove stream: RTCMediaStream) { Logger.debug("\(TAG) didRemove Stream:\(stream)") } /** Called when negotiation is needed, for example ICE has restarted. */ internal func peerConnectionShouldNegotiate(_ peerConnection: RTCPeerConnection) { Logger.debug("\(TAG) shouldNegotiate") } /** Called any time the IceConnectionState changes. */ internal func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState) { PeerConnectionClient.signalingQueue.async { guard self.peerConnection != nil else { Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client") return } Logger.debug("\(self.TAG) didChange IceConnectionState:\(newState.debugDescription)") switch newState { case .connected, .completed: if let delegate = self.delegate { DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } delegate.peerConnectionClientIceConnected(strongSelf) } } case .failed: Logger.warn("\(self.TAG) RTCIceConnection failed.") if let delegate = self.delegate { DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } delegate.peerConnectionClientIceFailed(strongSelf) } } case .disconnected: Logger.warn("\(self.TAG) RTCIceConnection disconnected.") default: Logger.debug("\(self.TAG) ignoring change IceConnectionState:\(newState.debugDescription)") } } } /** Called any time the IceGatheringState changes. */ internal func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceGatheringState) { Logger.debug("\(TAG) didChange IceGatheringState:\(newState.debugDescription)") } /** New ice candidate has been found. */ internal func peerConnection(_ peerConnection: RTCPeerConnection, didGenerate candidate: RTCIceCandidate) { PeerConnectionClient.signalingQueue.async { guard self.peerConnection != nil else { Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client") return } Logger.debug("\(self.TAG) didGenerate IceCandidate:\(candidate.sdp)") if let delegate = self.delegate { DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } delegate.peerConnectionClient(strongSelf, addedLocalIceCandidate: candidate) } } } } /** Called when a group of local Ice candidates have been removed. */ internal func peerConnection(_ peerConnection: RTCPeerConnection, didRemove candidates: [RTCIceCandidate]) { Logger.debug("\(TAG) didRemove IceCandidates:\(candidates)") } /** New data channel has been opened. */ internal func peerConnection(_ peerConnection: RTCPeerConnection, didOpen dataChannel: RTCDataChannel) { PeerConnectionClient.signalingQueue.async { guard self.peerConnection != nil else { Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client") return } Logger.debug("\(self.TAG) didOpen dataChannel:\(dataChannel)") assert(self.dataChannel == nil) self.dataChannel = dataChannel dataChannel.delegate = self } } // Mark: Audio Session class func configureAudioSession() { sharedAudioSession.configure() } class func startAudioSession() { sharedAudioSession.start() } class func stopAudioSession() { sharedAudioSession.stop() } // MARK: Helpers /** * We synchronize access to state in this class using this queue. */ private func assertOnSignalingQueue() { if #available(iOS 10.0, *) { dispatchPrecondition(condition: .onQueue(type(of: self).signalingQueue)) } else { // Skipping check on <iOS10, since syntax is different and it's just a development convenience. } } // MARK: Test-only accessors internal func peerConnectionForTests() -> RTCPeerConnection { AssertIsOnMainThread() var result: RTCPeerConnection? = nil PeerConnectionClient.signalingQueue.sync { result = peerConnection Logger.info("\(self.TAG) called \(#function)") } return result! } internal func dataChannelForTests() -> RTCDataChannel { AssertIsOnMainThread() var result: RTCDataChannel? = nil PeerConnectionClient.signalingQueue.sync { result = dataChannel Logger.info("\(self.TAG) called \(#function)") } return result! } internal func flushSignalingQueueForTests() { AssertIsOnMainThread() PeerConnectionClient.signalingQueue.sync { // Noop. } } } /** * Restrict an RTCSessionDescription to more secure parameters */ class HardenedRTCSessionDescription { let rtcSessionDescription: RTCSessionDescription var sdp: String { return rtcSessionDescription.sdp } init(rtcSessionDescription: RTCSessionDescription) { self.rtcSessionDescription = HardenedRTCSessionDescription.harden(rtcSessionDescription: rtcSessionDescription) } /** * Set some more secure parameters for the session description */ class func harden(rtcSessionDescription: RTCSessionDescription) -> RTCSessionDescription { var description = rtcSessionDescription.sdp // Enforce Constant bit rate. let cbrRegex = try! NSRegularExpression(pattern:"(a=fmtp:111 ((?!cbr=).)*)\r?\n", options:.caseInsensitive) description = cbrRegex.stringByReplacingMatches(in: description, options: [], range: NSMakeRange(0, description.characters.count), withTemplate: "$1;cbr=1\r\n") // Strip plaintext audio-level details // https://tools.ietf.org/html/rfc6464 let audioLevelRegex = try! NSRegularExpression(pattern:".+urn:ietf:params:rtp-hdrext:ssrc-audio-level.*\r?\n", options:.caseInsensitive) description = audioLevelRegex.stringByReplacingMatches(in: description, options: [], range: NSMakeRange(0, description.characters.count), withTemplate: "") return RTCSessionDescription.init(type: rtcSessionDescription.type, sdp: description) } } // Mark: Pretty Print Objc enums. fileprivate extension RTCSignalingState { var debugDescription: String { switch self { case .stable: return "stable" case .haveLocalOffer: return "haveLocalOffer" case .haveLocalPrAnswer: return "haveLocalPrAnswer" case .haveRemoteOffer: return "haveRemoteOffer" case .haveRemotePrAnswer: return "haveRemotePrAnswer" case .closed: return "closed" } } } fileprivate extension RTCIceGatheringState { var debugDescription: String { switch self { case .new: return "new" case .gathering: return "gathering" case .complete: return "complete" } } } fileprivate extension RTCIceConnectionState { var debugDescription: String { switch self { case .new: return "new" case .checking: return "checking" case .connected: return "connected" case .completed: return "completed" case .failed: return "failed" case .disconnected: return "disconnected" case .closed: return "closed" case .count: return "count" } } }
gpl-3.0
b3562f40aacb89ff16508401b1b677b6
39.120853
168
0.62294
5.649316
false
false
false
false
nRewik/ArtHIstory
ArtHistory/ArtHistory/LessonViewController.swift
1
11168
// // LessonViewController.swift // ArtHistory // // Created by Nutchaphon Rewik on 7/11/15. // Copyright (c) 2015 Nutchaphon Rewik. All rights reserved. // import UIKit import FontAwesome_swift import ChameleonFramework import BubbleTransition class LessonViewController: UIViewController { // Init var lesson: Lesson! var colorTone: UIImageColors! // States var topHeadViewOrigin: CGFloat? var topHeadHeightOrigin: CGFloat? var readOriginFrame: CGRect? var readImageViewOriginFrame: CGRect? var readIndexPath: NSIndexPath? /// Need update manually for performance reason var lessonContentHeight: CGFloat = 0.0 var minimumTopViewHeight: CGFloat{ return 70.0 } var maximumTopViewHeight: CGFloat{ return 150.0 } @IBOutlet weak var topSpace_headViewConstraint: NSLayoutConstraint! @IBOutlet weak var heightConstraint_headView: NSLayoutConstraint! @IBOutlet weak var statusBarOverlayView: UIView! @IBOutlet weak var headView: UIView! @IBOutlet weak var headImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var backButton: UIButton! @IBOutlet weak var gradientView: UIView! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var statusBarDimView: UIView! @IBOutlet weak var dimView: UIView! @IBOutlet weak var readView: UIView! @IBOutlet weak var readViewTopConstraint: NSLayoutConstraint! @IBOutlet weak var readViewBottomConstraint: NSLayoutConstraint! @IBOutlet weak var readviewLeadingConstraint: NSLayoutConstraint! @IBOutlet weak var readViewTralingConstraint: NSLayoutConstraint! @IBOutlet weak var readImageView: UIImageView! @IBOutlet weak var readImageViewTopConstraint: NSLayoutConstraint! @IBOutlet weak var readImageViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var readTextView: UITextView! @IBOutlet weak var tableView: UITableView! func setupInset(){ tableView.contentInset = UIEdgeInsets(top: maximumTopViewHeight, left: 0, bottom: 0, right: 0) } func setupShadow(){ headView.layer.shadowColor = UIColor.flatBlackColor().CGColor headView.layer.shadowOffset = CGSize(width: 0.0, height: 1.0) headView.layer.shadowOpacity = 0.3 } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setupInset() setupShadow() backButton.titleLabel?.font = UIFont.fontAwesomeOfSize(35.0) backButton.setTitle(String.fontAwesomeIconWithName(.ChevronCircleLeft), forState: .Normal) readView.layer.cornerRadius = 6.0 headImageView.image = lesson.image titleLabel.text = lesson.title tableView.dataSource = self tableView.delegate = self setStatusBarStyle(UIStatusBarStyleContrast) view.layoutIfNeeded() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let titleColor = UIColor(contrastingBlackOrWhiteColorOn: colorTone.backgroundColor, isFlat: true) let complementTitleColor = UIColor(complementaryFlatColorOf: titleColor) backButton.setTitleColor(titleColor, forState: .Normal) backButton.setTitleColor(complementTitleColor, forState: .Highlighted) backButton.setTitleColor(complementTitleColor, forState: .Selected) titleLabel.textColor = titleColor statusBarOverlayView.backgroundColor = colorTone.backgroundColor } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // Update lessonContentHeight lessonContentHeight = { let titleAttributedString = NSAttributedString(string: lesson.detail, attributes: [NSFontAttributeName:UIFont(name: "HelveticaNeue-Thin", size: 18)!]) let constraintedSize = CGSize(width: tableView.frame.width-30, height: 9999.0) let titleHeight = titleAttributedString.boundingRectWithSize(constraintedSize, options: .UsesLineFragmentOrigin, context: nil).height return 20 + titleHeight + 20 }() updateGradientColor() } func updateGradientColor(){ let gradientColor = colorTone.backgroundColor gradientView.backgroundColor = UIColor(gradientStyle: .TopToBottom, withFrame: gradientView.frame, andColors: [ gradientColor.colorWithAlphaComponent(0.0),gradientColor]) } @IBAction func readCloseButtonDidTouch() { guard let readOriginFrame = readOriginFrame else { return } guard let readImageViewOriginFrame = readImageViewOriginFrame else { return } readViewTopConstraint.constant = readOriginFrame.origin.y readViewBottomConstraint.constant = view.bounds.height - (readOriginFrame.origin.y + readOriginFrame.height) readviewLeadingConstraint.constant = readOriginFrame.origin.x readViewTralingConstraint.constant = view.bounds.width - (readOriginFrame.origin.x + readOriginFrame.width) readImageViewTopConstraint.constant = readImageViewOriginFrame.origin.y readImageViewHeightConstraint.constant = readImageViewOriginFrame.height if let topHeadViewOrigin = topHeadViewOrigin{ topSpace_headViewConstraint.constant = topHeadViewOrigin } if let topHeadHeightOrigin = topHeadHeightOrigin{ heightConstraint_headView.constant = topHeadHeightOrigin } setStatusBarStyle(UIStatusBarStyleContrast) UIView.animateWithDuration(0.5, animations: { self.dimView.alpha = 0.0 self.statusBarDimView.alpha = 0.0 self.readView.alpha = 1.0 self.closeButton.alpha = 0.0 self.view.layoutIfNeeded() }, completion: { finish in if let readIndexPath = self.readIndexPath{ let cell = self.tableView.cellForRowAtIndexPath(readIndexPath)! cell.hidden = false } self.readView.alpha = 0.0 self.readOriginFrame = nil self.readImageViewOriginFrame = nil self.readIndexPath = nil self.topHeadViewOrigin = nil self.topHeadHeightOrigin = nil }) } @IBAction func unwindToLessonView(segue: UIStoryboardSegue){ } } extension LessonViewController: UITableViewDataSource{ func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch(section){ case 0: return 1 case 1: return lesson.lessonGallery.count default: return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0{ let contentCell = tableView.dequeueReusableCellWithIdentifier("LessonContentTableViewCell") as! LessonContentTableViewCell contentCell.contentText = lesson.detail return contentCell } if indexPath.section == 1{ if let thumbnailImageCell = tableView.dequeueReusableCellWithIdentifier("ThumbnailImageTableViewCell") as? ThumbnailImageTableViewCell { thumbnailImageCell.thumbnailImage = lesson.lessonGallery[indexPath.row].image thumbnailImageCell.title = lesson.lessonGallery[indexPath.row].title thumbnailImageCell.subtitle = lesson.lessonGallery[indexPath.row].subtitle return thumbnailImageCell } } assertionFailure("should return all possible UITableViewCells") return UITableViewCell() } } //MARK: TableView Delegate extension LessonViewController: UITableViewDelegate{ func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) if indexPath.section == 1{ readImageView.image = lesson.lessonGallery[indexPath.row].image readTextView.text = lesson.lessonGallery[indexPath.row].subtitle let cell = tableView.cellForRowAtIndexPath(indexPath) as! ThumbnailImageTableViewCell let convertedRect = cell.convertRect(cell.bounds, toView: view) let imageViewConvertedRect = cell.thumbnailImageView.convertRect(cell.thumbnailImageView.bounds, toView: cell) readOriginFrame = convertedRect readImageViewOriginFrame = imageViewConvertedRect readIndexPath = indexPath cell.hidden = true readViewTopConstraint.constant = convertedRect.origin.y readViewBottomConstraint.constant = view.bounds.height - (convertedRect.origin.y + convertedRect.height) readviewLeadingConstraint.constant = convertedRect.origin.x readViewTralingConstraint.constant = view.bounds.width - (convertedRect.origin.x + convertedRect.width) readImageViewTopConstraint.constant = imageViewConvertedRect.origin.y readImageViewHeightConstraint.constant = imageViewConvertedRect.height view.layoutIfNeeded() [readViewBottomConstraint,readviewLeadingConstraint,readViewTralingConstraint].forEach{ $0.constant = 15.0 } readViewTopConstraint.constant = 30.0 readImageViewTopConstraint.constant = 50.0 readImageViewHeightConstraint.constant = 175.0 topHeadViewOrigin = topSpace_headViewConstraint.constant topSpace_headViewConstraint.constant = -minimumTopViewHeight topHeadHeightOrigin = heightConstraint_headView.constant heightConstraint_headView.constant = minimumTopViewHeight readView.alpha = 1.0 closeButton.alpha = 1.0 setStatusBarStyle(.LightContent) UIView.animateWithDuration(0.5, animations: { self.view.layoutIfNeeded() self.dimView.alpha = 0.9 self.statusBarDimView.alpha = 0.9 self.readView.alpha = 1.0 self.readTextView.contentOffset = CGPoint.zero }, completion: {finish in self.readTextView.contentOffset = CGPoint.zero }) } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.section == 1{ let thumbnailImageCellHeight = heightForThumbnailImageCellForRow(indexPath.row) return thumbnailImageCellHeight } return lessonContentHeight } func scrollViewDidScroll(scrollView: UIScrollView) { if scrollView != tableView{ return } //println(scrollView.contentOffset.y) let currentYOffset = scrollView.contentOffset.y + tableView.contentInset.top let topViewHeight = maximumTopViewHeight - currentYOffset let newHeight = max( minimumTopViewHeight , topViewHeight) heightConstraint_headView.constant = newHeight //println("\(newHeight)") //hide topbar when scroll far than lesson content let beginYoffsetThumbnailZone = lessonContentHeight - minimumTopViewHeight if scrollView.contentOffset.y > beginYoffsetThumbnailZone{ let delta = scrollView.contentOffset.y - beginYoffsetThumbnailZone topSpace_headViewConstraint.constant = max(-minimumTopViewHeight,-delta) }else{ topSpace_headViewConstraint.constant = 0 } } func scrollViewShouldScrollToTop(scrollView: UIScrollView) -> Bool { guard scrollView === tableView else { return true } return readIndexPath === nil } }
mit
17d24b4dcacf2155bd77671c536a6f71
33.68323
174
0.734599
5.028366
false
false
false
false
jjatie/Charts
Source/Charts/Utils/Platform+Accessibility.swift
1
6087
// // Platform+Accessibility.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation #if os(iOS) || os(tvOS) import UIKit internal func accessibilityPostLayoutChangedNotification(withElement element: Any? = nil) { UIAccessibility.post(notification: .layoutChanged, argument: element) } internal func accessibilityPostScreenChangedNotification(withElement element: Any? = nil) { UIAccessibility.post(notification: .screenChanged, argument: element) } /// A simple abstraction over UIAccessibilityElement and NSAccessibilityElement. open class NSUIAccessibilityElement: UIAccessibilityElement { private weak var containerView: UIView? final var isHeader: Bool = false { didSet { accessibilityTraits = isHeader ? .header : .none } } final var isSelected: Bool = false { didSet { accessibilityTraits = isSelected ? .selected : .none } } override public init(accessibilityContainer container: Any) { // We can force unwrap since all chart views are subclasses of UIView containerView = container as? UIView super.init(accessibilityContainer: container) } override open var accessibilityFrame: CGRect { get { return super.accessibilityFrame } set { guard let containerView = containerView else { return } super.accessibilityFrame = containerView.convert(newValue, to: UIScreen.main.coordinateSpace) } } } extension NSUIView { /// An array of accessibilityElements that is used to implement UIAccessibilityContainer internally. /// Subclasses **MUST** override this with an array of such elements. @objc open func accessibilityChildren() -> [Any]? { return nil } override public final var isAccessibilityElement: Bool { get { return false } // Return false here, so we can make individual elements accessible set {} } override open func accessibilityElementCount() -> Int { return accessibilityChildren()?.count ?? 0 } override open func accessibilityElement(at index: Int) -> Any? { return accessibilityChildren()?[index] } override open func index(ofAccessibilityElement element: Any) -> Int { guard let axElement = element as? NSUIAccessibilityElement else { return NSNotFound } return (accessibilityChildren() as? [NSUIAccessibilityElement])?.firstIndex(of: axElement) ?? NSNotFound } } #endif #if os(OSX) import AppKit internal func accessibilityPostLayoutChangedNotification(withElement element: Any? = nil) { guard let validElement = element else { return } NSAccessibility.post(element: validElement, notification: .layoutChanged) } internal func accessibilityPostScreenChangedNotification(withElement _: Any? = nil) { // Placeholder } /// A simple abstraction over UIAccessibilityElement and NSAccessibilityElement. open class NSUIAccessibilityElement: NSAccessibilityElement { private weak var containerView: NSView? final var isHeader: Bool = false { didSet { setAccessibilityRole(isHeader ? .staticText : .none) } } final var isSelected: Bool = false { didSet { setAccessibilitySelected(isSelected) } } open var accessibilityLabel: String { get { return accessibilityLabel() ?? "" } set { setAccessibilityLabel(newValue) } } open var accessibilityFrame: NSRect { get { return accessibilityFrame() } set { guard let containerView = containerView else { return } let bounds = NSAccessibility.screenRect(fromView: containerView, rect: newValue) // This works, but won't auto update if the window is resized or moved. // setAccessibilityFrame(bounds) // using FrameInParentSpace allows for automatic updating of frame when windows are moved and resized. // However, there seems to be a bug right now where using it causes an offset in the frame. // This is a slightly hacky workaround that calculates the offset and removes it from frame calculation. setAccessibilityFrameInParentSpace(bounds) let axFrame = accessibilityFrame() let widthOffset = abs(axFrame.origin.x - bounds.origin.x) let heightOffset = abs(axFrame.origin.y - bounds.origin.y) let rect = NSRect(x: bounds.origin.x - widthOffset, y: bounds.origin.y - heightOffset, width: bounds.width, height: bounds.height) setAccessibilityFrameInParentSpace(rect) } } public init(accessibilityContainer container: Any) { // We can force unwrap since all chart views are subclasses of NSView containerView = (container as! NSView) super.init() setAccessibilityParent(containerView) setAccessibilityRole(.row) } } /// - Note: setAccessibilityRole(.list) is called at init. See Platform.swift. extension NSUIView: NSAccessibilityGroup { override open func accessibilityLabel() -> String? { return "Chart View" } override open func accessibilityRows() -> [Any]? { return accessibilityChildren() } } #endif
apache-2.0
724117d5c68fa3d8bd9ac293e139bc9d
33.585227
120
0.608181
5.615314
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/CryptoAssets/Sources/EthereumKit/Models/TransactionTarget/EthereumSignMessageTarget.swift
1
2253
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Foundation import MoneyKit import PlatformKit public struct EthereumSignMessageTarget: WalletConnectTarget { public enum Message { /// The Data message to be signed. /// Used for `eth_sign` and `personal_sign` WalletConnect methods. case data(Data) /// The String typed data message to be signed. /// Used for `eth_signTypedData` WalletConnect method. case typedData(String) } // MARK: - Public Properties public let account: String public let dAppAddress: String public let dAppLogoURL: String public let dAppName: String public let message: Message public let network: EVMNetwork public let onTransactionRejected: () -> AnyPublisher<Void, Never> public let onTxCompleted: TxCompleted public var currencyType: CurrencyType { network.cryptoCurrency.currencyType } public var label: String { dAppName } var readableMessage: String { switch message { case .typedData(let typedDataJson): let data = Data(typedDataJson.utf8) let decoded = try? JSONDecoder().decode( TypedDataPayload.self, from: data ) return decoded .flatMap { typedDataPayload in typedDataPayload.message.description } ?? typedDataJson case .data(let data): return String(data: data, encoding: .utf8) ?? data.hexString.withHex } } public init( account: String, dAppAddress: String, dAppLogoURL: String, dAppName: String, message: Message, network: EVMNetwork, onTransactionRejected: @escaping () -> AnyPublisher<Void, Never>, onTxCompleted: @escaping TxCompleted ) { self.account = account self.dAppAddress = dAppAddress self.dAppLogoURL = dAppLogoURL self.dAppName = dAppName self.message = message self.network = network self.onTransactionRejected = onTransactionRejected self.onTxCompleted = onTxCompleted } }
lgpl-3.0
5a0e30c8176f8a21cb46a3077d563e73
28.246753
74
0.619893
4.82227
false
false
false
false
zs40x/PairProgrammingTimer
PairProgrammingTimer/Logic/SessionDelegateLogDecorator.swift
1
2082
// // SessionDelegateLogDecorator.swift // PairProgrammingTimer // // Created by Stefan Mehnert on 11.04.17. // Copyright © 2017 Stefan Mehnert. All rights reserved. // import Foundation class SessionDelegateLogDecorator { fileprivate let other: SessionDelegate fileprivate let log: SessionLog fileprivate let developerNameService: DeveloperNameService init(other: SessionDelegate, log: SessionLog, developerNameService: DeveloperNameService) { self.other = other self.log = log self.developerNameService = developerNameService } } extension SessionDelegateLogDecorator: SessionDelegate { func developerChanged(developer: Developer) { log.sessionEnded( developerName: developerNameService.nameOf(developer: otherDeveloper(developer)), otherDeveloperName: developerNameService.nameOf(developer:developer)) other.developerChanged(developer: developer) } func sessionStarted(sessionEndsOn: Date, forDeveloper: Developer, restored: Bool, duration: SessionDuration) { if !restored { log.sessionStarted( developerName: developerNameService.nameOf(developer: forDeveloper), otherDeveloperName: developerNameService.nameOf(developer:otherDeveloper(forDeveloper)), duration: duration) } other.sessionStarted(sessionEndsOn: sessionEndsOn, forDeveloper: forDeveloper, restored: restored, duration: duration) } func sessionEnded(forDeveloper: Developer) { log.sessionEnded( developerName: developerNameService.nameOf(developer: forDeveloper), otherDeveloperName: developerNameService.nameOf(developer:otherDeveloper(forDeveloper))) other.sessionEnded(forDeveloper: forDeveloper) } func countdownExpired() { other.countdownExpired() } private func otherDeveloper(_ developer: Developer) -> Developer { return developer == .left ? .right : .left } }
mit
c72b272f0fa0bc768513539045b27435
32.031746
126
0.690053
4.954762
false
false
false
false
daaavid/TIY-Assignments
18--Mutt-Cutts/MuttCutts/MuttCutts/PopoverViewController.swift
1
2620
// // PopoverViewController.swift // MuttCutts // // Created by david on 10/28/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit class PopoverViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var firstLocationTextField: UITextField! @IBOutlet weak var secondLocationTextField: UITextField! var delegate: PopoverViewControllerDelegate? var locationArr = [String]() override func viewDidLoad() { super.viewDidLoad() if firstLocationTextField.text! == "" { firstLocationTextField.becomeFirstResponder() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func searchButton(sender: UIButton) { search() } func textFieldShouldReturn(textField: UITextField) -> Bool { var rc = false if textField.text?.componentsSeparatedByString(",").count == 2 { switch textField { case firstLocationTextField: secondLocationTextField.becomeFirstResponder() default: secondLocationTextField.resignFirstResponder() rc = true search() } } else { switch textField { case firstLocationTextField: firstLocationTextField.placeholder = "Enter a valid City, State" default: secondLocationTextField.placeholder = "Enter a valid City, State" } } return rc } func search() { if firstLocationTextField.text != nil && secondLocationTextField.text != nil { let firstLocation = firstLocationTextField.text! let secondLocation = secondLocationTextField.text! locationArr.append(firstLocation); locationArr.append(secondLocation) UIApplication.sharedApplication().networkActivityIndicatorVisible = true delegate?.search(firstLocation, secondLocation: secondLocation) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
cc0-1.0
2d2dde5f84092427822357bd39213313
27.16129
106
0.611684
5.872197
false
false
false
false
Jakobeha/lAzR4t
lAzR4t Shared/Code/Play/TurretElemController.swift
1
1568
// // TurretElemController.swift // lAzR4t // // Created by Jakob Hain on 9/30/17. // Copyright © 2017 Jakob Hain. All rights reserved. // import Foundation class TurretElemController: PlayElemController_impl<TurretElem> { override var curModel: TurretElem { didSet { node_spe.reconfigure( healthRatio: curModel.healthRatio, color: curModel.color, direction: curModel.direction, isPlaceholder: curModel.isPlaceholder, pos: curModel.pos ) } } let node_spe: TurretElemNode var color: AttackColor { get { return curModel.color } set(newColor) { curModel = curModel.set(color: newColor) } } var direction: CellDirection { get { return self.curModel.direction } set(newDirection) { curModel = curModel.set(direction: newDirection) } } var isPlaceholder: Bool { get { return curModel.isPlaceholder } set(newIsPlaceholder) { curModel = curModel.set(isPlaceholder: newIsPlaceholder) } } var pos: CellPos { get { return curModel.pos } set(newPos) { curModel = curModel.set(pos: newPos) } } init(curModel: TurretElem) { node_spe = TurretElemNode( healthRatio: curModel.healthRatio, color: curModel.color, direction: curModel.direction, isPlaceholder: curModel.isPlaceholder, pos: curModel.pos ) super.init(curModel: curModel, node: node_spe) } }
mit
034b43424032ac43164ddf38bc5e1d1c
29.72549
90
0.605616
4.102094
false
false
false
false
apple/swift
test/SILGen/guaranteed_normal_args.swift
1
8063
// RUN: %target-swift-emit-silgen -parse-as-library -module-name Swift -parse-stdlib %s | %FileCheck %s // This test checks specific codegen related to normal arguments being passed at // +0. Eventually, it should be merged into normal SILGen tests. ///////////////// // Fake Stdlib // ///////////////// precedencegroup AssignmentPrecedence { assignment: true } public protocol ExpressibleByNilLiteral { init(nilLiteral: ()) } protocol IteratorProtocol { associatedtype Element mutating func next() -> Element? } protocol Sequence { associatedtype Element associatedtype Iterator : IteratorProtocol where Iterator.Element == Element func makeIterator() -> Iterator } enum Optional<T> { case none case some(T) } extension Optional : ExpressibleByNilLiteral { public init(nilLiteral: ()) { self = .none } } func _diagnoseUnexpectedNilOptional(_filenameStart: Builtin.RawPointer, _filenameLength: Builtin.Word, _filenameIsASCII: Builtin.Int1, _line: Builtin.Word) { // This would usually contain an assert, but we don't need one since we are // just emitting SILGen. } class Klass { init() {} } struct Buffer { var k: Klass init(inK: Klass) { k = inK } } public typealias AnyObject = Builtin.AnyObject protocol Protocol { associatedtype AssocType static func useInput(_ input: Builtin.Int32, into processInput: (AssocType) -> ()) } struct FakeArray<Element> { // Just to make this type non-trivial var k: Klass // We are only interested in this being called. We are not interested in its // implementation. mutating func append(_ t: Element) {} } struct FakeDictionary<Key, Value> { } struct FakeDictionaryIterator<Key, Value> { var dictionary: FakeDictionary<Key, Value>? init(_ newDictionary: FakeDictionary<Key, Value>) { dictionary = newDictionary } } extension FakeDictionaryIterator : IteratorProtocol { public typealias Element = (Key, Value) public mutating func next() -> Element? { return .none } } extension FakeDictionary : Sequence { public typealias Element = (Key, Value) public typealias Iterator = FakeDictionaryIterator<Key, Value> public func makeIterator() -> FakeDictionaryIterator<Key, Value> { return FakeDictionaryIterator(self) } } public struct Unmanaged<Instance : AnyObject> { internal unowned(unsafe) var _value: Instance } /////////// // Tests // /////////// class KlassWithBuffer { var buffer: Buffer // Make sure that the allocating init forwards into the initializing init at +1. // CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$ss15KlassWithBufferC3inKABs0A0C_tcfC : $@convention(method) (@owned Klass, @thick KlassWithBuffer.Type) -> @owned KlassWithBuffer { // CHECK: bb0([[ARG:%.*]] : @owned $Klass, // CHECK: [[INITIALIZING_INIT:%.*]] = function_ref @$ss15KlassWithBufferC3inKABs0A0C_tcfc : $@convention(method) (@owned Klass, @owned KlassWithBuffer) -> @owned KlassWithBuffer // CHECK: apply [[INITIALIZING_INIT]]([[ARG]], // CHECK: } // end sil function '$ss15KlassWithBufferC3inKABs0A0C_tcfC' init(inK: Klass = Klass()) { buffer = Buffer(inK: inK) } // This test makes sure that we: // // 1. Are able to propagate a +0 value buffer.k into a +0 value and that // we then copy that +0 value into a +1 value, before we begin the epilog and // then return that value. // CHECK-LABEL: sil hidden [ossa] @$ss15KlassWithBufferC03getC14AsNativeObjectBoyF : $@convention(method) (@guaranteed KlassWithBuffer) -> @owned Builtin.NativeObject { // CHECK: bb0([[SELF:%.*]] : @guaranteed $KlassWithBuffer): // CHECK: [[METHOD:%.*]] = class_method [[SELF]] : $KlassWithBuffer, #KlassWithBuffer.buffer!getter // CHECK: [[BUF:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK: [[BUF_BORROW:%.*]] = begin_borrow [[BUF]] // CHECK: [[K:%.*]] = struct_extract [[BUF_BORROW]] : $Buffer, #Buffer.k // CHECK: [[COPIED_K:%.*]] = copy_value [[K]] // CHECK: end_borrow [[BUF_BORROW]] // CHECK: [[CASTED_COPIED_K:%.*]] = unchecked_ref_cast [[COPIED_K]] // CHECK: destroy_value [[BUF]] // CHECK: return [[CASTED_COPIED_K]] // CHECK: } // end sil function '$ss15KlassWithBufferC03getC14AsNativeObjectBoyF' func getBufferAsNativeObject() -> Builtin.NativeObject { return Builtin.unsafeCastToNativeObject(buffer.k) } } struct StructContainingBridgeObject { var rawValue: Builtin.BridgeObject // CHECK-LABEL: sil hidden [ossa] @$ss28StructContainingBridgeObjectV8swiftObjAByXl_tcfC : $@convention(method) (@owned AnyObject, @thin StructContainingBridgeObject.Type) -> @owned StructContainingBridgeObject { // CHECK: bb0([[ARG:%.*]] : @owned $AnyObject, // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [lexical] [[ARG]] // CHECK: [[COPIED_ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[CASTED_ARG:%.*]] = unchecked_ref_cast [[COPIED_ARG]] : $AnyObject to $Builtin.BridgeObject // CHECK: assign [[CASTED_ARG]] to // CHECK: } // end sil function '$ss28StructContainingBridgeObjectV8swiftObjAByXl_tcfC' init(swiftObj: AnyObject) { rawValue = Builtin.reinterpretCast(swiftObj) } } struct ReabstractionThunkTest : Protocol { typealias AssocType = Builtin.Int32 static func useInput(_ input: Builtin.Int32, into processInput: (AssocType) -> ()) { processInput(input) } } // Make sure that we provide a cleanup to x properly before we pass it to // result. extension FakeDictionary { // CHECK-LABEL: sil hidden [ossa] @$ss14FakeDictionaryV20makeSureToCopyTuplesyyF : $@convention(method) <Key, Value> (FakeDictionary<Key, Value>) -> () { // CHECK: [[X:%.*]] = alloc_stack [lexical] $(Key, Value), let, name "x" // CHECK: [[INDUCTION_VAR:%.*]] = unchecked_take_enum_data_addr {{%.*}} : $*Optional<(Key, Value)>, #Optional.some!enumelt // CHECK: [[INDUCTION_VAR_0:%.*]] = tuple_element_addr [[INDUCTION_VAR]] : $*(Key, Value), 0 // CHECK: [[INDUCTION_VAR_1:%.*]] = tuple_element_addr [[INDUCTION_VAR]] : $*(Key, Value), 1 // CHECK: [[X_0:%.*]] = tuple_element_addr [[X]] : $*(Key, Value), 0 // CHECK: [[X_1:%.*]] = tuple_element_addr [[X]] : $*(Key, Value), 1 // CHECK: copy_addr [take] [[INDUCTION_VAR_0]] to [init] [[X_0]] // CHECK: copy_addr [take] [[INDUCTION_VAR_1]] to [init] [[X_1]] // CHECK: [[X_0:%.*]] = tuple_element_addr [[X]] : $*(Key, Value), 0 // CHECK: [[X_1:%.*]] = tuple_element_addr [[X]] : $*(Key, Value), 1 // CHECK: [[TMP_X:%.*]] = alloc_stack $(Key, Value) // CHECK: [[TMP_X_0:%.*]] = tuple_element_addr [[TMP_X]] : $*(Key, Value), 0 // CHECK: [[TMP_X_1:%.*]] = tuple_element_addr [[TMP_X]] : $*(Key, Value), 1 // CHECK: [[TMP_0:%.*]] = alloc_stack $Key // CHECK: copy_addr [[X_0]] to [init] [[TMP_0]] // CHECK: copy_addr [take] [[TMP_0]] to [init] [[TMP_X_0]] // CHECK: [[TMP_1:%.*]] = alloc_stack $Value // CHECK: copy_addr [[X_1]] to [init] [[TMP_1]] // CHECK: copy_addr [take] [[TMP_1]] to [init] [[TMP_X_1]] // CHECK: [[FUNC:%.*]] = function_ref @$ss9FakeArrayV6appendyyxF : $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @inout FakeArray<τ_0_0>) -> () // CHECK: apply [[FUNC]]<(Key, Value)>([[TMP_X]], // CHECK: } // end sil function '$ss14FakeDictionaryV20makeSureToCopyTuplesyyF' func makeSureToCopyTuples() { var result = FakeArray<Element>(k: Klass()) for x in self { result.append(x) } } } // Make sure that we properly forward x into memory and don't crash. public func forwardIntoMemory(fromNative x: AnyObject, y: Builtin.Word) -> Builtin.BridgeObject { // y would normally be 0._builtinWordValue. We don't want to define that // conformance. let object = Builtin.castToBridgeObject(x, y) return object } public struct StructWithOptionalAddressOnlyField<T> { public let newValue: T? } func useStructWithOptionalAddressOnlyField<T>(t: T) -> StructWithOptionalAddressOnlyField<T> { return StructWithOptionalAddressOnlyField<T>(newValue: t) }
apache-2.0
c847c87bc3597851890d5820ff78db4d
36.142857
214
0.653598
3.697248
false
false
false
false
felipedemetrius/AppSwift3
AppSwift3/ActionsTaskDetailTableViewCell.swift
1
2936
// // ActionsTaskDetailTableViewCell.swift // AppSwift3 // // Created by Felipe Silva on 2/15/17. // Copyright © 2017 Felipe Silva . All rights reserved. // import UIKit /// Cell with the action buttons for phone call, services, address, comments and favorites. class ActionsTaskDetailTableViewCell: UITableViewCell { /// ViewModel for this ViewCell var viewModel: ActionsTaskDetailDelegate? override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func call(_ sender: UIButton) { guard let tableView = self.superview?.superview as? UITableView else {return} guard let viewController = tableView.superview?.parentViewController as? TaskDetailViewController else {return} guard let task = viewController.viewModel?.task.value else {return} guard let numberPhone = task.phone else {return} viewModel?.callPhone(number: numberPhone) } @IBAction func service(_ sender: UIButton) { guard let tableView = self.superview?.superview as? UITableView else {return} guard let viewController = tableView.superview?.parentViewController as? TaskDetailViewController else {return} viewModel?.goToServiceView(actualViewController: viewController, withIdentifier: "goToServices") } @IBAction func address(_ sender: UIButton) { guard let tableView = self.superview?.superview as? UITableView else {return} guard let viewController = tableView.superview?.parentViewController as? TaskDetailViewController else {return} let task = viewController.viewModel?.task.value viewModel?.showAddress(vc: viewController, title: "Endereço", message: task?.address ?? "Inexistente", style: .alert) } @IBAction func comments(_ sender: UIButton) { guard let tableView = self.superview?.superview as? UITableView else {return} guard let viewController = tableView.superview?.parentViewController as? TaskDetailViewController else {return} guard let task = viewController.viewModel?.task.value else {return} viewModel?.shouldScrollTableView(tableView: tableView, task: task) } @IBAction func favorite(_ sender: UIButton) { guard let tableView = self.superview?.superview as? UITableView else {return} guard let viewController = tableView.superview?.parentViewController as? TaskDetailViewController else {return} guard let task = viewController.viewModel?.task.value else {return} viewModel?.favoriteTask(task: task) } }
mit
9f0cd0e0afff39a0409c519786b97147
34.349398
125
0.671779
5.344262
false
false
false
false
Onetaway/iOS8-day-by-day
08-today-extension/GitHubToday/GitHubTodayCommon/GitHubDataProvider.swift
3
5752
// // Copyright 2014 Scott Logic // // 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 @objc public class GitHubEvent: NSObject, Printable, Equatable, NSCoding { public var id: Int public var eventType: GitHubEventType public var repoName: String? public var time: NSDate? private class var dateFormatter : NSDateFormatter { struct Static { static let instance : NSDateFormatter = NSDateFormatter() } return Static.instance } public init(id: Int, eventType: GitHubEventType, repoName: String?, time: NSDate?) { self.id = id self.eventType = eventType self.repoName = repoName self.time = time } // NSCoding public required init(coder aDecoder: NSCoder) { self.id = aDecoder.decodeIntegerForKey("id") self.eventType = GitHubEventType.fromRaw(aDecoder.decodeObjectForKey("eventType") as String)! self.repoName = aDecoder.decodeObjectForKey("repoName") as? String self.time = aDecoder.decodeObjectForKey("time") as? NSDate } public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeInteger(id, forKey: "id") aCoder.encodeObject(eventType.toRaw(), forKey: "eventType") aCoder.encodeObject(repoName!, forKey: "repoName") aCoder.encodeObject(time!, forKey: "time") } public convenience init(json: JSONValue) { let data = GitHubEvent.extractDataFromJson(json) self.init(id: data.id, eventType: data.eventType, repoName: data.repoName, time: data.time) } public class func extractDataFromJson(jsonEvent: JSONValue) -> (id: Int, eventType: GitHubEventType, repoName: String?, time: NSDate?) { let id = jsonEvent["id"].integer! var repoName: String? = nil if let repo = jsonEvent["repo"].object { repoName = repo["name"]?.string } var eventType: GitHubEventType = .Other if let eventString = jsonEvent["type"].string { switch eventString { case "CreateEvent": eventType = .Create case "DeleteEvent": eventType = .Delete case "ForkEvent": eventType = .Fork case "PushEvent": eventType = .Push case "WatchEvent": eventType = .Watch case "FollowEvent": eventType = .Follow case "IssuesEvent": eventType = .Issues case "IssueCommentEvent": eventType = .IssueComment default: eventType = .Other } } var date: NSDate? if let createdString = jsonEvent["created_at"].string { GitHubEvent.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" date = GitHubEvent.dateFormatter.dateFromString(createdString) } return (id, eventType, repoName, date) } // Printable override public var description: String { return "[\(id)] \(time) : \(eventType.toRaw()) \(repoName)" } } // Equatable public func ==(lhs: GitHubEvent, rhs: GitHubEvent) -> Bool { return lhs.id == rhs.id } public enum GitHubEventType: String { case Create = "create" case Delete = "delete" case Fork = "fork" case Push = "push" case Watch = "watch" case Follow = "follow" case Issues = "issues" case IssueComment = "comment" case Other = "other" public var icon: String { switch self { case .Create: return "" case .Delete: return "" case .Follow: return "" case .Fork: return "" case .IssueComment: return "" case .Issues: return "" case .Other: return "" case .Push: return "" case .Watch: return "" default: return "" } } } public class GitHubDataProvider { public init() { } public func getEvents(user: String, callback: ([GitHubEvent])->()) { let url = NSURL(string: "https://api.github.com/users/\(user)/events") let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in if (error != nil) { println("Error: \(error.localizedDescription)") return } let events = self.convertJSONToEvents(JSONValue(data)) callback(events) }) task.resume() } private func convertJSONToEvents(data: JSONValue) -> [GitHubEvent] { let json = data.array var ghEvents = [GitHubEvent]() if let events = json { for event in events { let ghEvent = GitHubEvent(json: event) ghEvents.append(ghEvent) } } return ghEvents } } let mostRecentEventCacheKey = "GitHubToday.mostRecentEvent" public class GitHubEventCache { private var userDefaults: NSUserDefaults public init(userDefaults: NSUserDefaults) { self.userDefaults = userDefaults } public var mostRecentEvent: GitHubEvent? { get { if let data = userDefaults.objectForKey(mostRecentEventCacheKey) as? NSData { if let event = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? GitHubEvent { return event } } return nil } set(newEvent) { if let event = newEvent { let data = NSKeyedArchiver.archivedDataWithRootObject(event) userDefaults.setObject(data, forKey: mostRecentEventCacheKey) } else { userDefaults.removeObjectForKey(mostRecentEventCacheKey) } } } }
apache-2.0
6eb6a8e30f959f79b11ea0605c6c24cc
26.440191
138
0.657133
4.222386
false
false
false
false
erichoracek/Carthage
Source/CarthageKit/Cartfile.swift
2
8904
// // Cartfile.swift // Carthage // // Created by Justin Spahr-Summers on 2014-10-10. // Copyright (c) 2014 Carthage. All rights reserved. // import Foundation import Result import ReactiveCocoa /// The relative path to a project's checked out dependencies. public let CarthageProjectCheckoutsPath = "Carthage/Checkouts" /// Represents a Cartfile, which is a specification of a project's dependencies /// and any other settings Carthage needs to build it. public struct Cartfile { /// The dependencies listed in the Cartfile. public var dependencies: [Dependency<VersionSpecifier>] public init(dependencies: [Dependency<VersionSpecifier>] = []) { self.dependencies = dependencies } /// Returns the location where Cartfile should exist within the given /// directory. public static func URLInDirectory(directoryURL: NSURL) -> NSURL { return directoryURL.URLByAppendingPathComponent("Cartfile") } /// Attempts to parse Cartfile information from a string. public static func fromString(string: String) -> Result<Cartfile, CarthageError> { var cartfile = self() var result: Result<(), CarthageError> = .success(()) let commentIndicator = "#" (string as NSString).enumerateLinesUsingBlock { (line, stop) in let scanner = NSScanner(string: line) if scanner.scanString(commentIndicator, intoString: nil) { // Skip the rest of the line. return } if scanner.atEnd { // The line was all whitespace. return } switch (Dependency<VersionSpecifier>.fromScanner(scanner)) { case let .Success(dep): cartfile.dependencies.append(dep.value) case let .Failure(error): result = .failure(error.value) stop.memory = true } if scanner.scanString(commentIndicator, intoString: nil) { // Skip the rest of the line. return } if !scanner.atEnd { result = .failure(CarthageError.ParseError(description: "unexpected trailing characters in line: \(line)")) stop.memory = true } } return result.map { _ in cartfile } } /// Attempts to parse a Cartfile from a file at a given URL. public static func fromFile(cartfileURL: NSURL) -> Result<Cartfile, CarthageError> { var error: NSError? if let cartfileContents = NSString(contentsOfURL: cartfileURL, encoding: NSUTF8StringEncoding, error: &error) { return Cartfile.fromString(cartfileContents as String) } else { return .failure(CarthageError.ReadFailed(cartfileURL, error)) } } /// Appends the contents of another Cartfile to that of the receiver. public mutating func appendCartfile(cartfile: Cartfile) { dependencies += cartfile.dependencies } } extension Cartfile: Printable { public var description: String { return "\(dependencies)" } } // Duplicate dependencies extension Cartfile { /// Returns an array containing projects that are listed as duplicate /// dependencies. public func duplicateProjects() -> [ProjectIdentifier] { return filter(self.dependencyCountedSet) { $0.1 > 1} .map { $0.0 } } /// Returns the dependencies in a cartfile as a counted set containing the /// corresponding projects, represented as a dictionary. private var dependencyCountedSet: [ProjectIdentifier: Int] { return buildCountedSet(self.dependencies.map { $0.project }) } } /// Returns an array containing projects that are listed as dependencies /// in both arguments. public func duplicateProjectsInCartfiles(cartfile1: Cartfile, cartfile2: Cartfile) -> [ProjectIdentifier] { let projectSet1 = cartfile1.dependencyCountedSet return cartfile2.dependencies .map { $0.project } .filter { projectSet1[$0] != nil } } /// Represents a parsed Cartfile.resolved, which specifies which exact version was /// checked out for each dependency. public struct ResolvedCartfile { /// The dependencies listed in the Cartfile.resolved, in the order that they /// should be built. public var dependencies: [Dependency<PinnedVersion>] public init(dependencies: [Dependency<PinnedVersion>]) { self.dependencies = dependencies } /// Returns the location where Cartfile.resolved should exist within the given /// directory. public static func URLInDirectory(directoryURL: NSURL) -> NSURL { return directoryURL.URLByAppendingPathComponent("Cartfile.resolved") } /// Attempts to parse Cartfile.resolved information from a string. public static func fromString(string: String) -> Result<ResolvedCartfile, CarthageError> { var cartfile = self(dependencies: []) var result: Result<(), CarthageError> = .success(()) let scanner = NSScanner(string: string) scannerLoop: while !scanner.atEnd { switch (Dependency<PinnedVersion>.fromScanner(scanner)) { case let .Success(dep): cartfile.dependencies.append(dep.value) case let .Failure(error): result = .failure(error.value) break scannerLoop } } return result.map { _ in cartfile } } } extension ResolvedCartfile: Printable { public var description: String { return dependencies.reduce("") { (string, dependency) in return string + "\(dependency)\n" } } } /// Uniquely identifies a project that can be used as a dependency. public enum ProjectIdentifier: Equatable { /// A repository hosted on GitHub.com. case GitHub(GitHubRepository) /// An arbitrary Git repository. case Git(GitURL) /// The unique, user-visible name for this project. public var name: String { switch (self) { case let .GitHub(repo): return repo.name case let .Git(URL): return URL.name ?? URL.URLString } } /// The path at which this project will be checked out, relative to the /// working directory of the main project. public var relativePath: String { return CarthageProjectCheckoutsPath.stringByAppendingPathComponent(name) } } public func ==(lhs: ProjectIdentifier, rhs: ProjectIdentifier) -> Bool { switch (lhs, rhs) { case let (.GitHub(left), .GitHub(right)): return left == right case let (.Git(left), .Git(right)): return left == right default: return false } } extension ProjectIdentifier: Hashable { public var hashValue: Int { switch (self) { case let .GitHub(repo): return repo.hashValue case let .Git(URL): return URL.hashValue } } } extension ProjectIdentifier: Scannable { /// Attempts to parse a ProjectIdentifier. public static func fromScanner(scanner: NSScanner) -> Result<ProjectIdentifier, CarthageError> { var parser: (String -> Result<ProjectIdentifier, CarthageError>)! if scanner.scanString("github", intoString: nil) { parser = { repoNWO in return GitHubRepository.fromNWO(repoNWO).map { self.GitHub($0) } } } else if scanner.scanString("git", intoString: nil) { parser = { URLString in return .success(self.Git(GitURL(URLString))) } } else { return .failure(CarthageError.ParseError(description: "unexpected dependency type in line: \(scanner.currentLine)")) } if !scanner.scanString("\"", intoString: nil) { return .failure(CarthageError.ParseError(description: "expected string after dependency type in line: \(scanner.currentLine)")) } var address: NSString? = nil if !scanner.scanUpToString("\"", intoString: &address) || !scanner.scanString("\"", intoString: nil) { return .failure(CarthageError.ParseError(description: "empty or unterminated string after dependency type in line: \(scanner.currentLine)")) } if let address = address { return parser(address as String) } else { return .failure(CarthageError.ParseError(description: "empty string after dependency type in line: \(scanner.currentLine)")) } } } extension ProjectIdentifier: Printable { public var description: String { switch (self) { case let .GitHub(repo): return "github \"\(repo)\"" case let .Git(URL): return "git \"\(URL)\"" } } } /// Represents a single dependency of a project. public struct Dependency<V: VersionType>: Equatable { /// The project corresponding to this dependency. public let project: ProjectIdentifier /// The version(s) that are required to satisfy this dependency. public var version: V public init(project: ProjectIdentifier, version: V) { self.project = project self.version = version } /// Maps over the `version` in the receiver. public func map<W: VersionType>(f: V -> W) -> Dependency<W> { return Dependency<W>(project: project, version: f(version)) } } public func ==<V>(lhs: Dependency<V>, rhs: Dependency<V>) -> Bool { return lhs.project == rhs.project && lhs.version == rhs.version } extension Dependency: Scannable { /// Attempts to parse a Dependency specification. public static func fromScanner(scanner: NSScanner) -> Result<Dependency, CarthageError> { return ProjectIdentifier.fromScanner(scanner).flatMap { identifier in return V.fromScanner(scanner).map { specifier in self(project: identifier, version: specifier) } } } } extension Dependency: Printable { public var description: String { return "\(project) \(version)" } }
mit
f2744f3ac0bc4c15afc2be6bd0c088ab
28.68
143
0.722484
3.927658
false
false
false
false
igroomgrim/StubNBDDTest
StubNBDDTest/Model/Post.swift
1
502
// // Post.swift // StubNBDDTest // // Created by Anak Mirasing on 2/5/16. // Copyright © 2016 iGROOMGRiM. All rights reserved. // import Foundation import SwiftyJSON class Post { var userId: Int? var id: Int? var title: String? var body: String? init(json: AnyObject) { let data = JSON(json) self.userId = data["userId"].int self.id = data["id"].int self.title = data["title"].string self.body = data["body"].string } }
mit
308cd0b16a65b6df33db630eb9657249
18.269231
53
0.582834
3.408163
false
false
false
false
jefflovejapan/CIFilterKit
CIFilterKit/TileEffectFilters.swift
1
6500
// // TileEffectFilters.swift // CIFilterKit // // Created by Jeffrey Blagdon on 6/3/15. // Copyright (c) 2015 Jeffrey Blagdon. All rights reserved. // import Foundation /** - parameter inputTransform: The `CGAffineTransform` to apply - returns: A closure of type `Filter` */ public func AffineClamp(inputTransform: CGAffineTransform) -> Filter { return { image in let parameters = [ kCIInputImageKey: image, kCIInputTransformKey: inputTransform.value() ] let aFilter = CIFilter(name: FilterName.AffineClamp.rawValue, withInputParameters: parameters) return aFilter?.outputImage } } /** - parameter inputTransform: The `CGAffineTransform` to apply - returns: A closure of type `Filter` */ public func AffineTile(inputTransform: CGAffineTransform) -> Filter { return { image in let parameters = [ kCIInputImageKey: image, kCIInputTransformKey: inputTransform.value() ] let aFilter = CIFilter(name: FilterName.AffineTile.rawValue, withInputParameters: parameters) return aFilter?.outputImage } } /** - parameter options: An instance of `TileOptions` - returns: A closure of type `Filter` */ public func EightfoldReflectedTile(options: TileOptions) -> Filter { return { image in let parameters = [ kCIInputImageKey: image, kCIInputCenterKey: options.inputCenter.vector(), kCIInputAngleKey: options.inputAngle, kCIInputWidthKey: options.inputWidth ] let aFilter = CIFilter(name: FilterName.EightfoldReflectedTile.rawValue, withInputParameters: parameters) return aFilter?.outputImage } } /** - parameter options: An instance of `TileOptionsWithAcuteAngle` - returns: A closure of type `Filter` */ public func FourfoldReflectedTile(options: TileOptionsWithAcuteAngle) -> Filter { return { image in let parameters = [ kCIInputImageKey: image, kCIInputCenterKey: options.inputCenter.vector(), kCIInputAngleKey: options.inputAngle, "inputAcuteAngle": options.inputAcuteAngle, kCIInputWidthKey: options.inputWidth ] let aFilter = CIFilter(name: FilterName.FourfoldReflectedTile.rawValue, withInputParameters: parameters) return aFilter?.outputImage } } /** - parameter options: An instance of `TileOptions` - returns: A closure of type `Filter` */ public func FourfoldRotatedTile(options: TileOptions) -> Filter { return { image in let parameters = [ kCIInputImageKey: image, kCIInputCenterKey: options.inputCenter.vector(), kCIInputAngleKey: options.inputAngle, kCIInputWidthKey: options.inputWidth ] let aFilter = CIFilter(name: FilterName.FourfoldRotatedTile.rawValue, withInputParameters: parameters) return aFilter?.outputImage } } /** - parameter options: An instance of `TileOptionsWithAcuteAngle` - returns: A closure of type `Filter` */ public func FourfoldTranslatedTile(options: TileOptionsWithAcuteAngle) -> Filter { return { image in let parameters = [ kCIInputImageKey: image, kCIInputCenterKey: options.inputCenter.vector(), kCIInputAngleKey: options.inputAngle, "inputAcuteAngle": options.inputAcuteAngle, kCIInputWidthKey: options.inputWidth ] let aFilter = CIFilter(name: FilterName.FourfoldTranslatedTile.rawValue, withInputParameters: parameters) return aFilter?.outputImage } } /** - parameter options: An instance of `TileOptions` - returns: A closure of type `Filter` */ public func GlideReflectedTile(options: TileOptions) -> Filter { return { image in let parameters = [ kCIInputImageKey: image, kCIInputCenterKey: options.inputCenter.vector(), kCIInputAngleKey: options.inputAngle, kCIInputWidthKey: options.inputWidth ] let aFilter = CIFilter(name: FilterName.GlideReflectedTile.rawValue, withInputParameters: parameters) return aFilter?.outputImage } } /** - parameter options: An instance of `TileOptions` - returns: A closure of type `Filter` */ public func SixfoldReflectedTile(options: TileOptions) -> Filter { return { image in let parameters = [ kCIInputImageKey: image, kCIInputCenterKey: options.inputCenter.vector(), kCIInputAngleKey: options.inputAngle, kCIInputWidthKey: options.inputWidth ] let aFilter = CIFilter(name: FilterName.SixfoldReflectedTile.rawValue, withInputParameters: parameters) return aFilter?.outputImage } } /** - parameter options: An instance of `TileOptions` - returns: A closure of type `Filter` */ public func SixfoldRotatedTile(options: TileOptions) -> Filter { return { image in let parameters = [ kCIInputImageKey: image, kCIInputCenterKey: options.inputCenter.vector(), kCIInputAngleKey: options.inputAngle, kCIInputWidthKey: options.inputWidth ] let aFilter = CIFilter(name: FilterName.SixfoldRotatedTile.rawValue, withInputParameters: parameters) return aFilter?.outputImage } } /** - parameter options: An instance of `TriangleKaleidoscopeOptions` - returns: A closure of type `Filter` */ public func TriangleKaleidoscope(options: TriangleKaleidoscopeOptions) -> Filter { return { image in let parameters = [ kCIInputImageKey: image, "inputSize": options.inputSize, "inputRotation": options.inputRotation, "inputDecay": options.inputDecay ] let aFilter = CIFilter(name: FilterName.TriangleKaleidoscope.rawValue, withInputParameters: parameters) return aFilter?.outputImage } } /** - parameter options: An instance of `TileOptions` - returns: A closure of type `Filter` */ public func TwelvefoldReflectedTile(options: TileOptions) -> Filter { return { image in let parameters = [ kCIInputImageKey: image, kCIInputCenterKey: options.inputCenter.vector(), kCIInputAngleKey: options.inputAngle, kCIInputWidthKey: options.inputWidth ] let aFilter = CIFilter(name: FilterName.TwelvefoldReflectedTile.rawValue, withInputParameters: parameters) return aFilter?.outputImage } }
mit
c576e7a31990923314d9526bb13f9358
30.867647
114
0.676923
4.662841
false
false
false
false
sanche21/AppClips
AppClips/ViewController.swift
1
1218
// // ViewController.swift // AppClips // // Created by Daniel Sanche on 2015-02-15. // Copyright (c) 2015 Daniel Sanche. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! var generator : AppClips?; var icon = UIImage(named: "clip-icon") override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.imageView.image = icon } func completedInstall(){ generator?.stopServer() generator = nil let alert = UIAlertController(title: "Welcome Back", message: "You should now see a new icon on your home screen", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } @IBAction func brnPressed(sender: AnyObject) { generator = AppClips(clipURL: "appcliplaunch://", name:"Launcher", returnURL: "appclipreturn://", identifier:"com.example.appclip", icon:self.icon) generator!.startServer() } }
mit
fc71fe8a16720ef0dcb5d4b5f22d14f8
27.348837
168
0.647783
4.527881
false
false
false
false
Moya/Moya
Tests/MoyaTests/Observable+MoyaSpec.swift
2
26664
import Quick import Moya import RxSwift import Nimble import Foundation final class ObservableMoyaSpec: QuickSpec { override func spec() { describe("status codes filtering") { it("filters out unrequested status codes closed range upperbound") { let data = Data() let observable = Response(statusCode: 10, data: data).asObservable() var errored = false _ = observable.filter(statusCodes: 0...9).subscribe { event in switch event { case .next(let object): fail("called on non-correct status code: \(object)") case .error: errored = true default: break } } expect(errored).to(beTruthy()) } it("filters out unrequested status codes closed range lowerbound") { let data = Data() let observable = Response(statusCode: -1, data: data).asObservable() var errored = false _ = observable.filter(statusCodes: 0...9).subscribe { event in switch event { case .next(let object): fail("called on non-correct status code: \(object)") case .error: errored = true default: break } } expect(errored).to(beTruthy()) } it("filters out unrequested status codes range upperbound") { let data = Data() let observable = Response(statusCode: 10, data: data).asObservable() var errored = false _ = observable.filter(statusCodes: 0..<10).subscribe { event in switch event { case .next(let object): fail("called on non-correct status code: \(object)") case .error: errored = true default: break } } expect(errored).to(beTruthy()) } it("filters out unrequested status codes range lowerbound") { let data = Data() let observable = Response(statusCode: -1, data: data).asObservable() var errored = false _ = observable.filter(statusCodes: 0..<10).subscribe { event in switch event { case .next(let object): fail("called on non-correct status code: \(object)") case .error: errored = true default: break } } expect(errored).to(beTruthy()) } it("filters out non-successful status codes") { let data = Data() let observable = Response(statusCode: 404, data: data).asObservable() var errored = false _ = observable.filterSuccessfulStatusCodes().subscribe { event in switch event { case .next(let object): fail("called on non-success status code: \(object)") case .error: errored = true default: break } } expect(errored).to(beTruthy()) } it("passes through correct status codes") { let data = Data() let observable = Response(statusCode: 200, data: data).asObservable() var called = false _ = observable.filterSuccessfulStatusCodes().subscribe(onNext: { _ in called = true }) expect(called).to(beTruthy()) } it("filters out non-successful status and redirect codes") { let data = Data() let observable = Response(statusCode: 404, data: data).asObservable() var errored = false _ = observable.filterSuccessfulStatusAndRedirectCodes().subscribe { event in switch event { case .next(let object): fail("called on non-success status code: \(object)") case .error: errored = true default: break } } expect(errored).to(beTruthy()) } it("passes through correct status codes") { let data = Data() let observable = Response(statusCode: 200, data: data).asObservable() var called = false _ = observable.filterSuccessfulStatusAndRedirectCodes().subscribe(onNext: { _ in called = true }) expect(called).to(beTruthy()) } it("passes through correct redirect codes") { let data = Data() let observable = Response(statusCode: 304, data: data).asObservable() var called = false _ = observable.filterSuccessfulStatusAndRedirectCodes().subscribe(onNext: { _ in called = true }) expect(called).to(beTruthy()) } it("knows how to filter individual status code") { let data = Data() let observable = Response(statusCode: 42, data: data).asObservable() var called = false _ = observable.filter(statusCode: 42).subscribe(onNext: { _ in called = true }) expect(called).to(beTruthy()) } it("filters out different individual status code") { let data = Data() let observable = Response(statusCode: 43, data: data).asObservable() var errored = false _ = observable.filter(statusCode: 42).subscribe { event in switch event { case .next(let object): fail("called on non-success status code: \(object)") case .error: errored = true default: break } } expect(errored).to(beTruthy()) } } describe("image maping") { it("maps data representing an image to an image") { let image = Image.testImage guard let data = image.asJPEGRepresentation(0.75) else { fatalError("Failed creating Data from Image") } let observable = Response(statusCode: 200, data: data).asObservable() var size: CGSize? _ = observable.mapImage().subscribe(onNext: { image in size = image.size }) expect(size).to(equal(image.size)) } it("ignores invalid data") { let data = Data() let observable = Response(statusCode: 200, data: data).asObservable() var receivedError: MoyaError? _ = observable.mapImage().subscribe { event in switch event { case .next: fail("next called for invalid data") case .error(let error): receivedError = error as? MoyaError default: break } } expect(receivedError).toNot(beNil()) let expectedError = MoyaError.imageMapping(Response(statusCode: 200, data: Data(), response: nil)) expect(receivedError).to(beOfSameErrorType(expectedError)) } } describe("JSON mapping") { it("maps data representing some JSON to that JSON") { let json = ["name": "John Crighton", "occupation": "Astronaut"] let data = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) let observable = Response(statusCode: 200, data: data).asObservable() var receivedJSON: [String: String]? _ = observable.mapJSON().subscribe(onNext: { json in if let json = json as? [String: String] { receivedJSON = json } }) expect(receivedJSON?["name"]).to(equal(json["name"])) expect(receivedJSON?["occupation"]).to(equal(json["occupation"])) } it("returns a Cocoa error domain for invalid JSON") { let json = "{ \"name\": \"john }" guard let data = json.data(using: .utf8) else { fatalError("Failed creating Data from JSON String") } let observable = Response(statusCode: 200, data: data).asObservable() var receivedError: MoyaError? _ = observable.mapJSON().subscribe { event in switch event { case .next: fail("next called for invalid data") case .error(let error): receivedError = error as? MoyaError default: break } } expect(receivedError).toNot(beNil()) switch receivedError { case .some(.jsonMapping): break default: fail("expected NSError with \(NSCocoaErrorDomain) domain") } } } describe("string mapping") { it("maps data representing a string to a string") { let string = "You have the rights to the remains of a silent attorney." guard let data = string.data(using: .utf8) else { fatalError("Failed creating Data from String") } let observable = Response(statusCode: 200, data: data).asObservable() var receivedString: String? _ = observable.mapString().subscribe(onNext: { string in receivedString = string }) expect(receivedString).to(equal(string)) } it("maps data representing a string at a key path to a string") { let string = "You have the rights to the remains of a silent attorney." let json = ["words_to_live_by": string] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { fatalError("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asObservable() var receivedString: String? _ = observable.mapString(atKeyPath: "words_to_live_by").subscribe(onNext: { string in receivedString = string }) expect(receivedString).to(equal(string)) } it("ignores invalid data") { let data = Data(bytes: [0x11FFFF] as [UInt32], count: 1) //Byte exceeding UTF8 let observable = Response(statusCode: 200, data: data).asObservable() var receivedError: MoyaError? _ = observable.mapString().subscribe { event in switch event { case .next: fail("next called for invalid data") case .error(let error): receivedError = error as? MoyaError default: break } } expect(receivedError).toNot(beNil()) let expectedError = MoyaError.stringMapping(Response(statusCode: 200, data: Data(), response: nil)) expect(receivedError).to(beOfSameErrorType(expectedError)) } } describe("object mapping") { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" let decoder = JSONDecoder() decoder.dateDecodingStrategy = .formatted(formatter) let json: [String: Any] = [ "title": "Hello, Moya!", "createdAt": "1995-01-14T12:34:56" ] it("maps data representing a json to a decodable object") { guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asObservable() var receivedObject: Issue? _ = observable.map(Issue.self, using: decoder).subscribe(onNext: { object in receivedObject = object }) expect(receivedObject).notTo(beNil()) expect(receivedObject?.title) == "Hello, Moya!" expect(receivedObject?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")! } it("maps data representing a json array to an array of decodable objects") { let jsonArray = [json, json, json] guard let data = try? JSONSerialization.data(withJSONObject: jsonArray, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asObservable() var receivedObjects: [Issue]? _ = observable.map([Issue].self, using: decoder).subscribe(onNext: { objects in receivedObjects = objects }) expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.count) == 3 expect(receivedObjects?.map { $0.title }) == ["Hello, Moya!", "Hello, Moya!", "Hello, Moya!"] } it("maps empty data to a decodable object with optional properties") { let observable = Response(statusCode: 200, data: Data()).asObservable() var receivedObjects: OptionalIssue? _ = observable.map(OptionalIssue.self, using: decoder, failsOnEmptyData: false).subscribe(onNext: { object in receivedObjects = object }) expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.title).to(beNil()) expect(receivedObjects?.createdAt).to(beNil()) } it("maps empty data to a decodable array with optional properties") { let observable = Response(statusCode: 200, data: Data()).asObservable() var receivedObjects: [OptionalIssue]? _ = observable.map([OptionalIssue].self, using: decoder, failsOnEmptyData: false).subscribe(onNext: { object in receivedObjects = object }) expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.count) == 1 expect(receivedObjects?.first?.title).to(beNil()) expect(receivedObjects?.first?.createdAt).to(beNil()) } context("when using key path mapping") { it("maps data representing a json to a decodable object") { let json: [String: Any] = ["issue": json] // nested json guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asObservable() var receivedObject: Issue? _ = observable.map(Issue.self, atKeyPath: "issue", using: decoder).subscribe(onNext: { object in receivedObject = object }) expect(receivedObject).notTo(beNil()) expect(receivedObject?.title) == "Hello, Moya!" expect(receivedObject?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")! } it("maps data representing a json array to a decodable object (#1311)") { let json: [String: Any] = ["issues": [json]] // nested json array guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asObservable() var receivedObjects: [Issue]? _ = observable.map([Issue].self, atKeyPath: "issues", using: decoder).subscribe(onNext: { object in receivedObjects = object }) expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.count) == 1 expect(receivedObjects?.first?.title) == "Hello, Moya!" expect(receivedObjects?.first?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")! } it("maps empty data to a decodable object with optional properties") { let observable = Response(statusCode: 200, data: Data()).asObservable() var receivedObjects: OptionalIssue? _ = observable.map(OptionalIssue.self, atKeyPath: "issue", using: decoder, failsOnEmptyData: false).subscribe(onNext: { object in receivedObjects = object }) expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.title).to(beNil()) expect(receivedObjects?.createdAt).to(beNil()) } it("maps empty data to a decodable array with optional properties") { let observable = Response(statusCode: 200, data: Data()).asObservable() var receivedObjects: [OptionalIssue]? _ = observable.map([OptionalIssue].self, atKeyPath: "issue", using: decoder, failsOnEmptyData: false).subscribe(onNext: { object in receivedObjects = object }) expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.count) == 1 expect(receivedObjects?.first?.title).to(beNil()) expect(receivedObjects?.first?.createdAt).to(beNil()) } it("map Int data to an Int value") { let json: [String: Any] = ["count": 1] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asObservable() var count: Int? _ = observable.map(Int.self, atKeyPath: "count", using: decoder).subscribe(onNext: { value in count = value }) expect(count).notTo(beNil()) expect(count) == 1 } it("map Bool data to a Bool value") { let json: [String: Any] = ["isNew": true] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asObservable() var isNew: Bool? _ = observable.map(Bool.self, atKeyPath: "isNew", using: decoder).subscribe(onNext: { value in isNew = value }) expect(isNew).notTo(beNil()) expect(isNew) == true } it("map String data to a String value") { let json: [String: Any] = ["description": "Something interesting"] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asObservable() var description: String? _ = observable.map(String.self, atKeyPath: "description", using: decoder).subscribe(onNext: { value in description = value }) expect(description).notTo(beNil()) expect(description) == "Something interesting" } it("map String data to a URL value") { let json: [String: Any] = ["url": "http://www.example.com/test"] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asObservable() var url: URL? _ = observable.map(URL.self, atKeyPath: "url", using: decoder).subscribe(onNext: { value in url = value }) expect(url).notTo(beNil()) expect(url) == URL(string: "http://www.example.com/test") } it("shouldn't map Int data to a Bool value") { let json: [String: Any] = ["isNew": 1] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asObservable() var isNew: Bool? _ = observable.map(Bool.self, atKeyPath: "isNew", using: decoder).subscribe(onNext: { value in isNew = value }) expect(isNew).to(beNil()) } it("shouldn't map String data to an Int value") { let json: [String: Any] = ["test": "123"] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asObservable() var test: Int? _ = observable.map(Int.self, atKeyPath: "test", using: decoder).subscribe(onNext: { value in test = value }) expect(test).to(beNil()) } it("shouldn't map Array<String> data to an String value") { let json: [String: Any] = ["test": ["123", "456"]] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asObservable() var test: String? _ = observable.map(String.self, atKeyPath: "test", using: decoder).subscribe(onNext: { value in test = value }) expect(test).to(beNil()) } it("shouldn't map String data to an Array<String> value") { let json: [String: Any] = ["test": "123"] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asObservable() var test: [String]? _ = observable.map([String].self, atKeyPath: "test", using: decoder).subscribe(onNext: { value in test = value }) expect(test).to(beNil()) } } it("ignores invalid data") { var json = json json["createdAt"] = "Hahaha" // invalid date string guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asObservable() var receivedError: Error? _ = observable.map(Issue.self, using: decoder).subscribe { event in switch event { case .next: fail("next called for invalid data") case .error(let error): receivedError = error default: break } } if case let MoyaError.objectMapping(nestedError, _)? = receivedError { expect(nestedError).to(beAKindOf(DecodingError.self)) } else { fail("expected <MoyaError.objectMapping>, got <\(String(describing: receivedError))>") } } } } }
mit
09445ddd75b10d29cb1e578a8bdb92f5
43.51419
151
0.494824
5.796522
false
false
false
false
oacastefanita/PollsFramework
Example/PollsFramework-TV/ViewControllers/NewPollViewController.swift
1
2725
// // NewPollViewController.swift // PollsFramework // // Created by Stefanita Oaca on 24/07/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import PollsFramework import CoreData class NewPollViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let backButton = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(self.onBack(_:))) navigationItem.leftBarButtonItem = backButton } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "singleText" { let poll = (NSEntityDescription.insertNewObject(forEntityName: "Poll", into: PollsFrameworkController.sharedInstance.dataController().managedObjectContext) as! Poll) poll.pollTypeId = PollTypes.singleText.rawValue (segue.destination as! SingleTextViewController).screenType = .create (segue.destination as! SingleTextViewController).poll = poll }else if segue.identifier == "bestText" { let poll = (NSEntityDescription.insertNewObject(forEntityName: "Poll", into: PollsFrameworkController.sharedInstance.dataController().managedObjectContext) as! Poll) poll.pollTypeId = PollTypes.bestText.rawValue (segue.destination as! BestTextViewController).screenType = .create (segue.destination as! BestTextViewController).poll = poll }else if segue.identifier == "singleImage" { let poll = (NSEntityDescription.insertNewObject(forEntityName: "Poll", into: PollsFrameworkController.sharedInstance.dataController().managedObjectContext) as! Poll) poll.pollTypeId = PollTypes.singleImage.rawValue (segue.destination as! SingleImageViewController).screenType = .create (segue.destination as! SingleImageViewController).poll = poll } else if segue.identifier == "bestImage" { let poll = (NSEntityDescription.insertNewObject(forEntityName: "Poll", into: PollsFrameworkController.sharedInstance.dataController().managedObjectContext) as! Poll) poll.pollTypeId = PollTypes.bestImage.rawValue (segue.destination as! BestImageViewController).screenType = .create (segue.destination as! BestImageViewController).poll = poll } } @objc func onBack(_ sender: Any){ self.navigationController?.popViewController(animated: true) } }
mit
6ee2b6471012ee0686d3c85c2343c938
49.444444
177
0.702643
5.08209
false
false
false
false
pikachu987/PKCCrop
PKCCrop/Classes/PKCCropViewController.swift
1
11580
//Copyright (c) 2017 pikachu987 <[email protected]> // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in //all copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. import UIKit public protocol PKCCropDelegate: class { func pkcCropCancel(_ viewController: PKCCropViewController) func pkcCropImage(_ image: UIImage?, originalImage: UIImage?) func pkcCropComplete(_ viewController: PKCCropViewController) } public class PKCCropViewController: UIViewController { public weak var delegate: PKCCropDelegate? public var tag: Int = 0 var image = UIImage() @IBOutlet fileprivate weak var scrollView: UIScrollView! @IBOutlet fileprivate weak var scrollTopConst: NSLayoutConstraint! @IBOutlet fileprivate weak var scrollBottomConst: NSLayoutConstraint! @IBOutlet fileprivate weak var scrollLeadingConst: NSLayoutConstraint! @IBOutlet fileprivate weak var scrollTrailingConst: NSLayoutConstraint! @IBOutlet private weak var toolBar: UIToolbar! fileprivate var isZoomTimer = Timer() fileprivate let imageView = UIImageView() @IBOutlet fileprivate weak var cropLineView: PKCCropLineView! @IBOutlet fileprivate weak var maskView: UIView! private var imageRotateRate: Float = 0 public init(_ image: UIImage, tag: Int = 0) { super.init(nibName: "PKCCropViewController", bundle: Bundle(for: PKCCrop.self)) self.image = image self.tag = tag } override public var prefersStatusBarHidden: Bool{ if self.navigationController == nil || !PKCCropHelper.shared.isNavigationBarShow{ return true }else{ return false } } override public func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if self.navigationController == nil || !PKCCropHelper.shared.isNavigationBarShow{ self.navigationController?.setNavigationBarHidden(true, animated: true) } } override public func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if self.navigationController == nil || !PKCCropHelper.shared.isNavigationBarShow{ self.navigationController?.setNavigationBarHidden(false, animated: true) } } deinit { //print("deinit \(self)") } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func viewDidLoad() { super.viewDidLoad() self.initVars() self.initCrop(self.image) } private func initVars(){ self.view.backgroundColor = .black self.maskView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: PKCCropHelper.shared.maskAlpha) self.maskView.isUserInteractionEnabled = false if let height = self.navigationController?.navigationBar.bounds.height{ if PKCCropHelper.shared.isNavigationBarShow{ self.scrollTopConst.constant = 42 + height } } self.cropLineView.delegate = self self.scrollView.delegate = self self.scrollView.showsVerticalScrollIndicator = false self.scrollView.showsHorizontalScrollIndicator = false self.toolBar.barTintColor = PKCCropHelper.shared.barTintColor self.toolBar.backgroundColor = .white self.toolBar.items?.forEach({ (item) in item.tintColor = PKCCropHelper.shared.tintColor }) var barButtonItems = [UIBarButtonItem]() barButtonItems.append(UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(self.cancelAction(_:)))) if !PKCCropHelper.shared.isDegressShow{ barButtonItems.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)) }else{ barButtonItems.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)) if let image = PKCCropHelper.shared.degressBeforeImage{ barButtonItems.append(UIBarButtonItem(image: image.resize(CGSize(width: 24, height: 24)), style: .done, target: self, action: #selector(self.rotateLeftAction(_:)))) }else{ barButtonItems.append(UIBarButtonItem(title: "-90 Degress", style: .done, target: self, action: #selector(self.rotateLeftAction(_:)))) } barButtonItems.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)) if let image = PKCCropHelper.shared.degressAfterImage{ barButtonItems.append(UIBarButtonItem(image: image.resize(CGSize(width: 24, height: 24)), style: .done, target: self, action: #selector(self.rotateRightAction(_:)))) }else{ barButtonItems.append(UIBarButtonItem(title: "90 Degress", style: .done, target: self, action: #selector(self.rotateRightAction(_:)))) } barButtonItems.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)) } barButtonItems.append(UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.doneAction(_:)))) self.toolBar.setItems(barButtonItems, animated: true) } private func initCrop(_ image: UIImage){ self.scrollView.alpha = 0 self.cropLineView.alpha = 0 self.scrollView.minimumZoomScale = 0.5 self.scrollView.maximumZoomScale = 4 self.scrollView.zoomScale = 1 self.scrollView.subviews.forEach({ $0.removeFromSuperview() }) self.scrollView.addSubview(self.imageView) self.imageView.image = image let width = UIScreen.main.bounds.width - self.scrollLeadingConst.constant - self.scrollTrailingConst.constant let height = UIScreen.main.bounds.height - self.scrollTopConst.constant - self.scrollBottomConst.constant self.imageView.frame = CGRect(x: (width - image.size.width)/2, y: (height - image.size.height)/2, width: image.size.width, height: image.size.height) self.imageView.contentMode = .scaleAspectFill DispatchQueue.main.async { let minimumXScale = PKCCropHelper.shared.minSize / self.image.size.width let minimumYScale = PKCCropHelper.shared.minSize / self.image.size.height let deviceMinSize = UIScreen.main.bounds.width > UIScreen.main.bounds.height ? UIScreen.main.bounds.height : UIScreen.main.bounds.width let currentXScale = (deviceMinSize-40) / self.image.size.width let currentYScale = (deviceMinSize-40) / self.image.size.height self.scrollView.minimumZoomScale = minimumXScale < minimumYScale ? minimumYScale : minimumXScale self.scrollView.zoomScale = currentXScale < currentYScale ? currentYScale : currentXScale DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: { self.cropLineView.initLineFrame() }) DispatchQueue.main.asyncAfter(deadline: .now() + 0.3){ UIView.animate(withDuration: 0.2){ self.scrollView.alpha = 1 self.cropLineView.alpha = 1 } } } } @objc private func cancelAction(_ sender: UIBarButtonItem) { self.delegate?.pkcCropCancel(self) } @objc private func doneAction(_ sender: UIBarButtonItem) { let cropSize = self.cropLineView.cropSize() let captureRect = CGRect( x: -cropSize.origin.x+2, y: -cropSize.origin.y+2, width: self.scrollView.frame.width, height: self.scrollView.frame.height ) UIGraphicsBeginImageContextWithOptions(cropSize.size, false, 0.0) self.scrollView.drawHierarchy(in: captureRect, afterScreenUpdates: false) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() DispatchQueue.main.async { self.delegate?.pkcCropImage(image, originalImage: self.image) } self.delegate?.pkcCropComplete(self) } @objc private func rotateLeftAction(_ sender: UIBarButtonItem) { guard let image = self.imageView.image?.imageRotatedByDegrees(-90, flip: false) else { return } self.initCrop(image) } @objc private func rotateRightAction(_ sender: UIBarButtonItem) { guard let image = self.imageView.image?.imageRotatedByDegrees(90, flip: false) else { return } self.initCrop(image) } } extension PKCCropViewController: UIScrollViewDelegate{ @objc fileprivate func scrollDidZoomCenter(){ let width = UIScreen.main.bounds.width - self.scrollLeadingConst.constant - self.scrollTrailingConst.constant let height = UIScreen.main.bounds.height - self.scrollTopConst.constant - self.scrollBottomConst.constant let widthValue = (width - self.imageView.frame.width)/2 let heightValue = (height - self.imageView.frame.height)/2 self.imageView.frame.origin = CGPoint(x: widthValue, y: heightValue) self.scrollView.contentInset = UIEdgeInsetsMake(heightValue < 0 ? -heightValue : 0, widthValue < 0 ? -widthValue : 0, heightValue < 0 ? heightValue : 0, widthValue < 0 ? widthValue : 0) self.cropLineView.imageViewSize(self.imageView.frame) } public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return self.imageView } public func scrollViewDidZoom(_ scrollView: UIScrollView) { self.isZoomTimer.invalidate() self.isZoomTimer = Timer.scheduledTimer( timeInterval: 0.3, target: self, selector: #selector(self.scrollDidZoomCenter), userInfo: nil, repeats: false ) } } extension PKCCropViewController: PKCCropLineDelegate{ func pkcCropLineMask(_ frame: CGRect){ var frameValue = frame frameValue.origin.y += self.scrollTopConst.constant - 2 frameValue.origin.x += self.scrollLeadingConst.constant - 2 let path = UIBezierPath(roundedRect: frameValue, cornerRadius: PKCCropHelper.shared.isCircle ? frame.width/2 : 0) path.append(UIBezierPath(rect: self.maskView.frame)) let maskLayer = CAShapeLayer() maskLayer.fillRule = kCAFillRuleEvenOdd maskLayer.backgroundColor = UIColor.clear.cgColor maskLayer.path = path.cgPath self.maskView.layer.mask = maskLayer self.view.layoutIfNeeded() } }
mit
f13a3489fa5a0fb0effb46afb2e799ab
40.956522
193
0.678584
4.699675
false
false
false
false
rock-n-code/Kashmir
KashmirTests/Shared/Common/Extensions/UserDefaultsExtensionsTests.swift
1
2798
// // UserDefaultsExtensionsTests.swift // Kashmir // // Created by Javier Cicchelli on 15/02/2017. // Copyright © 2017 Rock & Code. All rights reserved. // import XCTest import Foundation @testable import Kashmir class UserDefaultsExtensionsTests: XCTestCase { // MARK: Constants let defaults = UserDefaults.standard let testKey = "test" // MARK: Setup override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } // MARK: Functions tests func testSetFullyDefinedCoder() { let test = TestCoder() test.title = "Test title" test.value = 100 test.list = ["Test #1", "Test #2", "Test #3"] defaults.set(test, forKey: testKey) defaults.synchronize() guard let testCoded = defaults.decode(forKey: testKey) as? TestCoder else { XCTFail("Unexpected error") return } XCTAssertNotNil(test) XCTAssertNotNil(testCoded) XCTAssert(test == testCoded) defaults.removeObject(forKey: testKey) defaults.synchronize() } func testSetPartiallyDefinedCoder() { let test = TestCoder() test.value = 100 defaults.set(test, forKey: testKey) defaults.synchronize() guard let testCoded = defaults.decode(forKey: testKey) as? TestCoder else { XCTFail("Unexpected error") return } XCTAssertNotNil(test) XCTAssertNotNil(testCoded) XCTAssert(test == testCoded) defaults.removeObject(forKey: testKey) defaults.synchronize() } func testSetEmptyCoder() { let test = TestCoder() defaults.set(test, forKey: testKey) defaults.synchronize() guard let testCoded = defaults.decode(forKey: testKey) as? TestCoder else { XCTFail("Unexpected error") return } XCTAssertNotNil(test) XCTAssertNotNil(testCoded) XCTAssert(test == testCoded) defaults.removeObject(forKey: testKey) defaults.synchronize() } func testDecodeKeyWithEmptyValue() { XCTAssertNil(defaults.decode(forKey: testKey)) } } // MARK: - TestObject class TestCoder: NSObject, NSCoding { // MARK: Properties var title: String? var value: Int? var list: [String]? // MARK: Initializers override init() {} // MARK: NSCoding required convenience init?(coder aDecoder: NSCoder) { self.init() self.title = aDecoder.decodeObject(forKey: "title") as? String self.value = aDecoder.decodeObject(forKey: "value") as? Int self.list = aDecoder.decodeObject(forKey: "list") as? [String] } func encode(with coder: NSCoder) { coder.encode(title, forKey: "title") coder.encode(value, forKey: "value") coder.encode(list, forKey: "list") } // MARK: Equatable static func == (lhs: TestCoder, rhs: TestCoder) -> Bool { return (lhs.title ?? "") == (rhs.title ?? "") && (lhs.value ?? 0) == (rhs.value ?? 0) && (lhs.list ?? []) == (rhs.list ?? []) } }
mit
f22bf2fe1daf878436d67c6a4c99fd44
19.122302
77
0.679299
3.436118
false
true
false
false
Boris-Em/Goban
Goban/Markup.swift
1
1433
// // Markup.swift // GobanSampleProject // // Created by Bobo on 1/13/17. // Copyright © 2017 Boris Emorine. All rights reserved. // import UIKit enum MarkupType { case Cross case Dot } protocol MarkupProtocol { var markupColor: UIColor { get set } var markupType: MarkupType { get set } } struct Markup: MarkupProtocol { var markupColor = UIColor.white var markupType = MarkupType.Cross } func ==(lhs: MarkupModel, rhs: MarkupModel) -> Bool { return lhs.gobanPoint == rhs.gobanPoint && lhs.layer == rhs.layer && lhs.markupColor == rhs.markupColor && lhs.markupType == rhs.markupType } func ==(lhs: MarkupModel, rhs: SGFP.Node) -> Bool { guard let property = rhs.propertyWithName(SGFMarkupProperties.MA.rawValue) else { return false } guard let propertyValue = property.values.first?.toPoint() else { return false } if let gobanPoint = GobanPoint(col: propertyValue.col, row: propertyValue.row) { return gobanPoint == lhs.gobanPoint } return false } internal struct MarkupModel: MarkupProtocol, Hashable { var markupColor = UIColor.white var markupType = MarkupType.Cross var layer: CAShapeLayer var gobanPoint: GobanPoint var hashValue: Int { get { return "\(gobanPoint.x) \(gobanPoint.y) \(Unmanaged.passUnretained(layer).toOpaque())".hashValue } set { } } }
mit
e461ccfd5e3a7070a6adbcae9fe7262c
23.689655
112
0.65852
3.700258
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/CountryManager.swift
1
2868
// // CountryManager.swift // TelegramMac // // Created by keepcoder on 26/11/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa class CountryItem { let shortName:String let fullName:String let smallName:String let code:Int init(shortName:String, fullName:String, smallName:String, code:Int) { self.shortName = shortName self.fullName = fullName self.smallName = smallName self.code = code } } class CountryManager { let countries:[CountryItem] private let coded:[Int:CountryItem] private let smalled:[String:CountryItem] private let fulled:[String:CountryItem] private let shorted:[String:CountryItem] init() { var countries:[CountryItem] = [CountryItem]() var coded:[Int:CountryItem] = [Int:CountryItem]() var smalled:[String:CountryItem] = [String:CountryItem]() var fulled:[String:CountryItem] = [String:CountryItem]() var shorted:[String:CountryItem] = [String:CountryItem]() if let resource = Bundle.main.path(forResource: "PhoneCountries", ofType: "txt"), let content = try? String(contentsOfFile: resource) { let list = content.components(separatedBy: CharacterSet.newlines) for country in list { let parameters = country.components(separatedBy: ";") if parameters.count == 3 { let fullName = "\(parameters[2]) +\(parameters[0])" let item = CountryItem(shortName: parameters[2], fullName: fullName, smallName: parameters[1], code: parameters[0].nsstring.integerValue) countries.append(item) if coded[item.code] == nil { coded[item.code] = item } smalled[item.smallName.lowercased()] = item fulled[item.fullName.lowercased()] = item shorted[item.shortName.lowercased()] = item } } } countries.sort { (item1, item2) -> Bool in return item1.fullName < item2.fullName } self.countries = countries self.coded = coded self.smalled = smalled self.fulled = fulled self.shorted = shorted } func item(byCodeNumber codeNumber: Int) -> CountryItem? { return coded[codeNumber] } func item(bySmallCountryName countryName: String) -> CountryItem? { return smalled[countryName.lowercased()] } func item(byFullCountryName countryName: String) -> CountryItem? { return fulled[countryName.lowercased()] } func item(byShortCountryName countryName: String) -> CountryItem? { return shorted[countryName.lowercased()] } }
gpl-2.0
3151838f952277917afb1ddfd11885b0
32.729412
157
0.592257
4.486698
false
false
false
false
ReactiveKit/Bond
Sources/Bond/Data Structures/TreeArray.swift
2
2826
// // The MIT License (MIT) // // Copyright (c) 2018 DeclarativeHub/Bond // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// A tree array represents a valueless root node of a tree structure where children are of TreeNode<ChileValue> type. public struct TreeArray<Value>: RangeReplaceableTreeProtocol, Instantiatable, CustomDebugStringConvertible { public var children: [TreeNode<Value>] public init() { self.children = [] } public init(_ children: [TreeNode<Value>]) { self.children = children } public init(childrenValues: [Value]) { self.children = childrenValues.map { TreeNode($0) } } public var debugDescription: String { return "[" + children.map { $0.debugDescription }.joined(separator: ", ") + "]" } public var asObject: ObjectTreeArray<Value> { return ObjectTreeArray(children) } } /// Class-based variant of TreeArray. public final class ObjectTreeArray<Value>: RangeReplaceableTreeProtocol, Instantiatable, CustomDebugStringConvertible { public var value: Void = () public var children: [ObjectTreeNode<Value>] public required init() { self.children = [] } public init(_ children: [ObjectTreeNode<Value>]) { self.children = children } public init(_ children: [TreeNode<Value>]) { self.children = children.map { $0.asObject } } public var debugDescription: String { return "[" + children.map { $0.debugDescription }.joined(separator: ", ") + "]" } public var asTreeArray: TreeArray<Value> { get { return TreeArray(children.map { $0.asTreeNode }) } set { self.children = newValue.children.map { $0.asObject } } } }
mit
73cccf674d635bdfdf2bb454013f1d9d
33.048193
119
0.683298
4.347692
false
false
false
false
lstn-ltd/lstn-sdk-ios
Example/Tests/Utilities/MockURLSession.swift
1
1349
// // MockURLSession.swift // Lstn // // Created by Dan Halliday on 18/10/2016. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation @testable import Lstn class MockURLSession: URLSessionType { let data: Data? let response: URLResponse? let error: Error? var dataTaskFired: Bool = false var dataTaskUrl: URL? = nil init(data: Data? = nil, response: URLResponse? = nil, error: Error? = nil) { self.data = data self.error = error let url = URL(string: "http://example.com")! self.response = response ?? HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil) } func dataTask(with url: URL, completionHandler: @escaping URLSessionDataTaskCallbackType) -> URLSessionDataTaskType { self.dataTaskFired = true self.dataTaskUrl = url return MockURLSessionDataTask { completionHandler(self.data, self.response, self.error) } } func dataTask(with request: URLRequest, completionHandler: @escaping URLSessionDataTaskCallbackType) -> URLSessionDataTaskType { self.dataTaskFired = true self.dataTaskUrl = request.url return MockURLSessionDataTask { completionHandler(self.data, self.response, self.error) } } }
mit
12ef8b9b3a520d75b36aff5de505c2a7
23.509091
132
0.652819
4.478405
false
false
false
false
AndyQ/CNCPlotter
CNCPlotter/GCodeParser.swift
1
4719
// // GCodeParser.swift // CNCPlotter // // Created by Andy Qua on 01/01/2017. // Copyright © 2017 Andy Qua. All rights reserved. // import Cocoa class GCodeItem : CustomStringConvertible { var type : String = "" var value : Int = 0 var elements : [String] var comments : String = "" var children = [String:Float]() init( elements : [String], comments : String ) { var i = 0 self.elements = elements self.comments = comments for element in elements { var cmd = element.substring(to: 1) var val : Float = 0 if cmd == "(" { cmd = element } else { val = Float(element.substring(from: 1))! } if i == 0 { self.type = cmd self.value = Int(val) } else { children[cmd] = val } i += 1 } } func writeGCode( scale : Float ) -> String { var ret = "" if type != "" { ret = "\(type)\(value)" } for (key, var val) in children { if "XYZ".contains(key) { val *= scale } ret += " \(key)\(val)" } ret += comments return ret } func isPenUp() -> Bool { var ret = false if type == "M" && (value == 300 ) { if let val = children["S"], val == 50 || val == 90 { ret = true } } if type == "M" && (value == 190 ) { ret = true } return ret } func isPenDown() -> Bool { var ret = false if type == "M" && (value == 300 || value == 1) { if let val = children["S"], val == 30 || val == 130 { ret = true } } if type == "M" && (value == 1130 ) { ret = true } return ret } func isMove() -> Bool { return type == "G" && (value == 0 || value == 1) } func getPosition() -> (CGFloat,CGFloat) { if !isMove() { return (0,0) } var x :CGFloat = 0 var y :CGFloat = 0 // Now grab out the X and Y coords if let xVal = children["X"], let yVal = children["Y"] { x = CGFloat(xVal) y = CGFloat(yVal) } return (x,y) } var description: String { return writeGCode(scale:1.0) } } class GCodeFile : CustomStringConvertible { let re1 = Regex("\\s*[%#;].*") let re2 = Regex("\\s*\\(.*\\).*") let re3 = Regex("\\s+") let re4 = Regex("([a-zA-Z][0-9\\+\\-\\.]*)|(\\*[0-9]+)") // let re4 = Regex("([a-zA-Z][0-9\\+\\-\\.]*)|(\\*[0-9]+)*(\\(.*\\))") var items = [GCodeItem]() init() { } init( lines : [String] ) { parseGCode( lines: lines ) } func parseGCode( lines : [String] ) { for line in lines { let gcodeItem = parseGCodeLine(line:line) items.append(gcodeItem) } } func parseGCodeLine( line : String ) -> GCodeItem { // First, take a copy of the comments let commentItems = getComments( line:line ) let comments = commentItems.count > 0 ? commentItems[0] : "" var ret = stripComments( line:line ) ret = removeSpaces( line:ret ).uppercased() let elements = re4.match(input: ret) let gcodeItem = GCodeItem(elements:elements, comments:comments) return gcodeItem } func removeSpaces( line: String ) -> String { let s = re3.replace(input: line, replacement: "") return s } func getComments( line : String ) -> [String] { let c1 = re1.match(input: line) let c2 = re2.match(input: line) var ret = [String]() if c1.count > 0 { ret.append(contentsOf:c1) } if c2.count > 0 { ret.append(contentsOf:c2) } return ret } func stripComments( line : String ) -> String { let s = re1.replace(input: line, replacement: "") let s2 = re2.replace(input: s, replacement: "") return s2 } func writeGCode( scale : Float ) -> String { var ret = "" for item in self.items { ret += "\(item.writeGCode(scale: scale))\n" } return ret } var description: String { return writeGCode(scale:1.0) } }
apache-2.0
407809d55575511cd3cf84756a85ffba
22.828283
73
0.437897
4.005093
false
false
false
false
sublimter/Meijiabang
KickYourAss/KickYourAss/ZXY_Start/ZXY_SearchVCS/ZXY_SearchArtistVC.swift
3
12609
// // ZXY_SearchArtistVC.swift // KickYourAss // // Created by 宇周 on 15/2/6. // Copyright (c) 2015年 多思科技. All rights reserved. // import UIKit class ZXY_SearchArtistVC: UIViewController { @IBOutlet var titleV: UIView! @IBOutlet weak var searchText: UITextField! @IBOutlet weak var currentTable: UITableView! private var userCityForFail = "大连市" private var allUserList : NSMutableArray? = NSMutableArray() private var locationService : BMKLocationService = BMKLocationService() private var cityNameSearch : BMKGeoCodeSearch = BMKGeoCodeSearch() var isDownLoad = false var currentPage = 1 override func viewDidLoad() { super.viewDidLoad() self.currentTable.tableFooterView = UIView(frame: CGRectZero) currentTable.addFooterWithCallback {[weak self] () -> Void in self?.currentTable.footerPullToRefreshText = "上拉加载更多" self?.currentTable.footerReleaseToRefreshText = "松开加载" self?.currentTable.footerRefreshingText = "正在加载" self?.currentPage++ self?.startGetArtistListData() } currentTable.addHeaderWithCallback { [weak self] () -> Void in self?.currentPage = 1 self?.currentTable.headerPullToRefreshText = "下拉刷新" self?.currentTable.headerReleaseToRefreshText = "松开刷新" self?.currentTable.headerRefreshingText = "正在刷新" self?.startGetArtistListData() } self.setNaviBarLeftImage("backArrow") self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "搜索", style: UIBarButtonItemStyle.Bordered, target: self, action: Selector("startGetArtistListData")) self.navigationItem.titleView = self.titleV // Do any additional setup after loading the view. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) locationService.delegate = nil cityNameSearch.delegate = nil locationService.stopUserLocationService() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func startGetArtistListData() { var userID : String? = LCYCommon.sharedInstance.userInfo?.userID if(userID == nil) { userID = "" } var cityNameTemp = ZXY_UserInfoDetail.sharedInstance.getUserCityName() if(cityNameTemp == nil) { locationService.delegate = self cityNameSearch.delegate = self locationService.startUserLocationService() } else { var apiString = ZXY_ALLApi.ZXY_MainAPI + ZXY_ALLApi.ZXY_SearchListAPI var coor : Dictionary<String , String?>? = ZXY_UserInfoDetail.sharedInstance.getUserCoordinate() var lat : String! = coor!["latitude"]! var log : String! = coor!["longitude"]! var apiParameter : Dictionary<String , AnyObject> = ["user_id" : "", "city" : cityNameTemp!, "lng" : log, "lat" : lat, "p" : currentPage, "nick_name" : searchText.text ] ZXY_NetHelperOperate.sharedInstance.startGetDataPost(apiString, parameter: apiParameter, successBlock: {[weak self] (returnDic) -> Void in if(self?.currentPage == 1) { self?.allUserList?.removeAllObjects() self?.allUserList?.addObjectsFromArray(ZXYSearchBaseModel(dictionary: returnDic).data) } else { self?.allUserList?.addObjectsFromArray(ZXYSearchBaseModel(dictionary: returnDic).data) } self?.isDownLoad = false self?.reloadCurrentTable() }) {[weak self] (error) -> Void in println(error) self?.isDownLoad = false self?.reloadCurrentTable() } } } } extension ZXY_SearchArtistVC : UITableViewDelegate , UITableViewDataSource , ZXY_SearchArtistCellDelegate { func reloadCurrentTable() { currentTable.footerEndRefreshing() currentTable.headerEndRefreshing() currentTable.reloadData() } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier(ZXY_SearchArtistCellID) as ZXY_SearchArtistCell cell.setRateValue(indexPath.row) var currentUser = allUserList![indexPath.row] as ZXYData cell.userName.text = currentUser.nickName as String cell.userProfile.image = UIImage(named: "search_personCenter") cell.setIsAttensionFlag(currentUser) cell.delegate = self if let isNil = currentUser.score { var scoreFloat : Float = (currentUser.score as NSString).floatValue var scoreInt : Int = Int(scoreFloat) cell.setRateValue(scoreInt) } else { cell.setRateValue(0) } if let isNil = currentUser.headImage { if(currentUser.headImage.hasPrefix("http")) { var urlString = currentUser.headImage cell.userProfile.setImageWithURL(NSURL(string: urlString)) } else { var urlString = ZXY_ALLApi.ZXY_MainAPIImage + currentUser.headImage cell.userProfile.setImageWithURL(NSURL(string: urlString)) } } else { cell.userProfile.image = UIImage(named: "search_personCenter") } var artCoor = self.xYStringToCoor(currentUser.longitude, latitude: currentUser.latitude) var coor : Dictionary<String , String?>? = ZXY_UserInfoDetail.sharedInstance.getUserCoordinate() var lat = coor!["latitude"]! var log = coor!["longitude"]! var userCoor = self.xYStringToCoor(log, latitude: lat) var distance = self.distanceCompareCoor(artCoor, userPosition: userCoor) cell.distanceLbl.text = "\(Double(round(100 * distance)/100)) km" cell.userProfileEdge.backgroundColor = self.colorWithIndexPath(indexPath) cell.conerLbl.backgroundColor = self.colorWithIndexPath(indexPath) if(currentUser.role == "1") { cell.conerLbl.hidden = true } else { cell.conerLbl.hidden = false } if(currentUser.image.count > 0) { cell.userArtPhotoView.hidden = false cell.setArtsImage(currentUser.image as [ZXYImage]) } else { cell.userArtPhotoView.hidden = true } return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var currentUser = allUserList![indexPath.row] as ZXYData if(currentUser.image.count > 0) { return 181 } else { return 181 - 94 } } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let isNil = allUserList { return allUserList!.count } else { return 0 } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var currentArtist = allUserList![indexPath.row] as ZXYData var story = UIStoryboard(name: "ArtistDetailStoryBoard", bundle: nil) //var currentArtist : ZXYArtistListData = userListData[indexPath.row] as ZXYArtistListData var vc = story.instantiateViewControllerWithIdentifier(ZXY_ArtistDetailVCID) as ZXY_ArtistDetailVC vc.setUserID(currentArtist.userId) self.navigationController?.pushViewController(vc, animated: true) } func attensionBtnClick(currentFlag: ZXYData) { var urlString = ZXY_ALLApi.ZXY_MainAPI + ZXY_ALLApi.ZXY_ChangeStatusAtten var userID : String? = LCYCommon.sharedInstance.userInfo?.userID if(userID == nil) { var story = UIStoryboard(name: "AboutMe", bundle: nil) var vc = story.instantiateViewControllerWithIdentifier("login") as UIViewController self.navigationController?.pushViewController(vc, animated: true) return } var changeUserID = currentFlag.userId var controlID = "" if(currentFlag.isAttention == 1) { controlID = "2" } else { controlID = "1" } var parameter :Dictionary<String , AnyObject> = ["control" : controlID , "user_id" : (userID! as NSString).integerValue , "attention_user_id": (changeUserID as NSString).integerValue] ZXY_NetHelperOperate().startGetDataPost(urlString, parameter: parameter, successBlock: { [weak self] (returnDic) -> Void in if(currentFlag.isAttention == 1) { currentFlag.isAttention = 2 } else { currentFlag.isAttention = 1 } self?.currentTable.reloadData() }) { (error) -> Void in } } } extension ZXY_SearchArtistVC : BMKLocationServiceDelegate , BMKGeoCodeSearchDelegate { func didUpdateBMKUserLocation(userLocation: BMKUserLocation!) { var lastLocation : CLLocation = userLocation.location var optionO : BMKReverseGeoCodeOption = BMKReverseGeoCodeOption() optionO.reverseGeoPoint = userLocation.location.coordinate ZXY_UserInfoDetail.sharedInstance.setUserCoordinate("\(lastLocation.coordinate.latitude)", longitude: "\(lastLocation.coordinate.longitude)") self.cityNameSearch.reverseGeoCode(optionO) } func onGetReverseGeoCodeResult(searcher: BMKGeoCodeSearch!, result: BMKReverseGeoCodeResult!, errorCode error: BMKSearchErrorCode) { if(error.value == BMK_SEARCH_NO_ERROR.value) { ZXY_UserInfoDetail.sharedInstance.setUserCityName(result.addressDetail.city) startGetArtistListData() searcher.delegate = nil locationService.stopUserLocationService() } else { ZXY_UserInfoDetail.sharedInstance.setUserCityName(userCityForFail) startGetArtistListData() searcher.delegate = nil locationService.stopUserLocationService() } } } extension ZXY_SearchArtistVC { func colorWithIndexPath(indexPath: NSIndexPath) -> UIColor { var currentRow = indexPath.row switch currentRow % 5 { case 0: return UIColor.greenColor() case 1: return UIColor.redColor() case 2: return UIColor.orangeColor() case 3: return UIColor.greenColor() case 4: return UIColor.purpleColor() default: return UIColor.greenColor() } } func distanceCompareCoor(artistPosition : CLLocationCoordinate2D? , userPosition : CLLocationCoordinate2D?) -> Double { if(artistPosition != nil && userPosition != nil) { var artistPot = BMKMapPointForCoordinate(artistPosition!) var userPot = BMKMapPointForCoordinate(userPosition!) var distance = BMKMetersBetweenMapPoints(artistPot, userPot) return distance/1000 } else { return 0 } } func xYStringToCoor(longitude : String? , latitude: String?) -> CLLocationCoordinate2D? { if(longitude == nil || latitude == nil) { return nil } else { var logFloat = (longitude! as NSString).doubleValue var latFloat = (latitude! as NSString).doubleValue return CLLocationCoordinate2DMake(latFloat, logFloat) } } }
mit
46890804453d2bdf092118f8c5783c79
33.526171
191
0.596585
4.97144
false
false
false
false
somegeekintn/SimDirs
SimDirs/Model/SimRuntime.swift
1
4689
// // SimRuntime.swift // SimDirs // // Created by Casey Fleser on 5/24/22. // import SwiftUI class SimRuntime: ObservableObject, Comparable, Decodable { enum CodingKeys: String, CodingKey { case availabilityError case bundlePath case buildversion case identifier case isAvailable case isInternal case name case platform case runtimeRoot case supportedDeviceTypes case version } struct DeviceType: Decodable { let name : String let bundlePath : String let identifier : String let productFamily : SimProductFamily init(canonical: SimDeviceType) { name = canonical.name bundlePath = canonical.bundlePath identifier = canonical.identifier productFamily = canonical.productFamily } } @Published var devices = [SimDevice]() let name : String let version : String let identifier : String let platform : SimPlatform let bundlePath : String let buildversion : String let runtimeRoot : String let isInternal : Bool let isAvailable : Bool var supportedDeviceTypes : [DeviceType] let availabilityError : String? var isPlaceholder = false static func < (lhs: SimRuntime, rhs: SimRuntime) -> Bool { return lhs.name < rhs.name } static func == (lhs: SimRuntime, rhs: SimRuntime) -> Bool { return lhs.identifier == rhs.identifier } init(platformID: String) throws { guard let lastComponent = platformID.split(separator: ".").last else { throw SimError.deviceParsingFailure } let vComps = lastComponent.split(separator: "-") if vComps.count == 3 { guard let compPlatform = SimPlatform(rawValue: String(vComps[0])) else { throw SimError.deviceParsingFailure } guard let major = Int(vComps[1]) else { throw SimError.deviceParsingFailure } guard let minor = Int(vComps[2]) else { throw SimError.deviceParsingFailure } platform = compPlatform version = "\(major).\(minor)" name = "\(platform) \(version)" identifier = platformID bundlePath = "" buildversion = "" runtimeRoot = "" isInternal = false isAvailable = false supportedDeviceTypes = [] availabilityError = "Missing runtime" isPlaceholder = true } else { throw SimError.deviceParsingFailure } } func supports(deviceType: SimDeviceType) -> Bool { return supportedDeviceTypes.contains { $0.identifier == deviceType.identifier } } func supports(platform: SimPlatform) -> Bool { return self.platform == platform } func setDevices(_ devices: [SimDevice], from devTypes: [SimDeviceType]) { self.devices = devices // If this runtime is a placeholder it will be missing supported device types // create device type stubs based on the devices being added using supplied // fully described device types if isPlaceholder { let devTypeIDs = Set(devices.map({ $0.deviceTypeIdentifier })) self.supportedDeviceTypes = devTypeIDs.compactMap { devTypeID in devTypes.first(where: { $0.identifier == devTypeID }).map({ SimRuntime.DeviceType(canonical: $0) }) } } } } extension SimRuntime: SourceItemData { var title : String { return name } var headerTitle : String { "Runtime: \(title)" } var imageDesc : SourceImageDesc { .symbol(systemName: "shippingbox", color: isAvailable ? .green : .red) } var optionTrait : SourceFilter.Options { isAvailable ? .runtimeInstalled : [] } } extension Array where Element == SimRuntime { mutating func indexOfMatchedOrCreated(identifier: String) throws -> Index { return try firstIndex { $0.identifier == identifier } ?? { try self.append(SimRuntime(platformID: identifier)) return self.endIndex - 1 }() } func supporting(deviceType: SimDeviceType) -> Self { filter { $0.supports(deviceType: deviceType) } } func supporting(platform: SimPlatform) -> Self { filter { $0.supports(platform: platform) } } }
mit
33a973ffeec4e8fdfcb89c477e75e053
32.255319
122
0.579015
5.085683
false
false
false
false
klundberg/swift-corelibs-foundation
Foundation/NSXMLDTDNode.swift
1
8283
// 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 // import CoreFoundation /*! @typedef NSXMLDTDNodeKind @abstract The subkind of a DTD node kind. */ extension XMLDTDNode { public enum DTDKind : UInt { case general case parsed case unparsed case parameter case predefined case cdataAttribute case idAttribute case idRefAttribute case idRefsAttribute case entityAttribute case entitiesAttribute case nmTokenAttribute case nmTokensAttribute case enumerationAttribute case notationAttribute case undefinedDeclaration case emptyDeclaration case anyDeclaration case mixedDeclaration case elementDeclaration } } /*! @class NSXMLDTDNode @abstract The nodes that are exclusive to a DTD @discussion Every DTD node has a name. Object value is defined as follows:<ul> <li><b>Entity declaration</b> - the string that that entity resolves to eg "&lt;"</li> <li><b>Attribute declaration</b> - the default value, if any</li> <li><b>Element declaration</b> - the validation string</li> <li><b>Notation declaration</b> - no objectValue</li></ul> */ public class XMLDTDNode: XMLNode { /*! @method initWithXMLString: @abstract Returns an element, attribute, entity, or notation DTD node based on the full XML string. */ public init?(XMLString string: String) { guard let ptr = _CFXMLParseDTDNode(string) else { return nil } super.init(ptr: ptr) } //primitive public override init(kind: XMLNode.Kind, options: Int) { let ptr: _CFXMLNodePtr switch kind { case .elementDeclaration: ptr = _CFXMLDTDNewElementDesc(nil, nil)! default: super.init(kind: kind, options: options) return } super.init(ptr: ptr) } //primitive /*! @method DTDKind @abstract Sets the DTD sub kind. */ public var dtdKind: DTDKind { switch _CFXMLNodeGetType(_xmlNode) { case _kCFXMLDTDNodeTypeElement: switch _CFXMLDTDElementNodeGetType(_xmlNode) { case _kCFXMLDTDNodeElementTypeAny: return .anyDeclaration case _kCFXMLDTDNodeElementTypeEmpty: return .emptyDeclaration case _kCFXMLDTDNodeElementTypeMixed: return .mixedDeclaration case _kCFXMLDTDNodeElementTypeElement: return .elementDeclaration default: return .undefinedDeclaration } case _kCFXMLDTDNodeTypeEntity: switch _CFXMLDTDEntityNodeGetType(_xmlNode) { case _kCFXMLDTDNodeEntityTypeInternalGeneral: return .general case _kCFXMLDTDNodeEntityTypeExternalGeneralUnparsed: return .unparsed case _kCFXMLDTDNodeEntityTypeExternalParameter: fallthrough case _kCFXMLDTDNodeEntityTypeInternalParameter: return .parameter case _kCFXMLDTDNodeEntityTypeInternalPredefined: return .predefined case _kCFXMLDTDNodeEntityTypeExternalGeneralParsed: return .general default: fatalError("Invalid entity declaration type") } case _kCFXMLDTDNodeTypeAttribute: switch _CFXMLDTDAttributeNodeGetType(_xmlNode) { case _kCFXMLDTDNodeAttributeTypeCData: return .cdataAttribute case _kCFXMLDTDNodeAttributeTypeID: return .idAttribute case _kCFXMLDTDNodeAttributeTypeIDRef: return .idRefAttribute case _kCFXMLDTDNodeAttributeTypeIDRefs: return .idRefsAttribute case _kCFXMLDTDNodeAttributeTypeEntity: return .entityAttribute case _kCFXMLDTDNodeAttributeTypeEntities: return .entitiesAttribute case _kCFXMLDTDNodeAttributeTypeNMToken: return .nmTokenAttribute case _kCFXMLDTDNodeAttributeTypeNMTokens: return .nmTokensAttribute case _kCFXMLDTDNodeAttributeTypeEnumeration: return .enumerationAttribute case _kCFXMLDTDNodeAttributeTypeNotation: return .notationAttribute default: fatalError("Invalid attribute declaration type") } case _kCFXMLTypeInvalid: return unsafeBitCast(0, to: DTDKind.self) // this mirrors Darwin default: fatalError("This is not actually a DTD node!") } }//primitive /*! @method isExternal @abstract True if the system id is set. Valid for entities and notations. */ public var external: Bool { return systemID != nil } //primitive /*! @method publicID @abstract Sets the public id. This identifier should be in the default catalog in /etc/xml/catalog or in a path specified by the environment variable XML_CATALOG_FILES. When the public id is set the system id must also be set. Valid for entities and notations. */ public var publicID: String? { get { return _CFXMLDTDNodeGetPublicID(_xmlNode)?._swiftObject } set { if let value = newValue { _CFXMLDTDNodeSetPublicID(_xmlNode, value) } else { _CFXMLDTDNodeSetPublicID(_xmlNode, nil) } } } /*! @method systemID @abstract Sets the system id. This should be a URL that points to a valid DTD. Valid for entities and notations. */ public var systemID: String? { get { return _CFXMLDTDNodeGetSystemID(_xmlNode)?._swiftObject } set { if let value = newValue { _CFXMLDTDNodeSetSystemID(_xmlNode, value) } else { _CFXMLDTDNodeSetSystemID(_xmlNode, nil) } } } /*! @method notationName @abstract Set the notation name. Valid for entities only. */ public var notationName: String? { get { guard dtdKind == .unparsed else { return nil } return _CFXMLGetEntityContent(_xmlNode)?._swiftObject } set { guard dtdKind == .unparsed else { return } if let value = newValue { _CFXMLNodeSetContent(_xmlNode, value) } else { _CFXMLNodeSetContent(_xmlNode, nil) } } }//primitive internal override class func _objectNodeForNode(_ node: _CFXMLNodePtr) -> XMLDTDNode { let type = _CFXMLNodeGetType(node) precondition(type == _kCFXMLDTDNodeTypeAttribute || type == _kCFXMLDTDNodeTypeNotation || type == _kCFXMLDTDNodeTypeEntity || type == _kCFXMLDTDNodeTypeElement) if let privateData = _CFXMLNodeGetPrivateData(node) { return XMLDTDNode.unretainedReference(privateData) } return XMLDTDNode(ptr: node) } internal override init(ptr: _CFXMLNodePtr) { super.init(ptr: ptr) } }
apache-2.0
ddaace310a9e8a4d6440bf61e6fbd739
29.12
268
0.55801
5.225868
false
false
false
false
jasperscholten/programmeerproject
JasperScholten-project/Form.swift
1
1152
// // Form.swift // JasperScholten-project // // Created by Jasper Scholten on 16-01-17. // Copyright © 2017 Jasper Scholten. All rights reserved. // // The struct presented here contains all characteristics of the 'Forms' saved in Firebase. This entry in Firebase contains all forms, related to the organisation that created the form. import Foundation import Firebase struct Form { let formName: String let formID: String let organisationID: String init(formName: String, formID: String, organisationID: String) { self.formName = formName self.formID = formID self.organisationID = organisationID } init(snapshot: FIRDataSnapshot) { let snapshotValue = snapshot.value as! [String: AnyObject] self.formName = snapshotValue["formName"] as! String self.formID = snapshotValue["formID"] as! String self.organisationID = snapshotValue["organisationID"] as! String } func toAnyObject() -> Any { return [ "formName": formName, "formID": formID, "organisationID": organisationID ] } }
apache-2.0
e893e0f8b1f4b14851301b9be475001f
27.775
186
0.653345
4.231618
false
false
false
false
Pacific3/PUIKit
PUIKit/Extensions/UIApplication.swift
1
1465
extension UIApplication { public func p_setPrimaryColor( primary: Color, secondaryColor secondary: Color, terciaryColor terciary: Color) { UINavigationBar.appearance().barTintColor = primary UINavigationBar.appearance().tintColor = secondary UIBarButtonItem.appearance().tintColor = secondary UITabBar.appearance().barTintColor = secondary UITabBar.appearance().tintColor = primary UINavigationBar.appearance().titleTextAttributes = [ NSForegroundColorAttributeName: secondary ] UINavigationBar.appearanceWhenContainedInInstancesOfClasses([UIPopoverPresentationController.self]).barTintColor = secondary UINavigationBar.appearanceWhenContainedInInstancesOfClasses([UIPopoverPresentationController.self]).tintColor = primary UINavigationBar.appearanceWhenContainedInInstancesOfClasses([UIPopoverPresentationController.self]).titleTextAttributes = [ NSForegroundColorAttributeName: primary ] } public func p_setPrimaryColor<C: ColorConvertible>( primary: C, secondaryColor secondary: C, terciaryColor terciary: C) { p_setPrimaryColor(primary.color(), secondaryColor: secondary.color(), terciaryColor: terciary.color() ) } }
mit
d21bc4652c30fc88e983382d975e41d0
39.694444
136
0.649147
6.845794
false
false
false
false
Codeido/swift-basics
Playground Codebase/Classes.playground/section-1.swift
1
1856
// Playground - noun: a place where people can play import UIKit //All methods and properties of a class are public. If you just need to store data in a structured object, you should use a struct // A parent class of Square class Shape { init() { } func getArea() -> Int { return 0; } } // A simple class `Square` extends `Shape` class Square: Shape { var sideLength: Int // Custom getter and setter property var perimeter: Int { get { return 4 * sideLength } set { sideLength = newValue / 4 } } init(sideLength: Int) { self.sideLength = sideLength super.init() } func shrink() { if sideLength > 0 { --sideLength } } override func getArea() -> Int { return sideLength * sideLength } } var mySquare = Square(sideLength: 5) print(mySquare.getArea()) // 25 mySquare.shrink() print(mySquare.sideLength) // 4 // Access the Square class object, // equivalent to [Square class] in Objective-C. Square.self //example for 'willSet' and 'didSet' class StepCounter { var totalSteps: Int = 0 { willSet(newTotalSteps) { println("About to set totalSteps to \(newTotalSteps)") } didSet { if totalSteps > oldValue { println("Added \(totalSteps - oldValue) steps to 'totalSteps'") } } } } var stepCounter = StepCounter() stepCounter.totalSteps = 100 // About to set totalSteps to 100 \n Added 100 steps to 'totalSteps' stepCounter.totalSteps = 145 // About to set totalSteps to 145 \n Added 45 steps to 'totalSteps' // If you don't need a custom getter and setter, but still want to run code // before an after getting or setting a property, you can use `willSet` and `didSet`
gpl-2.0
0985dd4795b4df9337987b3051376b84
24.438356
130
0.609375
4.24714
false
false
false
false
ksco/swift-algorithm-club-cn
Longest Common Subsequence/LongestCommonSubsequence.playground/Contents.swift
1
1643
extension String { public func longestCommonSubsequence(other: String) -> String { func lcsLength(other: String) -> [[Int]] { var matrix = [[Int]](count: self.characters.count+1, repeatedValue: [Int](count: other.characters.count+1, repeatedValue: 0)) for (i, selfChar) in self.characters.enumerate() { for (j, otherChar) in other.characters.enumerate() { if otherChar == selfChar { matrix[i+1][j+1] = matrix[i][j] + 1 } else { matrix[i+1][j+1] = max(matrix[i][j+1], matrix[i+1][j]) } } } return matrix } func backtrack(matrix: [[Int]]) -> String { var i = self.characters.count var j = other.characters.count var charInSequence = self.endIndex var lcs = String() while i >= 1 && j >= 1 { if matrix[i][j] == matrix[i][j - 1] { j -= 1 } else if matrix[i][j] == matrix[i - 1][j] { i -= 1 charInSequence = charInSequence.predecessor() } else { i -= 1 j -= 1 charInSequence = charInSequence.predecessor() lcs.append(self[charInSequence]) } } return String(lcs.characters.reverse()) } return backtrack(lcsLength(other)) } } // Examples let a = "ABCBX" let b = "ABDCAB" let c = "KLMK" a.longestCommonSubsequence(c) // "" a.longestCommonSubsequence("") // "" a.longestCommonSubsequence(b) // "ABCB" b.longestCommonSubsequence(a) // "ABCB" a.longestCommonSubsequence(a) // "ABCBX" "Hello World".longestCommonSubsequence("Bonjour le monde")
mit
2fd8ea14981b62cac869f03b75b2dcaf
27.327586
131
0.558125
3.458947
false
false
false
false
adozenlines/xmpp-messenger-ios
Example/xmpp-messenger-ios/OpenChatsTableViewController.swift
2
5474
// // GroupChatTableViewController.swift // OneChat // // Created by Paul on 02/03/2015. // Copyright (c) 2015 ProcessOne. All rights reserved. // import UIKit import xmpp_messenger_ios import XMPPFramework class OpenChatsTableViewController: UITableViewController, OneRosterDelegate { var chatList = NSArray() // Mark: Life Cycle override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) OneRoster.sharedInstance.delegate = self OneChat.sharedInstance.connect(username: kXMPP.myJID, password: kXMPP.myPassword) { (stream, error) -> Void in if let _ = error { self.performSegueWithIdentifier("One.HomeToSetting", sender: self) } else { //set up online UI } } tableView.rowHeight = 50 // Mark: Will show the label with the text "No recent chats" if there is no open chats view.addSubview(OneChats.noRecentChats()) // Mark: Checking the internet connection if !OneChat.sharedInstance.isConnectionAvailable() { let alertController = UIAlertController(title: "Error", message: "Please check the internet connection.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dissmiss", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in //do something })) self.presentViewController(alertController, animated: true, completion: nil) } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) OneRoster.sharedInstance.delegate = nil } // Mark: OneRoster Delegates func oneRosterContentChanged(controller: NSFetchedResultsController) { //Will reload the tableView to reflet roster's changes tableView.reloadData() } // Mark: UITableView Datasources override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return OneChats.getChatsList().count } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { //let sections: NSArray? = OneRoster.sharedInstance.fetchedResultsController()!.sections return 1//sections } // Mark: UITableView Delegates override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.01 } override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView() } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let user = OneChats.getChatsList().objectAtIndex(indexPath.row) as! XMPPUserCoreDataStorageObject cell!.textLabel!.text = user.displayName cell!.detailTextLabel?.hidden = true OneChat.sharedInstance.configurePhotoForCell(cell!, user: user) cell?.imageView?.layer.cornerRadius = 24 cell?.imageView?.clipsToBounds = true return cell! } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { let refreshAlert = UIAlertController(title: "", message: "Are you sure you want to clear the entire message history? \n This cannot be undone.", preferredStyle: UIAlertControllerStyle.ActionSheet) refreshAlert.addAction(UIAlertAction(title: "Clear message history", style: .Destructive, handler: { (action: UIAlertAction!) in OneChats.removeUserAtIndexPath(indexPath) // Mark: Will show the label with the text "No recent chats" if there is no open chats self.view.addSubview(OneChats.noRecentChats()) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left) })) refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in })) presentViewController(refreshAlert, animated: true, completion: nil) } } // Mark: Segue support override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool { if identifier == "chat.to.add" { if !OneChat.sharedInstance.isConnected() { let alert = UIAlertController(title: "Attention", message: "You have to be connected to start a chat", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) return false } } return true } override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) { if segue?.identifier == "chats.to.chat" { if let controller = segue?.destinationViewController as? ChatViewController { if let cell: UITableViewCell? = sender as? UITableViewCell { let user = OneChats.getChatsList().objectAtIndex(tableView.indexPathForCell(cell!)!.row) as! XMPPUserCoreDataStorageObject controller.recipient = user } } } } // Mark: Memory Management override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
8476dfd5bf372405aee822fa6785fe3b
35.493333
199
0.713372
4.623311
false
false
false
false
imryan/swifty-tinder
SwiftyTinder/Classes/Models/STProfile.swift
1
3072
// // STProfile.swift // SwiftyTinder // // Created by Ryan Cohen on 7/31/16. // Copyright © 2016 Ryan Cohen. All rights reserved. // import Foundation public class STProfile { public enum STGenderType: Int { case STGenderTypeMale = 0 case STGenderTypeFemale = 1 } public struct STInterest { var id: String var name: String } public struct STJob { var companyId: String? var company: String? var titleId: String? var title: String? } public struct STSchool { var id: String? var name: String? var year: String? var type: String? } public struct STPhoto { enum STPhotoSize: Int { case Size640 = 0 case Size320 = 1 case Size172 = 2 case Size84 = 3 } var photoURL: String? // [640x640], 320x320, 172x172, 84x84 are resolutions // => photos[i]["processed_files"][x]["url"] func photoWithSize(size: STPhotoSize) -> STPhoto { return STPhoto(photoURL: nil) } } public var id: String public var name: String public var birthdate: String // => "1996-09-04T00:00:00.000Z" public var distance: Int? public var bio: String public var gender: STGenderType public var photos: [STPhoto] = [] public var jobs: [STJob]? = [] public var schools: [STSchool]? = [] init(dictionary: NSDictionary) { self.id = dictionary["_id"] as! String self.name = dictionary["name"] as! String self.birthdate = dictionary["birth_date"] as! String self.distance = dictionary["distance_mi"] as? Int self.bio = dictionary["bio"] as! String self.gender = STGenderType(rawValue: dictionary["gender"] as! Int)! for photo in dictionary["photos"] as! [NSDictionary] { let photoURL = photo["url"] as! String let photoObject = STPhoto(photoURL: photoURL) photos.append(photoObject) } for job in dictionary["jobs"] as! [NSDictionary] { let companyId = job["company"]?["id"] as? String let companyName = job["company"]?["name"] as? String let jobId = job["title"]?["id"] as? String let jobName = job["title"]?["name"] as? String let job = STJob(companyId: companyId, company: companyName, titleId: jobId, title: jobName) jobs?.append(job) } for school in dictionary["schools"] as! [NSDictionary] { let schoolId = school["id"] as? String let schoolName = school["name"] as? String let schoolYear = school["year"] as? String let schoolType = school["type"] as? String let school = STSchool(id: schoolId, name: schoolName, year: schoolYear, type: schoolType) schools?.append(school) } } }
mit
28858f901071594615bcca9c6a433e9b
28.825243
103
0.549658
4.356028
false
false
false
false
ntwf/TheTaleClient
TheTale/Stores/PlayerInformation/AccountInformation/Hero/Position/Position.swift
1
728
// // Position.swift // the-tale // // Created by Mikhail Vospennikov on 07/07/2017. // Copyright © 2017 Mikhail Vospennikov. All rights reserved. // import Foundation class Position: NSObject { var xCoordinate: Int var yCoordinate: Int var xDirection: Int var yDirection: Int required init?(jsonObject: JSON) { guard let xCoordinate = jsonObject["x"] as? Int, let yCoordinate = jsonObject["y"] as? Int, let xDirection = jsonObject["dx"] as? Int, let yDirection = jsonObject["dy"] as? Int else { return nil } self.xCoordinate = xCoordinate self.yCoordinate = yCoordinate self.xDirection = xDirection self.yDirection = yDirection } }
mit
229ab9b75e08be6cedda4b64917c364d
21.71875
62
0.649243
3.846561
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/DiscoveryV1/Models/NluEnrichmentFeatures.swift
1
4081
/** * (C) Copyright IBM Corp. 2018, 2020. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import IBMSwiftSDKCore /** Object containing Natural Language Understanding features to be used. */ public struct NluEnrichmentFeatures: Codable, Equatable { /** An object specifying the Keyword enrichment and related parameters. */ public var keywords: NluEnrichmentKeywords? /** An object speficying the Entities enrichment and related parameters. */ public var entities: NluEnrichmentEntities? /** An object specifying the sentiment extraction enrichment and related parameters. */ public var sentiment: NluEnrichmentSentiment? /** An object specifying the emotion detection enrichment and related parameters. */ public var emotion: NluEnrichmentEmotion? /** An object that indicates the Categories enrichment will be applied to the specified field. */ public var categories: [String: JSON]? /** An object specifiying the semantic roles enrichment and related parameters. */ public var semanticRoles: NluEnrichmentSemanticRoles? /** An object specifying the relations enrichment and related parameters. */ public var relations: NluEnrichmentRelations? /** An object specifiying the concepts enrichment and related parameters. */ public var concepts: NluEnrichmentConcepts? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case keywords = "keywords" case entities = "entities" case sentiment = "sentiment" case emotion = "emotion" case categories = "categories" case semanticRoles = "semantic_roles" case relations = "relations" case concepts = "concepts" } /** Initialize a `NluEnrichmentFeatures` with member variables. - parameter keywords: An object specifying the Keyword enrichment and related parameters. - parameter entities: An object speficying the Entities enrichment and related parameters. - parameter sentiment: An object specifying the sentiment extraction enrichment and related parameters. - parameter emotion: An object specifying the emotion detection enrichment and related parameters. - parameter categories: An object that indicates the Categories enrichment will be applied to the specified field. - parameter semanticRoles: An object specifiying the semantic roles enrichment and related parameters. - parameter relations: An object specifying the relations enrichment and related parameters. - parameter concepts: An object specifiying the concepts enrichment and related parameters. - returns: An initialized `NluEnrichmentFeatures`. */ public init( keywords: NluEnrichmentKeywords? = nil, entities: NluEnrichmentEntities? = nil, sentiment: NluEnrichmentSentiment? = nil, emotion: NluEnrichmentEmotion? = nil, categories: [String: JSON]? = nil, semanticRoles: NluEnrichmentSemanticRoles? = nil, relations: NluEnrichmentRelations? = nil, concepts: NluEnrichmentConcepts? = nil ) { self.keywords = keywords self.entities = entities self.sentiment = sentiment self.emotion = emotion self.categories = categories self.semanticRoles = semanticRoles self.relations = relations self.concepts = concepts } }
apache-2.0
1171f1343d41d7b0517a5e2ffef0b38d
35.115044
113
0.705219
4.767523
false
false
false
false
gringoireDM/LNZWeakCollection
LNZWeakCollectionTests/WeakValuesDictionaryTests.swift
1
919
// // WeakValuesDictionaryTests.swift // LNZWeakCollectionTests // // Created by Giuseppe Lanza on 06/02/18. // Copyright © 2018 Giuseppe Lanza. All rights reserved. // import XCTest @testable import LNZWeakCollection class WeakValuesDictionaryTests: XCTestCase { var weakDictionary = WeakDictionary<NSString, NSObject>(withWeakRelation: .strongToWeak) func testAdd() { let key = "Name" as NSString let value = NSObject() weakDictionary[key] = value XCTAssertEqual(value, weakDictionary[key]) } func testWeakKey() { let key = "Name" as NSString var value: NSObject? = NSObject() weakDictionary[key] = value XCTAssertEqual(value, weakDictionary[key]) value = nil XCTAssertEqual(0, weakDictionary.count) XCTAssertNil(weakDictionary["Name"]) } }
mit
f3e1b8b5c42e5ca5b4b7878008bfa6ea
23.157895
92
0.62854
4.478049
false
true
false
false
niekang/WeiBo
WeiBo/Class/Utils/Extension/NSDate+Extension.swift
1
2481
// // NSDate+Extension.swift // WeiBo // // Created by 聂康 on 2017/6/23. // Copyright © 2017年 com.nk. All rights reserved. // import Foundation /// 日期格式化器 - 不要频繁的释放和创建,会影响性能 private let dateFormatter = DateFormatter() /// 当前日历对象 private let calendar = Calendar.current extension Date { /// 计算与当前系统时间偏差 delta 秒数的日期字符串 /// 在 Swift 中,如果要定义结构体的 `类`函数,使用 static 修饰 -> 静态函数 static func dateString(delta: TimeInterval) -> String { let date = Date(timeIntervalSinceNow: delta) // 指定日期格式 dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return dateFormatter.string(from: date) } /// 将新浪格式的字符串转换成日期 /// /// - parameter string: Tue Sep 15 12:12:00 +0800 2015 /// /// - returns: 日期 static func sinaDate(string: String) -> Date? { // 1. 设置日期格式 dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy" // 2. 转换并且返回日期 return dateFormatter.date(from: string) } /** 刚刚(一分钟内) X分钟前(一小时内) X小时前(当天) 昨天 HH:mm(昨天) MM-dd HH:mm(一年内) yyyy-MM-dd HH:mm(更早期) */ var dateDescription: String { // 1. 判断日期是否是今天 if calendar.isDateInToday(self) { let delta = -Int(self.timeIntervalSinceNow) if delta < 60 { return "刚刚" } if delta < 3600 { return "\(delta / 60) 分钟前" } return "\(delta / 3600) 小时前" } // 2. 其他天 var fmt = " HH:mm" if calendar.isDateInYesterday(self) { fmt = "昨天" + fmt } else { fmt = "MM-dd" + fmt let year = calendar.component(.year, from: self) let thisYear = calendar.component(.year, from: Date()) if year != thisYear { fmt = "yyyy-" + fmt } } // 设置日期格式字符串 dateFormatter.dateFormat = fmt return dateFormatter.string(from: self) } }
apache-2.0
da5360402ec7ffdd53d71f53ab97c060
22.538462
66
0.49113
3.966667
false
false
false
false
instacrate/Subber-api
Sources/App/Stripe/Models/Transfer.swift
2
4050
// // Transfer.swift // subber-api // // Created by Hakon Hanesand on 1/31/17. // // import Foundation import Node public enum SourceType: String, NodeConvertible { case alipay_account case bank_account case bitcoin_receiver case card } public enum ChargeMethod: String, NodeConvertible { case standard case instant } public enum TransferStatus: String, NodeConvertible { case pending case paid case failed case in_transit case canceled } public final class Transfer: NodeConvertible { static let type = "transfer" public let id: String public let amount: Int public let amount_reversed: Int public let application_fee: String? public let balance_transaction: String public let created: Date public let currency: Currency public let date: Date public let description: String public let destination: String public let failure_code: String? public let failure_message: String? public let livemode: Bool public let metadata: Node public let method: ChargeMethod public let recipient: Node // [TransferReversal] public let reversals: String public let reversed: Bool public let source_transaction: String? public let source_type: SourceType public let statement_descriptor: String? public let status: TransferStatus public let transfer_group: String? public let type: String public init(node: Node, in context: Context = EmptyNode) throws { guard try node.extract("object") == Transfer.type else { throw NodeError.unableToConvert(node: node, expected: Transfer.type) } id = try node.extract("id") amount = try node.extract("amount") amount_reversed = try node.extract("amount_reversed") application_fee = try node.extract("application_fee") balance_transaction = try node.extract("balance_transaction") created = try node.extract("created") currency = try node.extract("currency") date = try node.extract("date") description = try node.extract("description") destination = try node.extract("destination") failure_code = try node.extract("failure_code") failure_message = try node.extract("failure_message") livemode = try node.extract("livemode") metadata = try node.extract("metadata") method = try node.extract("method") recipient = try node.extract("recipient") reversals = try node.extract("reversals") reversed = try node.extract("reversed") source_transaction = try node.extract("source_transaction") source_type = try node.extract("source_type") statement_descriptor = try node.extract("statement_descriptor") status = try node.extract("status") transfer_group = try node.extract("transfer_group") type = try node.extract("type") } public func makeNode(context: Context = EmptyNode) throws -> Node { return try Node(node: [ "id" : id, "amount" : amount, "amount_reversed" : amount_reversed, "balance_transaction" : balance_transaction, "created" : created, "currency" : currency, "date" : date, "description" : description, "destination" : destination, "livemode" : livemode, "metadata" : metadata, "method" : method, "recipient" : recipient, "reversals" : reversals, "reversed" : reversed, "source_type" : source_type, "status" : status, "type" : type ]).add(objects: [ "application_fee" : application_fee, "source_transaction" : source_transaction, "failure_code" : failure_code, "failure_message" : failure_message, "statement_descriptor" : statement_descriptor, "transfer_group" : transfer_group ]) } }
mit
d6c162d835620dcee4a2ffe3f364df50
31.66129
80
0.623704
4.576271
false
false
false
false
sabyapradhan/IBM-Ready-App-for-Banking
HatchReadyApp/apps/Hatch/iphone/native/Hatch/DataSources/DashboardDataManager.swift
1
5469
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import Foundation /** * A shared resource manager for obtaining Business and Accounts specific data from MobileFirst Platform */ public class DashboardDataManager: NSObject{ // Callback function that will execute after the call returns var callback : ((Bool, [Business]!)->())! // Holds the business objects returned from MFP var businesses: [Business]! // Index to intiate the dashboard with var businessIndex = 0 // Class variable that will return a singleton when requested public class var sharedInstance : DashboardDataManager{ struct Singleton { static let instance = DashboardDataManager() } return Singleton.instance } /** Calls the MobileFirst Platform service :param: callback Callback to determine success */ func getDashboardData(callback: ((Bool, [Business]!)->())!){ self.callback = callback let adapterName : String = "SBBAdapter" let procedureName : String = "getDashboardData" let caller = WLProcedureCaller(adapterName : adapterName, procedureName: procedureName) let params = [] caller.invokeWithResponse(self, params: nil) var userExists = false } /** Method used for testing */ public func getDashboardDataTest(){ getDashboardData(nil) } /** Method that is fired when a retry is attempted for dashboard data. */ func retryGetDashboardData(){ getDashboardData(callback) } /** Parses MobileFirst Platform's response and returns an array of account objects. :param: worklightResponseJson JSON response from MobileFirst Platform with Dashboard data. :returns: Array of account objects. */ func parseDashboardResponse(worklightResponseJson: NSDictionary) -> [Business]{ let businessesJsonString = worklightResponseJson["result"] as! String let data = businessesJsonString.dataUsingEncoding(NSUTF8StringEncoding) let businessJsonArray = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(0), error: nil) as! [AnyObject] var businesses: [Business] = [] for businessJson in businessJsonArray as! [[String: AnyObject]] { var business = Business() business.name = (businessJson["businessName"] as! String).uppercaseString business.imageName = businessJson["imageFile"] as! String var accounts : [Account] = [] for accountJson in businessJson["accounts"] as! [[String: AnyObject]] { var account = Account() account.id = accountJson["_id"] as! String account.accountName = (accountJson["name"] as! String).uppercaseString account.accountType = AccountType.Account account.balance = accountJson["balance"] as! Float account.hasTransactions = (account.accountName == "CHECKING") || (account.accountName == "SAVINGS") accounts.append(account) } business.accounts = accounts var spendings : [Account] = [] for spendingJson in businessJson["spending"] as! [[String: AnyObject]] { var spending = Account() spending.id = spendingJson["_id"] as! String spending.accountName = (spendingJson["name"] as! String).uppercaseString spending.accountType = AccountType.Spending spending.balance = spendingJson["balance"] as! Float spendings.append(spending) } business.spendings = spendings businesses.append(business) } return businesses } } extension DashboardDataManager: WLDataDelegate{ /** Delegate method for MobileFirst Platform. Called when connection and return is successful :param: response Response from MobileFirst Platform */ public func onSuccess(response: WLResponse!) { let responseJson = response.getResponseJson() as NSDictionary // Parse JSON response into dashboard format and store in accounts businesses = parseDashboardResponse(responseJson) // Execute the callback from the view controller that instantiated the dashboard call callback(true, businesses) } /** Delegate method for MobileFirst Platform. Called when connection or return is unsuccessful :param: response Response from MobileFirst Platform */ public func onFailure(response: WLFailResponse!) { MQALogger.log("Response: \(response.responseText)") if (response.errorCode.value == 0) { MILAlertViewManager.sharedInstance.show("Can not connect to the server, click to refresh", callback: retryGetDashboardData) } callback(false, nil) } /** Delegate method for MobileFirst Platform. Task to do before executing a call. */ public func onPreExecute() { } /** Delegate method for MobileFirst Platform. Task to do after executing a call. */ public func onPostExecute() { } }
epl-1.0
7b2719f91beb7711b9372eec0903e7e3
33.18125
140
0.626554
5.54002
false
false
false
false
richardpiazza/CodeQuickKit
Sources/CodeQuickKit/Foundation/Date+Semantic.swift
1
2338
import Foundation public extension Date { /// Provides the current timestamp minus 24 hours. static var yesterday: Date { return Date().dateByAdding(days: -1)! } /// Provides the current timestamp minus 48 hours. static var twoDaysAgo: Date { return Date().dateByAdding(days: -2)! } /// Provides the current timestamp minus 7 days. static var lastWeek: Date { return Date().dateByAdding(days: -7)! } /// Provides the current timestamp plus 24 hours. static var tomorrow: Date { return Date().dateByAdding(days: 1)! } /// Provides the current timestamp plus 48 days. static var dayAfterTomorrow: Date { return Date().dateByAdding(days: 2)! } /// Provides the current timestamp plus 7 days. static var nextWeek: Date { return Date().dateByAdding(days: 7)! } /// Determines if the instance date is before the reference date (second granularity). func isBefore(_ date: Date) -> Bool { return Calendar.current.compare(self, to: date, toGranularity: .second) == .orderedAscending } /// Determines if the instance date is after the reference date (second granularity). func isAfter(_ date: Date) -> Bool { return Calendar.current.compare(self, to: date, toGranularity: .second) == .orderedDescending } /// Determines if the instance date is equal to the reference date (second granularity). func isSame(_ date: Date) -> Bool { return Calendar.current.compare(self, to: date, toGranularity: .second) == .orderedSame } /// Uses `Calendar` to return the instance date mutated by the specified number of minutes. func dateByAdding(minutes value: Int) -> Date? { return Calendar.current.date(byAdding: .minute, value: value, to: self) } /// Uses `Calendar` to return the instance date mutated by the specified number of hours. func dateByAdding(hours value: Int) -> Date? { return Calendar.current.date(byAdding: .hour, value: value, to: self) } /// Uses `Calendar` to return the instance date mutated by the specified number of days. func dateByAdding(days value: Int) -> Date? { return Calendar.current.date(byAdding: .day, value: value, to: self) } }
mit
e25b07687618faef168343c58f054406
36.111111
101
0.648417
4.557505
false
false
false
false
pebble8888/PBKit
PBKit/String+PBURLSafeBase64.swift
1
2029
// // String+PBURLSafeBase64.swift // PBKit // // Created by pebble8888 on 2017/01/09. // Copyright © 2017年 pebble8888. All rights reserved. // import Foundation extension String { fileprivate static let table:[UInt8] = { let str:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=" return str.utf8.map { UInt8($0) } }() /** * @note URL safe base64 * RFC4648 no LF 62th:+ 63th:/ =padding(4 multiple) * * @note Base64 class in Ruby * strict_decode64, strict_encode64 : RFC 4648 no LF 62th:+ 63th:/ * urlsafe_decode64, urlsafe_encode64 : RFC 4648 no LF 62th:- 64th:_ */ public func base64UrlSafe() -> String { let input = self.utf8 let length = input.count var data: Data = Data() // process by 3 bytes(24bit=6bit*3) for i in stride(from:0, to: length, by: 3) { var value:Int = 0 for j in stride(from: i, to: i+3, by: 1) { value <<= 8 if j < length { value |= (0xFF & Int(input[input.index(input.startIndex, offsetBy: j)])) } } // 0x3F = 63 data.append( String.table[(value >> 18) & 0x3F]) data.append( String.table[(value >> 12) & 0x3F]) data.append((i + 1) < length ? String.table[(value >> 6) & 0x3F] : "=".utf8.first!) data.append((i + 2) < length ? String.table[(value >> 0) & 0x3F] : "=".utf8.first!) } guard let retStr = String(data: data, encoding: .utf8) else { return "" } return retStr } public func base64() -> String { return Data(self.utf8).base64EncodedString() } /** * @brief remove = at end */ public func base64UrlSafeNoEqual() -> String { let str = self.base64UrlSafe() return str.replacingOccurrences(of: "=", with: "") } }
mit
a821bec96c7866553852da10cfac1f70
32.213115
96
0.522211
3.65045
false
false
false
false
carlo-/ipolito
iPoliTO2/Constants.swift
1
1388
// // Constants.swift // iPoliTO2 // // Created by Carlo Rapisarda on 22/08/2016. // Copyright © 2016 crapisarda. All rights reserved. // struct PTConstants { static let demoAccount = PTAccount(rawStudentID: "s000000", password: "iPoliTO_demo") // MUST be set to false for production static let alwaysAskToLogin = false // MUST be set to false for production static let alwaysShowWhatsNewMessage = false // MUST be set to false for production static let alwaysActAsFirstExecution = false // MUST be set to false for production static let shouldForceDebugAccount = false // MUST be set to false for production static let jumpstart = false static let debugAccount: PTAccount = demoAccount static let appStoreReviewLink = "http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=1069740093&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8" static let gitHubLink = "https://github.com/carlo-/ipolito" static let gitHubReadmeLink = "https://github.com/carlo-/ipolito/blob/master/README.md#ipolito" static let appStoreLink = "https://itunes.apple.com/us/app/ipolito-per-iphone/id1069740093?mt=8" static let feedbackEmail = "[email protected]" static let releaseVersionOfLastExecutionKey = "releaseVersionOfLastExecution" }
gpl-3.0
b1e367a9be841842c208a396a2570799
32.829268
179
0.715934
3.842105
false
false
false
false
c98/AppMateServer
Sources/sessions.swift
1
9512
// // sessions.swift // PerfectTemplate // // Created by 止水 on 1/3/17. // // import Foundation import PerfectWebSockets /// 会话管理模块 class Session: ModuleProtocol { enum DBError: Error { case CreateOutputStreamFailed case CreateInputStreamFailed } struct SessionElement { var session_id: String var device_name: String var did: String var app_name: String var app_version: String var platform: String var os_version: String var connect_time: String var connect_status: Int var socket: WebSocket? } var sessions: [SessionElement] = [] var active_session_count: Int = 0 var hearbeat_ack_sessions: [String] = [] var timer: DispatchSourceTimer? = nil var checkTimer: DispatchSourceTimer? = nil func sessionsInfo() -> [[String:Any]] { return self.sessions.map { [ "session_id": $0.session_id, "device_name": $0.device_name, "did": $0.did, "app_name": $0.app_name, "app_version": $0.app_version, "platform": $0.platform, "os_version": $0.os_version, "connect_time": $0.connect_time, "connect_status": $0.connect_status ] } } init() { try? self.loadSessions() self.heartBeat() } func loadSessions() throws { guard let input = InputStream.init(fileAtPath: "./sessions.json") else { throw DBError.CreateInputStreamFailed } input.open() guard let sessions = try? JSONSerialization.jsonObject(with: input, options: []) as? [[String:Any]] else { return } for session in sessions! { guard let session_id = session["session_id"] as? String else { return } guard let device_name = session["device_name"] as? String else { return } guard let did = session["did"] as? String else { return } guard let app_name = session["app_name"] as? String else { return } guard let app_version = session["app_version"] as? String else { return } guard let platform = session["platform"] as? String else { return } guard let os_version = session["os_version"] as? String else { return } guard let connect_time = session["connect_time"] as? String else { return } let connect_status = 0 let sessionElement = SessionElement.init(session_id: session_id, device_name: device_name, did: did, app_name: app_name, app_version: app_version, platform: platform, os_version: os_version, connect_time: connect_time, connect_status: connect_status, socket: nil) self.sessions.append(sessionElement) } } func saveSessions() throws { self.syncSessionCount() if self.sessions.count == 0 { return } var index = 0 for i in (0..<self.sessions.count).reversed() { let session = self.sessions[i] let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" if let date = dateFormatter.date(from: session.connect_time) { if Date().timeIntervalSince(date) <= 1000*60*60*24*3 { index = i break } } } self.sessions = Array(self.sessions.prefix(through: index)) guard let output = OutputStream.init(toFileAtPath: "./sessions.json", append: false) else { throw DBError.CreateOutputStreamFailed } output.open() JSONSerialization.writeJSONObject(self.sessionsInfo(), to: output, options: [JSONSerialization.WritingOptions.prettyPrinted], error: nil) let msg: [String:Any] = ["topic":"session.list", "session_id":"*:*:*", "payload":self.sessionsInfo()] SubscribeCenter.sharedInstance.notify(message: msg) } func syncSessionCount() { var active_session_count = 0 for session in self.sessions { if session.connect_status == 1 { active_session_count += 1 } } self.active_session_count = active_session_count } func heartBeat() { self.timer = DispatchSource.makeTimerSource() self.timer?.scheduleRepeating(deadline: DispatchTime.now(), interval: 10) self.timer?.resume() self.timer?.setEventHandler { self.hearbeat_ack_sessions = [] for session in self.sessions { if session.connect_status == 0 { continue } let msg = [ "publish":[ "topic":"HeartBeat.SYN", "session_id":session.session_id ] ] guard let content = String.init(data: try! JSONSerialization.data(withJSONObject: msg), encoding: String.Encoding.utf8) else { assert(false) break } session.socket!.sendStringMessage(string: content, final: true) {} } self.checkTimer = DispatchSource.makeTimerSource() self.checkTimer?.scheduleOneshot(deadline: DispatchTime.now() + .seconds(5)) self.checkTimer?.resume() self.checkTimer?.setEventHandler { var index = 0 while index < self.sessions.count { var session = self.sessions[index] if session.connect_status == 0 { index += 1 continue } if self.hearbeat_ack_sessions.index(of: session.session_id) != nil { if session.connect_status != 1 { session.connect_status = 1 self.sessions.remove(at: index) self.sessions.insert(session, at: 0) } } else { if session.connect_status != 2 { session.connect_status = 2 self.sessions.insert(session, at: self.active_session_count) self.sessions.remove(at: index) } } self.syncSessionCount() index += 1 } try? self.saveSessions() } } } func onHeartBeat_ACK(socket:WebSocket, topic:String, sessionId:String, message:[String:Any]) { self.hearbeat_ack_sessions.append(sessionId) } func handleEvent(socket: WebSocket, action: String, topic: String, sessionId: String, message: [String : Any]) { switch action { case "publish": self.onPublish(socket: socket, topic: topic, sessionId: sessionId, message: message) case "subscribe": self.onSubscribe(socket: socket, topic: topic, sessionId: sessionId, message: message) default: break } } func onPublish(socket: WebSocket, topic: String, sessionId: String, message: [String:Any]) { switch topic { case "App.Start.Log": self.onConnect(socket: socket, topic: topic, sessionId: sessionId, message: message) case "App.End.Log": self.onDisconnect(socket: socket, topic: topic, sessionId: sessionId, message: message) case "HeartBeat.ACK": self.onHeartBeat_ACK(socket: socket, topic: topic, sessionId: sessionId, message: message) default: break } } func onSubscribe(socket: WebSocket, topic: String, sessionId: String, message: [String:Any]) { if topic != "session.list" { return } let msg = ["publish": [ "topic":topic, "session_id": sessionId, "payload": self.sessionsInfo() ]] guard let content = String.init(data: try! JSONSerialization.data(withJSONObject: msg), encoding: String.Encoding.utf8) else { return } socket.sendStringMessage(string: content, final: true) {} } func onConnect(socket: WebSocket, topic: String, sessionId: String, message: [String:Any]) { guard let payload = message["payload"] as? [String:Any] else { return } guard let deviceName = payload["deviceName"] as? String else { return } guard let platform = payload["platform"] as? String else { return } guard let osVersion = payload["osVersion"] as? String else { return } let connectTime = format_date() var isExisted = false for (index, var session) in self.sessions.enumerated() { if session.session_id == sessionId { session.connect_time = connectTime session.connect_status = 1 session.socket = socket session.device_name = deviceName isExisted = true self.sessions.remove(at: index) self.sessions.insert(session, at: 0) self.hearbeat_ack_sessions.append(sessionId) break } } if !isExisted { let sessionIdComps = sessionId.characters.split(separator: ":").map(String.init) let did = sessionIdComps[0] let appName = sessionIdComps[1] let appVersion = sessionIdComps[2] self.sessions.insert(SessionElement(session_id: sessionId, device_name: deviceName, did: did, app_name: appName, app_version: appVersion, platform: platform, os_version: osVersion, connect_time: connectTime, connect_status: 1, socket: socket), at: 0) } try? self.saveSessions() } func onDisconnect(socket: WebSocket, topic: String, sessionId: String, message: [String:Any]) { SubscribeCenter.sharedInstance.unsubscribeAll(socket: socket) var not_found = true for (index, var session) in self.sessions.enumerated() { if let sock = session.socket, sock == socket { if session.connect_status == 1 { session.connect_status = 0 self.sessions.insert(session, at: self.active_session_count) self.sessions.remove(at: index) } not_found = false break } } if not_found { return } try? self.saveSessions() } }
apache-2.0
b049d5c47e70e90253e77722f3f7b04b
29.242038
139
0.618366
3.660756
false
false
false
false