repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
danielctull-forks/onepassword-app-extension
refs/heads/master
Demos/WebView Demo for iOS Swift/WebView Demo for iOS Swift/WebViewController.swift
mit
1
// // WebViewController.swift // WebView Demo for iOS Swift // // Created by Rad Azzouz on 2015-05-14. // Copyright (c) 2015 AgileBits Inc. All rights reserved. // import UIKit class WebViewController: UIViewController, UISearchBarDelegate, WKNavigationDelegate { @IBOutlet weak var onepasswordFillButton: UIButton! @IBOutlet weak var webViewContainer: UIView! @IBOutlet weak var searchBar: UISearchBar! @IBOutlet var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() self.onepasswordFillButton.hidden = (false == OnePasswordExtension.sharedExtension().isAppExtensionAvailable()) let configuration = WKWebViewConfiguration() self.webView = WKWebView(frame: self.webViewContainer.bounds, configuration: configuration) self.webView.autoresizingMask = UIViewAutoresizing(arrayLiteral: .FlexibleHeight, .FlexibleWidth) self.webView.navigationDelegate = self self.webViewContainer.addSubview(self.webView) let htmlFilePath = NSBundle.mainBundle().pathForResource("welcome", ofType: "html") var htmlString : String! do { htmlString = try String(contentsOfFile: htmlFilePath!, encoding: NSUTF8StringEncoding) } catch { print("Failed to obtain the html string from file \(htmlFilePath) with error: <\(error)>") } self.webView.loadHTMLString(htmlString, baseURL: NSURL(string: "https://agilebits.com")) } @IBAction func fillUsing1Password(sender: AnyObject) -> Void { OnePasswordExtension.sharedExtension().fillItemIntoWebView(self.webView, forViewController: self, sender: sender, showOnlyLogins: false) { (success, error) -> Void in if success == false { print("Failed to fill into webview: <\(error)>") } } } @IBAction func goBack(sender: AnyObject) -> Void { let navigation = self.webView.goBack() if navigation == nil { let htmlFilePath = NSBundle.mainBundle().pathForResource("welcome", ofType: "html") var htmlString : String! do { htmlString = try String(contentsOfFile: htmlFilePath!, encoding: NSUTF8StringEncoding) } catch { print("Failed to obtain the html string from file \(htmlFilePath) with error: <\(error)>") } self.webView.loadHTMLString(htmlString, baseURL: NSURL(string: "https://agilebits.com")) } } @IBAction func goForward(sender: AnyObject) -> Void { self.webView.goForward() } // UISearchBarDelegate func searchBarSearchButtonClicked(searchBar: UISearchBar) { self.performSearch(searchBar.text) } func searchBarTextDidEndEditing(searchBar: UISearchBar) { self.performSearch(searchBar.text) } func handleSearch(searchBar: UISearchBar) { self.performSearch(searchBar.text) } func searchBarCancelButtonClicked(searchBar: UISearchBar) { self.performSearch(searchBar.text) } // Convenience func performSearch(text: String!) { let lowercaseText = text.lowercaseStringWithLocale(NSLocale.currentLocale()) var URL: NSURL? let hasSpaces = lowercaseText.rangeOfString(" ") != nil let hasDots = lowercaseText.rangeOfString(".") != nil let search: Bool = !hasSpaces || !hasDots if (search) { let hasScheme = lowercaseText.hasPrefix("http:") || lowercaseText.hasPrefix("https:") if (hasScheme) { URL = NSURL(string: lowercaseText) } else { URL = NSURL(string: "https://".stringByAppendingString(lowercaseText)) } } if (URL == nil) { let URLComponents = NSURLComponents() URLComponents.scheme = "https" URLComponents.host = "www.google.com" URLComponents.path = "/search" let queryItem = NSURLQueryItem(name: "q", value: text) URLComponents.queryItems = [queryItem] URL = URLComponents.URL } self.searchBar.text = URL?.absoluteString self.searchBar.resignFirstResponder() let request = NSURLRequest(URL: URL!) self.webView.loadRequest(request) } // WKNavigationDelegate func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { self.searchBar.text = webView.URL?.absoluteString if self.searchBar.text == "about:blank" { self.searchBar.text = "" } } }
3a4d845a225bce5ba03a0cf3000167ac
29.134328
168
0.731303
false
false
false
false
sishenyihuba/Weibo
refs/heads/master
Weibo/05-Tools/Utils/NetworkTools.swift
mit
1
// // NetworkTools.swift // 06-AFNetworking的封装 // // Created by daixianglong on 16/4/6. // Copyright . All rights reserved. // import AFNetworking // 定义枚举类型 enum RequestType : String { case GET = "GET" case POST = "POST" } class NetworkTools: AFHTTPSessionManager { // let是线程安全的 static let shareInstance : NetworkTools = { let tools = NetworkTools() tools.responseSerializer.acceptableContentTypes?.insert("text/html") tools.responseSerializer.acceptableContentTypes?.insert("text/plain") return tools }() } // MARK:- 封装请求方法 extension NetworkTools { func request(methodType : RequestType, urlString : String, parameters : [String : AnyObject], finished : (result : AnyObject?, error : NSError?) -> ()) { // 1.定义成功的回调闭包 let successCallBack = { (task : NSURLSessionDataTask, result : AnyObject?) -> Void in finished(result: result, error: nil) } // 2.定义失败的回调闭包 let failureCallBack = { (task : NSURLSessionDataTask?, error : NSError) -> Void in finished(result: nil, error: error) } // 3.发送网络请求 if methodType == .GET { GET(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack) } else { POST(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack) } } } // MARK:- 请求AccessToken extension NetworkTools { func loadAccessToken(code : String, finished : (result : [String : AnyObject]?, error : NSError?) -> ()) { // 1.获取请求的URLString let urlString = "https://api.weibo.com/oauth2/access_token" // 2.获取请求的参数 let parameters = ["client_id" : app_key, "client_secret" : secret_key, "grant_type" : "authorization_code", "redirect_uri" : callback_url, "code" : code] // 3.发送网络请求 request(.POST, urlString: urlString, parameters: parameters) { (result, error) -> () in finished(result: result as? [String : AnyObject], error: error) } } } // MARK:- 请求用户的信息 extension NetworkTools { func loadUserInfo(userAccount:UserAccount,completionHandler:(result:[String:AnyObject]?,error:NSError?)->()) { guard let access_token = userAccount.access_token else { return } guard let uid = userAccount.uid else { return } let parameters = ["access_token" : access_token, "uid" : uid] request(.GET, urlString: "https://api.weibo.com/2/users/show.json", parameters: parameters) { (result, error) in completionHandler(result: result as? [String:AnyObject], error: error) } } } //MARK: - 请求微博数据 extension NetworkTools { func loadStatuses(since_id :Int,max_id :Int, completionHandler:(result:[[String:AnyObject]]?, error:NSError?)->()) { let urlString = "https://api.weibo.com/2/statuses/home_timeline.json" let parameters = ["access_token" : (UserAccountViewModel.sharedInstance.account?.access_token)!, "since_id" : since_id,"max_id" : max_id] request(.GET, urlString: urlString, parameters: parameters as! [String : AnyObject]) { (result, error) in guard let resultDict = result as? [String:AnyObject] else { return } completionHandler(result: resultDict["statuses"] as? [[String:AnyObject]], error: error) } } } //MARK: - 发送微博 extension NetworkTools { func sendStatus(statusText : String, isSuccess : (isSuccess : Bool) -> ()) { // 1.获取请求的URLString let urlString = "https://api.weibo.com/2/statuses/update.json" // 2.获取请求的参数 let parameters = ["access_token" : (UserAccountViewModel.sharedInstance.account?.access_token)!, "status" : statusText] // 3.发送网络请求 request(.POST, urlString: urlString, parameters: parameters) { (result, error) -> () in if result != nil { isSuccess(isSuccess: true) } else { isSuccess(isSuccess: false) } } } } // MARK:- 发送微博并且携带照片 extension NetworkTools { func sendStatus(statusText : String, image : UIImage, isSuccess : (isSuccess : Bool) -> ()) { // 1.获取请求的URLString let urlString = "https://api.weibo.com/2/statuses/upload.json" // 2.获取请求的参数 let parameters = ["access_token" : (UserAccountViewModel.sharedInstance.account?.access_token)!, "status" : statusText] // 3.发送网络请求 POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in if let imageData = UIImageJPEGRepresentation(image, 0.5) { formData.appendPartWithFileData(imageData, name: "pic", fileName: "123.png", mimeType: "image/png") } }, progress: nil, success: { (_, _) -> Void in isSuccess(isSuccess: true) }) { (_, error) -> Void in print(error) } } }
77b7d7032bf2febb6496b1898f1101c5
33.736486
161
0.596771
false
false
false
false
evan-liu/CommandArguments
refs/heads/master
Doc.playground/Pages/Basic.xcplaygroundpage/Contents.swift
mit
1
import Foundation import CommandArguments struct BuildArguments: CommandArguments { var platform = Operand() var version = Option() var clean = Flag() } var buildArgs = BuildArguments() do { try buildArgs.parse("build ios --version=1.0 --clean", from: 1) } catch { print(error) } buildArgs.platform.value // "ios" buildArgs.version.value // "1.0" buildArgs.clean.value // true //: [Next](@next)
ff4dfd4291cfe26c5583e34b1160b43f
19.571429
67
0.663573
false
false
false
false
elationfoundation/Reporta-iOS
refs/heads/master
IWMF/ViewControllers/CheckInViewController/CheckinNotificationViewController.swift
gpl-3.0
1
// // checkinNotificationViewController.swift // IMWF // // This class is used for display reminders about Check-in like Confirmation, Check-in started, Check-in closed etc. // // import UIKit import CoreLocation enum CheckInNotificationType : Int{ case ConfirmationReminder = 4 case ConfirmNow = 3 case StartReminder = 2 case StartNow = 1 case CloseReminder = 5 case CloseNow = 6 } class CheckinNotificationViewController: UIViewController, MediaDetailProtocol, WSClientDelegate ,CheckInModalProtocol{ @IBOutlet weak var textView: UITextView! @IBOutlet weak var verticalSpaceCloseCheckin_editCheckin: NSLayoutConstraint! @IBOutlet weak var verticalSpaceFullLines: NSLayoutConstraint! @IBOutlet weak var verticalSpaceFullLine_Button: NSLayoutConstraint! @IBOutlet weak var verticalSpacereporta_notif: NSLayoutConstraint! @IBOutlet weak var confirmButton: UIButton! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var lblReporta: UILabel! @IBOutlet weak var btnAddMedia : UIButton! @IBOutlet weak var btnEditCheckIn : UIButton! @IBOutlet weak var verticleSpaceBtn_TextView: NSLayoutConstraint! var notiType : CheckInNotificationType! var checkInpassword : NSString! var checkInID : NSNumber! var checkIn : CheckIn! var userLocation : CLLocation! = nil var arrMedia : NSMutableArray! // MARK:- LifeCycle Methods override func viewDidLoad() { super.viewDidLoad() Structures.Constant.appDelegate.hideSOSButton() btnAddMedia.setTitle(NSLocalizedString(Utility.getKey("addmedia"),comment:""), forState: .Normal) btnEditCheckIn.setTitle(NSLocalizedString(Utility.getKey("edit_checkin"),comment:""), forState: .Normal) btnAddMedia.contentVerticalAlignment = UIControlContentVerticalAlignment.Center btnEditCheckIn.contentVerticalAlignment = UIControlContentVerticalAlignment.Center lblReporta.text=NSLocalizedString(Utility.getKey("reporta"),comment:"") if CheckIn.isAnyCheckInActive() { checkIn = CheckIn() checkIn = CheckIn.getCurrentCheckInObject() } notifications() arrMedia = NSMutableArray() Structures.Constant.appDelegate.commonLocation.getUserCurrentLocation() NSNotificationCenter.defaultCenter().addObserver(self, selector: "locationUpdate:", name:Structures.Constant.LocationUpdate, object: nil) Structures.Constant.appDelegate.initializeSOSButton() } override func viewWillAppear(animated: Bool) { Structures.Constant.appDelegate.showSOSButton() super.viewWillAppear(animated) } override func viewWillDisappear(animated: Bool) { Structures.Constant.appDelegate.showSOSButton() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func locationUpdate(notification: NSNotification) { userLocation = notification.object as! CLLocation! } // MARK:-Notification Screen Methods func notifications() { if self.notiType == .ConfirmationReminder{ self.textView.text = NSLocalizedString(Utility.getKey("confirm_checkin_in_10min"),comment:"") self.confirmButton.setTitle(NSLocalizedString(Utility.getKey("confirm_now"),comment:""), forState: .Normal) self.closeButton.setTitle(NSLocalizedString(Utility.getKey("close_checkin"),comment:""), forState: .Normal) self.confirmButton.setTitleColor(UIColor.orangeColor(), forState: .Normal) self.closeButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) self.textView.textColor = UIColor.whiteColor() self.textView.textAlignment = NSTextAlignment.Center //fonts self.confirmButton.setTitleColor(UIColor.orangeColor(), forState: .Normal) self.closeButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) self.textView.textColor = UIColor.whiteColor() self.textView.textAlignment = NSTextAlignment.Center self.confirmButton.titleLabel?.font = Utility.setFont() self.closeButton.titleLabel?.font = Utility.setFont() self.textView.font = Utility.setFont() }else if self.notiType == .ConfirmNow{ self.textView.text = NSLocalizedString(Utility.getKey("confirm_checkin_now"),comment:"") self.confirmButton.setTitle(NSLocalizedString(Utility.getKey("confirm_now"),comment:""), forState: .Normal) self.closeButton.setTitle(NSLocalizedString(Utility.getKey("close_checkin"),comment:""), forState: .Normal) self.confirmButton.setTitleColor(UIColor.orangeColor(), forState: .Normal) self.closeButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) self.textView.textColor = UIColor.whiteColor() self.textView.textAlignment = NSTextAlignment.Center self.confirmButton.titleLabel?.font = Utility.setFont() self.closeButton.titleLabel?.font = Utility.setFont() self.textView.font = Utility.setFont() }else if self.notiType == .StartReminder { self.textView.text = NSLocalizedString(Utility.getKey("scheduled_checkin_begins_10min"),comment:"") self.confirmButton.setTitle(NSLocalizedString(Utility.getKey("start_now"),comment:""), forState: .Normal) self.closeButton.setTitle(NSLocalizedString(Utility.getKey("cancel_checkin"),comment:""), forState: .Normal) self.closeButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) self.textView.textColor = UIColor.whiteColor() self.textView.textAlignment = NSTextAlignment.Center self.confirmButton.titleLabel?.font = Utility.setFont() self.closeButton.titleLabel?.font = Utility.setFont() self.textView.font = Utility.setFont() }else if self.notiType == .StartNow{ self.textView.text = NSLocalizedString(Utility.getKey("checkin_started"),comment:"") self.confirmButton.setTitle(NSLocalizedString(Utility.getKey("started"),comment:""), forState: .Normal) self.confirmButton.hidden = true self.closeButton.setTitle(NSLocalizedString(Utility.getKey("Ok"),comment:""), forState: .Normal) self.confirmButton.setTitleColor(UIColor.orangeColor(), forState: .Normal) self.closeButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) self.textView.textColor = UIColor.whiteColor() self.textView.textAlignment = NSTextAlignment.Center self.confirmButton.titleLabel?.font = Utility.setFont() self.closeButton.titleLabel?.font = Utility.setFont() self.textView.font = Utility.setFont() } else if self.notiType == .CloseReminder { self.textView.text = NSLocalizedString(Utility.getKey("checkin_closed_10min"),comment:"") self.confirmButton.setTitle(NSLocalizedString(Utility.getKey("closenow"),comment:""), forState: .Normal) self.closeButton.setTitle(NSLocalizedString(Utility.getKey("update_end_time"),comment:""), forState: .Normal) self.confirmButton.setTitleColor(UIColor.orangeColor(), forState: .Normal) self.closeButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) self.textView.textColor = UIColor.whiteColor() self.textView.textAlignment = NSTextAlignment.Center self.confirmButton.titleLabel?.font = Utility.setFont() self.closeButton.titleLabel?.font = Utility.setFont() self.textView.font = Utility.setFont() } else if self.notiType == .CloseNow { btnAddMedia.enabled = false btnEditCheckIn.enabled = false self.textView.text = NSLocalizedString(Utility.getKey("checkin_closed"),comment:"") self.confirmButton.setTitle("", forState: .Normal) self.confirmButton.hidden = true self.closeButton.setTitle(NSLocalizedString(Utility.getKey("Ok"),comment:""), forState: .Normal) self.confirmButton.setTitleColor(UIColor.orangeColor(), forState: .Normal) self.closeButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) self.textView.textColor = UIColor.whiteColor() self.textView.textAlignment = NSTextAlignment.Center self.confirmButton.titleLabel?.font = Utility.setFont() self.closeButton.titleLabel?.font = Utility.setFont() self.textView.font = Utility.setFont() CheckIn.removeActiveCheckInObject() } } @IBAction func editAction(sender: AnyObject) { let CheckInScreen : CheckInViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("CheckInViewController") as! CheckInViewController showViewController(CheckInScreen, sender: self.view) } @IBAction func addAction(sender: AnyObject) { let mediaPickerScreen : MediaPickerViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MediaPickerViewController") as! MediaPickerViewController mediaPickerScreen.delegate = self mediaPickerScreen.mediaFor = .CheckIn showViewController(mediaPickerScreen, sender: self.view) } func dictStatusCheckIn(checkIN : CheckIn, status : NSNumber) -> NSDictionary{ var latitude : NSNumber = 0 var longitude : NSNumber = 0 if userLocation != nil { latitude = NSNumber(double: userLocation.coordinate.latitude) longitude = NSNumber(double: userLocation.coordinate.longitude) } let dictionary = [ Structures.CheckIn.CheckIn_ID : checkIN.checkInID, Structures.Constant.Latitude : latitude, Structures.Constant.Longitude : longitude, Structures.Constant.Status : status, Structures.Constant.TimezoneID : NSTimeZone.systemTimeZone().description, Structures.Constant.Time : Utility.getUTCFromDate() ] return dictionary } //MARK: - Media Picker Delegate Method func addMedia(mediaObject : Media){ self.arrMedia.addObject(mediaObject) } func uploadMediaIfAny(){ let totalCnt : Int = self.arrMedia.count var uploadingSuccessFully : Bool = true for _ in self.arrMedia{ if !uploadingSuccessFully{ break } dispatch_async(dispatch_get_main_queue(), { () -> Void in let strIndi : String = String(format: NSLocalizedString(Utility.getKey("uploading_of"),comment:""), totalCnt+1 - self.arrMedia.count, totalCnt) SVProgressHUD.showWithStatus(strIndi, maskType: 4) }) let tempMedia : Media = self.arrMedia[0] as! Media tempMedia.notificationID = self.checkIn.checkInID Media.sendMediaObject(tempMedia, completionClosure: { (isSuccess) -> Void in if isSuccess == true { // Delete from directory if tempMedia.mediaType == MediaType.Video { CommonUnit.deleteSingleFile(tempMedia.name, fromDirectory: "/Media/") } else if tempMedia.mediaType == MediaType.Image { CommonUnit.deleteSingleFile(tempMedia.name, fromDirectory: "/Media/") } else if tempMedia.mediaType == MediaType.Audio { CommonUnit.deleteSingleFile(tempMedia.name, fromDirectory: "/Media/") } self.arrMedia.removeObjectAtIndex(0) } else{ // add in pending array uploadingSuccessFully = false self.appendPendingMedia() let alert = UIAlertController(title: NSLocalizedString(Utility.getKey("failed_to_upload_all_media"),comment:""), message: "", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: NSLocalizedString(Utility.getKey("Ok"),comment:""), style: .Default, handler: { action in self.backToHomeScreen() })) self.presentViewController(alert, animated: true, completion: nil) } if self.arrMedia.count == 0 { dispatch_async(dispatch_get_main_queue(), { () -> Void in SVProgressHUD.show() //All Media Sent Successfully let dic : NSMutableDictionary = NSMutableDictionary() dic [Structures.Media.ForeignID] = self.checkIn.checkInID dic [Structures.Media.TableID] = NotificationType.CheckIn.rawValue let wsObj : WSClient = WSClient() wsObj.delegate = self wsObj.sendMailWithMedia(dic) }) } }) } } func appendPendingMedia() { if self.checkIn.mediaArray.count > 0 { let arrStore : NSMutableArray = NSMutableArray() for (var i : Int = 0; i < self.arrMedia.count ; i++) { let tempMedia : Media = self.arrMedia[i] as! Media tempMedia.notificationID = self.checkIn.checkInID arrStore.addObject(tempMedia) } let userName = String(format: "%@", Structures.Constant.appDelegate.prefrence.LoggedInUser) CommonUnit.appendDataWithKey(KEY_PENDING_MEDIA, inFile: userName , list: arrStore) SVProgressHUD.dismiss() } } //MARK:- Confirm Button Actions @IBAction func confirmButton(sender: AnyObject) { if self.notiType == .ConfirmationReminder { confirmCheckIn() } else if self.notiType == .ConfirmNow { confirmCheckIn() } else if self.notiType == .StartReminder { startCheckIn() } else if self.notiType == .CloseReminder { closeCheckIn() } } func confirmCheckIn() { SVProgressHUD.showWithStatus(NSLocalizedString(Utility.getKey("confirming_checkin"),comment:""), maskType: 4) CheckIn.updateCheckInStatus(NSMutableDictionary(dictionary:self.dictStatusCheckIn(checkIn, status : NSNumber(integer : 2)))) CheckIn.sharedInstance.delegate = self } func startCheckIn(){ SVProgressHUD.showWithStatus(NSLocalizedString(Utility.getKey("starting_checkin"),comment:""), maskType: 4) CheckIn.updateCheckInStatus(NSMutableDictionary(dictionary:self.dictStatusCheckIn(checkIn, status : NSNumber(integer : 1)))) CheckIn.sharedInstance.delegate = self } func cancelCheckIn(){ let alertController = UIAlertController(title: NSLocalizedString(Utility.getKey("Enter Password"),comment:""), message: NSLocalizedString(Utility.getKey("enter_pass_to_deactive_acheckin"),comment:""), preferredStyle: .Alert) alertController.addTextFieldWithConfigurationHandler { (textField) in textField.placeholder = NSLocalizedString(Utility.getKey("Password"),comment:"") textField.secureTextEntry = true if Structures.Constant.appDelegate.isArabic == true { textField.textAlignment = NSTextAlignment.Right } else { textField.textAlignment = NSTextAlignment.Left } } let okAction = UIAlertAction(title: NSLocalizedString(Utility.getKey("Ok"),comment:""), style: .Default) { (_) in let tfPassword = alertController.textFields![0] let password : NSString = tfPassword.text! self.checkInpassword = tfPassword.text if password.length>0{ SVProgressHUD.showWithStatus(NSLocalizedString(Utility.getKey("canceling_checkin"),comment:""), maskType: 4) CheckIn.updateCheckInStatus(NSMutableDictionary(dictionary:self.dictCloseStatusCheckIn(self.checkIn, status : NSNumber(integer : 3)))) CheckIn.sharedInstance.delegate = self }else{ let title = NSLocalizedString(Utility.getKey("confirmation"),comment:"") let message = NSLocalizedString(Utility.getKey("failed_to_cancel_checkin"),comment:"") let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: NSLocalizedString(Utility.getKey("Ok"),comment:""), style: .Cancel) { (action) in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.backToHomeScreen() }) } alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } } let cancelAction = UIAlertAction(title: NSLocalizedString(Utility.getKey("Cancel"),comment:""), style: .Cancel) { (action) in } if Structures.Constant.appDelegate.isArabic == true { alertController.addAction(cancelAction) alertController.addAction(okAction) } else { alertController.addAction(okAction) alertController.addAction(cancelAction) } self.presentViewController(alertController, animated: true, completion: nil) } func closeCheckIn() { let alertController = UIAlertController(title: NSLocalizedString(Utility.getKey("Enter Password"),comment:""), message: NSLocalizedString(Utility.getKey("enter_pass_to_deactive_acheckin"),comment:""), preferredStyle: .Alert) alertController.addTextFieldWithConfigurationHandler { (textField) in textField.placeholder = NSLocalizedString(Utility.getKey("Password"),comment:"") textField.secureTextEntry = true if Structures.Constant.appDelegate.isArabic == true { textField.textAlignment = NSTextAlignment.Right } else { textField.textAlignment = NSTextAlignment.Left } } let okAction = UIAlertAction(title: NSLocalizedString(Utility.getKey("Ok"),comment:""), style: .Default) { (_) in let tfPassword = alertController.textFields![0] let password : NSString = tfPassword.text! self.checkInpassword = tfPassword.text if password.length>0 && password.length>0 { SVProgressHUD.showWithStatus(NSLocalizedString(Utility.getKey("closing_checkin"),comment:""), maskType: 4) CheckIn.updateCheckInStatus(NSMutableDictionary(dictionary:self.dictCloseStatusCheckIn(self.checkIn, status : NSNumber(integer : 4)))) CheckIn.sharedInstance.delegate = self }else{ let title = NSLocalizedString(Utility.getKey("confirmation"),comment:"") let message = NSLocalizedString(Utility.getKey("failed_to_cancel_checkin"),comment:"") let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: NSLocalizedString(Utility.getKey("Ok"),comment:""), style: .Cancel) { (action) in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.backToHomeScreen() }) } alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } } let cancelAction = UIAlertAction(title: NSLocalizedString(Utility.getKey("Cancel"),comment:""), style: .Cancel) { (action) in } if Structures.Constant.appDelegate.isArabic == true { alertController.addAction(cancelAction) alertController.addAction(okAction) } else { alertController.addAction(okAction) alertController.addAction(cancelAction) } self.presentViewController(alertController, animated: true, completion: nil) } //MARK:- Close CheckIn @IBAction func closeCheckin(sender: AnyObject) { if self.notiType == .ConfirmationReminder { closeCheckIn() } else if self.notiType == .ConfirmNow { closeCheckIn() } else if self.notiType == .StartReminder { cancelCheckIn() } else if self.notiType == .StartNow { if self.arrMedia.count > 0{ dispatch_async(dispatch_get_main_queue(), { () -> Void in self.uploadMediaIfAny() }) } else{ backToHomeScreen() } } else if self.notiType == .CloseReminder { updateDateAndTimeOfCheckIn() } else if self.notiType == .CloseNow { backToHomeScreen() } } func dictCloseStatusCheckIn(checkIN : CheckIn, status : NSNumber) -> NSDictionary{ let dictionary = [ Structures.CheckIn.CheckIn_ID : checkIN.checkInID, Structures.Constant.Latitude : self.checkIn.latitude, Structures.Constant.Longitude : self.checkIn.longitude, Structures.Constant.Status : status, Structures.Constant.TimezoneID : NSTimeZone.systemTimeZone().description, Structures.Constant.Time : Utility.getUTCFromDate(), Structures.User.User_Password : checkInpassword ] return dictionary } func updateDateAndTimeOfCheckIn(){ let checkInViewController : CheckInViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MediaPickerViewController") as! CheckInViewController showViewController(checkInViewController, sender: self.view) } func setUpLocalNotifications(action : NSString, body : NSString, fireDate : NSDate, userInfo : NSDictionary){ let localNotification:UILocalNotification = UILocalNotification() localNotification.alertAction = action as String localNotification.alertBody = body as String localNotification.fireDate = fireDate localNotification.userInfo = userInfo as [NSObject : AnyObject] UIApplication.sharedApplication().scheduleLocalNotification(localNotification) } func backToPreviousScreen(){ self.navigationController?.popViewControllerAnimated(true) } func backToHomeScreen() { if var _ : UINavigationController = Structures.Constant.appDelegate.window?.rootViewController as? UINavigationController { let homeNavController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MyContainerVC") Structures.Constant.appDelegate.window?.rootViewController? = homeNavController } else if let _ = Structures.Constant.appDelegate.window?.rootViewController as? MyContainerVC { self.navigationController?.popToRootViewControllerAnimated(true) } } func commonCheckInResponse(wsType : WSRequestType, checkIn_ID : NSNumber ,dict : NSDictionary, isSuccess : Bool) { if wsType == WSRequestType.ConfirmCheckIn{ if isSuccess { Utility.cancelNotification(Structures.CheckInStatus.Confirmation) Utility.cancelNotification(Structures.CheckInStatus.Reminder) Utility.cancelNotification(Structures.CheckInStatus.CloseReminder) Utility.cancelNotification(Structures.CheckInStatus.CheckInClosed) Utility.cancelNotification(Structures.CheckInStatus.MissedCheckIn) var isEndDateSet : Bool = true Structures.Constant.appDelegate.prefrence.laststatustime = NSDate() AppPrefrences.saveAppPrefrences(Structures.Constant.appDelegate.prefrence) if Structures.Constant.appDelegate.prefrence.endTime .isEqualToString("") { isEndDateSet = false let date = NSDate(timeInterval: (self.checkIn.frequency.doubleValue * 60 * 24 ), sinceDate: NSDate()) self.checkIn.endTime = date } self.checkIn.status = .Confirmed let startedDate = self.checkIn.startTime let frequency : NSTimeInterval = (self.checkIn.frequency.doubleValue) let endTime : NSDate = self.checkIn.endTime let lastConfirmCheckinTime = NSDate() let currentTime = NSDate() //Remonder Before 5 min var startOffsetReminder : Double = 0 if frequency >= 30 { if startedDate.compare(currentTime) == NSComparisonResult.OrderedDescending { startOffsetReminder = startedDate.timeIntervalSinceDate(currentTime) } let triggerDurationReminder : Double = startOffsetReminder + (frequency - 10) * 60 let nextConfirmationReminder = NSDate(timeInterval: triggerDurationReminder, sinceDate: currentTime) if (isEndDateSet == false || nextConfirmationReminder.compare(endTime) == NSComparisonResult.OrderedAscending) { dispatch_async(dispatch_get_main_queue(), { () -> Void in let userInfo : NSDictionary = ["CheckInID" : self.checkIn.checkInID, Structures.CheckIn.Status : Structures.CheckInStatus.Reminder ] self.setUpLocalNotifications(NSLocalizedString(Utility.getKey("confirm_checkin_remind"),comment:""), body: NSLocalizedString(Utility.getKey("confirm_checkin_10min"),comment:""), fireDate: nextConfirmationReminder, userInfo: userInfo) }) if isEndDateSet == true { //Close Reminder let timeInterval = startedDate.timeIntervalSinceDate(endTime) if Int(timeInterval) >= (60 * 30) { let startOffsetReminder = currentTime.timeIntervalSinceDate(endTime) if startOffsetReminder > 10 * 60 { dispatch_async(dispatch_get_main_queue(), { () -> Void in let userInfo : NSDictionary = ["CheckInID" : self.checkIn.checkInID, Structures.CheckIn.Status : Structures.CheckInStatus.CloseReminder] self.setUpLocalNotifications(NSLocalizedString(Utility.getKey("checkin_closed_10min"),comment:""), body: NSLocalizedString(Utility.getKey("confirm_checkin_10min"),comment:""), fireDate: NSDate(timeInterval: -600, sinceDate: self.checkIn.endTime), userInfo: userInfo) }) } } } } } //Confirmation Before 1 min var startOffsetFrequency : Double = 0 if startedDate.compare(currentTime) == NSComparisonResult.OrderedDescending { startOffsetFrequency = startedDate.timeIntervalSinceDate(currentTime) } let triggerDurationFrequency : Double = startOffsetFrequency + (frequency - 2) * 60 let nextConfirmationFrequency = NSDate(timeInterval: triggerDurationFrequency, sinceDate: currentTime) if (isEndDateSet == false || endTime.compare(nextConfirmationFrequency) == NSComparisonResult.OrderedDescending) { dispatch_async(dispatch_get_main_queue(), { () -> Void in let userInfo : NSDictionary = ["CheckInID" : self.checkIn.checkInID, Structures.CheckIn.Status : Structures.CheckInStatus.Confirmation] self.setUpLocalNotifications(NSLocalizedString(Utility.getKey("confirm_checkin_now"),comment:""), body: NSLocalizedString(Utility.getKey("confirm_checkin_now"),comment:""), fireDate: nextConfirmationFrequency, userInfo: userInfo) }) } //Miss Check-In var startOffsetFreq : Double = 0 var trigerDuration : Double = 0 //startedDate > currentDate if startedDate.compare(currentTime) == NSComparisonResult.OrderedDescending { // Future date startOffsetFreq = startedDate.timeIntervalSinceDate(currentTime) } trigerDuration = startOffsetFreq + ((frequency + 1) * 60) //startedDate < currentDate if startedDate.compare(currentTime) == NSComparisonResult.OrderedAscending { trigerDuration = trigerDuration - (currentTime.timeIntervalSinceDate(lastConfirmCheckinTime)) } let newDate = NSDate(timeInterval: trigerDuration, sinceDate: currentTime) if isEndDateSet == false || newDate.compare(endTime) == NSComparisonResult.OrderedAscending { dispatch_async(dispatch_get_main_queue(), { () -> Void in let userInfo : NSDictionary = ["CheckInID" : self.checkIn.checkInID, Structures.CheckIn.Status : Structures.CheckInStatus.MissedCheckIn] Structures.Constant.appDelegate.setUpLocalNotificationsReActive( String(format: NSLocalizedString(Utility.getKey("you_missed_chechin_confirmation"),comment:"") , (Utility.timeFromDate(newDate))), body: String(format: NSLocalizedString(Utility.getKey("you_missed_chechin_confirmation"),comment:"") , (Utility.timeFromDate(newDate))), fireDate: newDate, userInfo: userInfo) }) } //CheckIn endTime Close Reminder if (isEndDateSet == true && currentTime.compare(endTime) == NSComparisonResult.OrderedAscending) { dispatch_async(dispatch_get_main_queue(), { () -> Void in let userInfo : NSDictionary = ["CheckInID" : self.checkIn.checkInID,Structures.CheckIn.Status : Structures.CheckInStatus.CheckInClosed ] self.setUpLocalNotifications(NSLocalizedString(Utility.getKey("checkin_closed"),comment:""), body: NSLocalizedString(Utility.getKey("checkin_closed"),comment:""), fireDate: self.checkIn.endTime, userInfo: userInfo) }) } CheckIn.saveCurrentCheckInObject(self.checkIn) NSUserDefaults.standardUserDefaults().synchronize() if self.arrMedia.count > 0 { self.uploadMediaIfAny() } else { let nextConfirmation = NSDate(timeInterval: (startOffsetFrequency+(frequency) * 60), sinceDate: currentTime) var title = "" if nextConfirmation.compare(self.checkIn.endTime) == NSComparisonResult.OrderedAscending{ title = String(format: NSLocalizedString(Utility.getKey("your_next_conf"),comment:"") , (Utility.timeFromDate(nextConfirmation))) }else{ title = String(format: NSLocalizedString(Utility.getKey("checkin_closed_at"),comment:"") , (Utility.timeFromDate(self.checkIn.endTime))) } let alert = UIAlertController(title: title, message: "", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: NSLocalizedString(Utility.getKey("Ok"),comment:""), style: .Default, handler: { action in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.backToHomeScreen() }) })) dispatch_async(dispatch_get_main_queue(), { () -> Void in self.presentViewController(alert, animated: true, completion: nil) }) } } else { CheckIn.removeActiveCheckInObject() self.backToHomeScreen() } }else if wsType == WSRequestType.CheckInStarted{ let title = NSLocalizedString(Utility.getKey("confirmation"),comment:"") var message = "" if isSuccess{ message = NSLocalizedString(Utility.getKey("checkin_started_successfully"),comment:"") self.checkIn.status = .Started CheckIn.saveCurrentCheckInObject(self.checkIn) }else{ message = NSLocalizedString(Utility.getKey("failed_to_start_checkin"),comment:"") } if self.arrMedia.count > 0{ self.uploadMediaIfAny() }else{ let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: NSLocalizedString(Utility.getKey("Ok"),comment:""), style: .Cancel) { (action) in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.backToHomeScreen() }) } alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } }else if wsType == WSRequestType.CancelCheckIn{ let title = NSLocalizedString(Utility.getKey("confirmation"),comment:"") var message = "" if isSuccess{ CheckIn.removeActiveCheckInObject() message = NSLocalizedString(Utility.getKey("checkin_canceled"),comment:"") if self.arrMedia.count > 0{ self.uploadMediaIfAny() }else{ let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: NSLocalizedString(Utility.getKey("Ok"),comment:""), style: .Cancel) { (action) in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.backToHomeScreen() }) } alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } }else{ message = NSLocalizedString(Utility.getKey("failed_to_cancel_checkin"),comment:"") let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: NSLocalizedString(Utility.getKey("Ok"),comment:""), style: .Cancel) { (action) in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.backToHomeScreen() }) } alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } }else if wsType == WSRequestType.CloseCheckIn{ let title = NSLocalizedString(Utility.getKey("confirmation"),comment:"") var message = "" if isSuccess{ CheckIn.removeActiveCheckInObject() message = NSLocalizedString(Utility.getKey("checkin_closed"),comment:"") if self.arrMedia.count > 0{ self.uploadMediaIfAny() }else{ let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: NSLocalizedString(Utility.getKey("Ok"),comment:""), style: .Cancel) { (action) in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.backToHomeScreen() }) } alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } }else{ message = NSLocalizedString(Utility.getKey("failed_to_cancel_checkin"),comment:"") let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: NSLocalizedString(Utility.getKey("Ok"),comment:""), style: .Cancel) { (action) in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.backToHomeScreen() }) } alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } } } //MARK:- WSDelegate func WSResponse(response:AnyObject?, ReqType type:WSRequestType) { if (response is NSString) { SVProgressHUD.dismiss() } else { let data : NSData? = NSData(data: response as! NSData) if (data != nil) { if let dic: NSDictionary = (try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary! { if type == WSRequestType.SendMailWithMedia { if dic.objectForKey(Structures.Constant.Status)?.integerValue == 1 { Utility.updateUserHeaderToken(dic.objectForKey(Structures.Constant.Headertoken) as! String) dispatch_async(dispatch_get_main_queue(), { () -> Void in SVProgressHUD.dismiss() let alert = UIAlertController(title: NSLocalizedString(Utility.getKey("media_upload_success"),comment:""), message: "", preferredStyle: UIAlertControllerStyle.Alert) //"Media files uploaded successfully" alert.addAction(UIAlertAction(title: NSLocalizedString(Utility.getKey("Ok"),comment:""), style: .Default, handler: { action in self.backToHomeScreen() })) self.presentViewController(alert, animated: true, completion: nil) }) } } } SVProgressHUD.dismiss() } else { SVProgressHUD.dismiss() } } } func WSResponseEoor(error:NSError, ReqType type:WSRequestType) { SVProgressHUD.dismiss() Utility.showAlertWithTitle(NSLocalizedString(Utility.getKey("try_later"),comment:""), strMessage: "", strButtonTitle: NSLocalizedString(Utility.getKey("Ok"),comment:""), view: self) } }
ee742a879e95ad2a9b19e3b618a37ef9
49.774752
395
0.593477
false
false
false
false
ResearchSuite/ResearchSuiteExtensions-iOS
refs/heads/master
source/Core/Classes/RSTextInstructionStepViewController.swift
apache-2.0
1
// // RSTextInstructionStepViewController.swift // ResearchSuiteExtensions // // Created by James Kizer on 10/18/18. // import UIKit import SnapKit open class RSTextInstructionStepViewController: RSQuestionViewController { var scrollView: UIScrollView! override open func viewDidLoad() { super.viewDidLoad() guard let step = self.step as? RSTextInstructionStep else { return } guard let sections = step.sections else { return } let stackedViews: [UIView] = sections.map { section in let label = UILabel() label.numberOfLines = 0 label.attributedText = section.attributedText label.textAlignment = section.alignment label.layoutMargins = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8) return label } let stackView = UIStackView(arrangedSubviews: stackedViews) stackView.axis = .vertical stackView.distribution = .equalSpacing stackView.layoutMargins = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8) stackView.isLayoutMarginsRelativeArrangement = true stackView.spacing = 8.0 let scrollView = UIScrollView() scrollView.frame = self.contentView.bounds self.contentView.addSubview(scrollView) self.scrollView = scrollView scrollView.snp.makeConstraints { (make) in make.width.height.equalToSuperview() make.center.equalToSuperview() } scrollView.addSubview(stackView) stackView.snp.makeConstraints { (make) in make.leading.trailing.equalToSuperview() make.top.bottom.equalToSuperview() make.width.equalToSuperview() } } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.scrollView.frame = self.contentView.bounds } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.scrollView.frame = self.contentView.bounds } }
4ea2e9cf9e7dd9653805786e10c2710d
29.757143
84
0.627497
false
false
false
false
scotlandyard/expocity
refs/heads/master
expocity/Controller/Chat/CChat.swift
mit
1
import UIKit class CChat:CController { weak var viewChat:VChat! let roomId:String var model:MChat! init(roomId:String) { self.roomId = roomId super.init(nibName:nil, bundle:nil) } required init?(coder:NSCoder) { fatalError() } override func viewDidAppear(_ animated:Bool) { super.viewDidAppear(animated) if model == nil { DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.loadModel() } } } override func loadView() { let viewChat:VChat = VChat(controller:self) self.viewChat = viewChat view = viewChat } override func viewWillTransition(to size:CGSize, with coordinator:UIViewControllerTransitionCoordinator) { UIApplication.shared.keyWindow!.endEditing(true) super.viewWillTransition(to:size, with:coordinator) DispatchQueue.main.async { [weak self] in self?.viewChat.conversation.scrollToBottom() } } //MARK: private private func loadModel() { let roomReference:String = FDatabase.Parent.room.rawValue let path:String = String( format:"%@/%@", roomReference, roomId) FMain.sharedInstance.database.listenOnce( path:path, modelType:FDatabaseModelRoom.self) { [weak self] (object:FDatabaseModelRoom) in self?.model = MChat(firebaseRoom:object) self?.modelLoaded() } } private func modelLoaded() { DispatchQueue.main.async { [weak self] in self?.chatReady() } } private func chatReady() { title = model.title viewChat.chatLoaded() } private func addChatItem(chatItem:MChatItem) { let index:Int = model.items.count let indexPath:IndexPath = IndexPath(item:index, section:0) let indexes:[IndexPath] = [indexPath] model.items.append(chatItem) viewChat.conversation.didAddChatItem(indexes:indexes) } //MARK: public func displayImageRect() -> CGRect { let imageView:UIImageView = viewChat.display.imageView let rect:CGRect = imageView.superview!.convert(imageView.frame, to:parentController.viewParent) return rect } func addTextMine(text:String) { let chatItem:MChatItemTextMine = MChatItemTextMine(text:text) addChatItem(chatItem:chatItem) } func addEmojiMine(image:UIImage) { let chatItem:MChatItemEmojiMine = MChatItemEmojiMine(image:image) addChatItem(chatItem:chatItem) } func displayDetail() { let imageView:UIImageView = viewChat.display.imageView let image:UIImage? = imageView.image let rect:CGRect = imageView.superview!.convert(imageView.frame, to:parentController.viewParent) let displayOption:MChatDisplayOptionsItem = model.displayOption let controllerDetail:CChatDisplayDetail = CChatDisplayDetail(image:image, imageRect:rect, displayOption:displayOption) parentController.over(controller:controllerDetail) } func displayOptions() { let controllerOptions:CChatDisplayOptions = CChatDisplayOptions(modelChat:model) parentController.over(controller:controllerOptions) } func displayAnnotations() { let controllerAnnotations:CChatDisplayAnnotations = CChatDisplayAnnotations(controllerChat:self) parentController.over(controller:controllerAnnotations) viewChat.display.displayAnnotations() NotificationCenter.default.removeObserver(viewChat) } func removeImage() { model.annotations.items = [] viewChat.display.removeImage() } }
6abe2fb1fccf8f8447bcdf3a18ecb9ad
26.02
126
0.613373
false
false
false
false
alickbass/ViewComponents
refs/heads/master
ViewComponents/UIIScrollViewStyle.swift
mit
1
// // UIIScrollViewStyle.swift // ViewComponents // // Created by Oleksii on 12/05/2017. // Copyright © 2017 WeAreReasonablePeople. All rights reserved. // import UIKit private enum UIScrollViewStyleKey: Int, StyleKey { case contentOffset = 300, contentSize, contentInset case isScrollEnabled, isDirectionalLockEnabled, isPagingEnabled case bounces, alwaysBounceVertical, alwaysBounceHorizontal case canCancelContentTouches, delaysContentTouches, indicatorStyle case scrollIndicatorInsets, showsHorizontalScrollIndicator, showsVerticalScrollIndicator case maximumZoomScale, minimumZoomScale, bouncesZoom } public extension AnyStyle where T: UIScrollView { private typealias ViewStyle<Item> = Style<T, Item, UIScrollViewStyleKey> public static func contentOffset(_ value: CGPoint) -> AnyStyle<T> { return ViewStyle(value, key: .contentOffset, sideEffect: { $0.contentOffset = $1 }).toAnyStyle } public static func contentSize(_ value: CGSize) -> AnyStyle<T> { return ViewStyle(value, key: .contentSize, sideEffect: { $0.contentSize = $1 }).toAnyStyle } public static func contentInset(_ value: UIEdgeInsets) -> AnyStyle<T> { return ViewStyle(value, key: .contentInset, sideEffect: { $0.contentInset = $1 }).toAnyStyle } public static func isScrollEnabled(_ value: Bool) -> AnyStyle<T> { return ViewStyle(value, key: .isScrollEnabled, sideEffect: { $0.isScrollEnabled = $1 }).toAnyStyle } public static func isDirectionalLockEnabled(_ value: Bool) -> AnyStyle<T> { return ViewStyle(value, key: .isDirectionalLockEnabled, sideEffect: { $0.isDirectionalLockEnabled = $1 }).toAnyStyle } public static func isPagingEnabled(_ value: Bool) -> AnyStyle<T> { return ViewStyle(value, key: .isPagingEnabled, sideEffect: { $0.isPagingEnabled = $1 }).toAnyStyle } public static func bounces(_ value: Bool) -> AnyStyle<T> { return ViewStyle(value, key: .bounces, sideEffect: { $0.bounces = $1 }).toAnyStyle } public static func alwaysBounceVertical(_ value: Bool) -> AnyStyle<T> { return ViewStyle(value, key: .alwaysBounceVertical, sideEffect: { $0.alwaysBounceVertical = $1 }).toAnyStyle } public static func alwaysBounceHorizontal(_ value: Bool) -> AnyStyle<T> { return ViewStyle(value, key: .alwaysBounceHorizontal, sideEffect: { $0.alwaysBounceHorizontal = $1 }).toAnyStyle } public static func canCancelContentTouches(_ value: Bool) -> AnyStyle<T> { return ViewStyle(value, key: .canCancelContentTouches, sideEffect: { $0.canCancelContentTouches = $1 }).toAnyStyle } public static func delaysContentTouches(_ value: Bool) -> AnyStyle<T> { return ViewStyle(value, key: .delaysContentTouches, sideEffect: { $0.delaysContentTouches = $1 }).toAnyStyle } public static func indicatorStyle(_ value: UIScrollViewIndicatorStyle) -> AnyStyle<T> { return ViewStyle(value, key: .indicatorStyle, sideEffect: { $0.indicatorStyle = $1 }).toAnyStyle } public static func scrollIndicatorInsets(_ value: UIEdgeInsets) -> AnyStyle<T> { return ViewStyle(value, key: .scrollIndicatorInsets, sideEffect: { $0.scrollIndicatorInsets = $1 }).toAnyStyle } public static func showsHorizontalScrollIndicator(_ value: Bool) -> AnyStyle<T> { return ViewStyle(value, key: .showsHorizontalScrollIndicator, sideEffect: { $0.showsHorizontalScrollIndicator = $1 }).toAnyStyle } public static func showsVerticalScrollIndicator(_ value: Bool) -> AnyStyle<T> { return ViewStyle(value, key: .showsVerticalScrollIndicator, sideEffect: { $0.showsVerticalScrollIndicator = $1 }).toAnyStyle } public static func maximumZoomScale(_ value: CGFloat) -> AnyStyle<T> { return ViewStyle(value, key: .maximumZoomScale, sideEffect: { $0.maximumZoomScale = $1 }).toAnyStyle } public static func minimumZoomScale(_ value: CGFloat) -> AnyStyle<T> { return ViewStyle(value, key: .minimumZoomScale, sideEffect: { $0.minimumZoomScale = $1 }).toAnyStyle } public static func bouncesZoom(_ value: Bool) -> AnyStyle<T> { return ViewStyle(value, key: .bouncesZoom, sideEffect: { $0.bouncesZoom = $1 }).toAnyStyle } }
bb01d9680978bf854cbc1cbe557a9355
45.393617
136
0.6964
false
false
false
false
edjiang/forward-swift-workshop
refs/heads/master
SwiftNotesIOS/Pods/Stormpath/Stormpath/Networking/OAuthAPIRequestManager.swift
apache-2.0
1
// // OAuthAPIRequestManager.swift // Stormpath // // Created by Edward Jiang on 2/5/16. // Copyright © 2016 Stormpath. All rights reserved. // import Foundation class OAuthAPIRequestManager: APIRequestManager { var requestBody: String var callback: AccessTokenCallback private init(withURL url: NSURL, requestBody: String, callback: AccessTokenCallback) { self.requestBody = requestBody self.callback = callback super.init(withURL: url) } convenience init(withURL url: NSURL, username: String, password: String, callback: AccessTokenCallback) { let requestBody = "username=\(username.formURLEncoded)&password=\(password.formURLEncoded)&grant_type=password" self.init(withURL: url, requestBody: requestBody, callback: callback) } convenience init(withURL url: NSURL, refreshToken: String, callback: AccessTokenCallback) { let requestBody = String(format: "refresh_token=%@&grant_type=refresh_token", refreshToken) self.init(withURL: url, requestBody: requestBody, callback: callback) } override func prepareForRequest() { request.HTTPMethod = "POST" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.HTTPBody = requestBody.dataUsingEncoding(NSUTF8StringEncoding) } override func requestDidFinish(data: NSData, response: NSHTTPURLResponse) { guard let json = (try? NSJSONSerialization.JSONObjectWithData(data, options: [])) as? NSDictionary, accessToken = json["access_token"] as? String else { //Callback and return performCallback(error: StormpathError.APIResponseError) return } let refreshToken = json["refresh_token"] as? String performCallback(accessToken, refreshToken: refreshToken, error: nil) } override func performCallback(error error: NSError?) { performCallback(nil, refreshToken: nil, error: error) } func performCallback(accessToken: String?, refreshToken: String?, error: NSError?) { dispatch_async(dispatch_get_main_queue()) { self.callback(accessToken: accessToken, refreshToken: refreshToken, error: error) } } } // Custom URL encode, 'cos iOS is missing one. This one is blatantly stolen from AFNetworking's implementation of percent escaping and converted to Swift private extension String { var formURLEncoded: String { let charactersGeneralDelimitersToEncode = ":#[]@" let charactersSubDelimitersToEncode = "!$&'()*+,;=" let allowedCharacterSet: NSMutableCharacterSet = NSCharacterSet.URLHostAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet allowedCharacterSet.removeCharactersInString(charactersGeneralDelimitersToEncode.stringByAppendingString(charactersSubDelimitersToEncode)) return self.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet)! } }
e975130beb1bffea06e2af245a99d51a
39.421053
153
0.695865
false
false
false
false
russbishop/swift
refs/heads/master
test/ClangModules/blocks_parse.swift
apache-2.0
1
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -verify %s // REQUIRES: objc_interop import blocks import Foundation var someNSString : NSString func useString(_ s: String) {} accepts_block { } someNSString.enumerateLines {(s:String?) in } someNSString.enumerateLines {s in } someNSString.enumerateLines({ useString($0) }) accepts_block(/*not a block=*/()) // expected-error{{cannot convert value of type '()' to expected argument type 'my_block_t' (aka '() -> ()'}} func testNoEscape(f: @noescape @convention(block) () -> Void, nsStr: NSString, fStr: @noescape (String!) -> Void) { accepts_noescape_block(f) accepts_noescape_block(f) // rdar://problem/19818617 nsStr.enumerateLines(fStr) // okay due to @noescape _ = nsStr.enumerateLines as Int // expected-error{{cannot convert value of type '(@noescape (String) -> Void) -> Void' to type 'Int' in coercion}} } func checkTypeImpl<T>(_ a: inout T, _: T.Type) {} do { var blockOpt = blockWithoutNullability() checkTypeImpl(&blockOpt, Optional<my_block_t>.self) var block: my_block_t = blockWithoutNullability() } do { var block = blockWithNonnull() checkTypeImpl(&block, my_block_t.self) } do { var blockOpt = blockWithNullUnspecified() checkTypeImpl(&blockOpt, Optional<my_block_t>.self) var block: my_block_t = blockWithNullUnspecified() } do { var block = blockWithNullable() checkTypeImpl(&block, Optional<my_block_t>.self) }
db26a0ccb005963310ba8fa22f282e61
30.021277
148
0.697531
false
false
false
false
MegaManX32/CD
refs/heads/master
CD/CD/View Controllers/SettingsViewController.swift
mit
1
// // SettingsViewController.swift // CD // // Created by Vladislav Simovic on 12/26/16. // Copyright © 2016 CustomDeal. All rights reserved. // import UIKit import AlamofireImage import MBProgressHUD import MessageUI fileprivate let revealWidthOffset: CGFloat = 60 fileprivate let avatarImageViewHeightAndWidth: CGFloat = 60 class SettingsViewController: UIViewController, MFMailComposeViewControllerDelegate { // MARK: - Properties @IBOutlet weak var avatarImageView : UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var emailLabel : UILabel! @IBOutlet weak var createListOrProvideServiceButton : UIButton! @IBOutlet weak var hostSwitch : UISwitch! // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() // set reveal width self.revealViewController().rearViewRevealWidth = UIScreen.main.bounds.width - revealWidthOffset // set avatar self.avatarImageView.layer.cornerRadius = avatarImageViewHeightAndWidth / 2.0 self.avatarImageView.layer.masksToBounds = true // add tap gesture to all front view controllers self.revealViewController().tapGestureRecognizer() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // update user let context = CoreDataManager.sharedInstance.mainContext let user = User.findUserWith(uid: StandardUserDefaults.userID(), context: context)! self.nameLabel.text = user.firstName! self.emailLabel.text = user.email! if let photoURL = user.photoURL { self.avatarImageView.af_setImage(withURL: URL(string:photoURL)!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK - User Actions @IBAction func hostOptionChanged(sender: UISwitch) { if !sender.isOn { self.createListOrProvideServiceButton.setTitle("Create Rider List", for: .normal) let controller = self.storyboard?.instantiateViewController(withIdentifier: "GuestNavigationController"); self.revealViewController().pushFrontViewController(controller, animated: true) } else { self.createListOrProvideServiceButton.setTitle("Provide Service", for: .normal) let controller = self.storyboard?.instantiateViewController(withIdentifier: "HostNavigationController"); self.revealViewController().pushFrontViewController(controller, animated: true) } } @IBAction func createListOrProvideServiceAction(sender: UIButton) { if !self.hostSwitch.isOn { let controller = self.storyboard?.instantiateViewController(withIdentifier: "CreateRiderListViewController") as! CreateRiderListViewController if self.revealViewController().frontViewController is GuestHomeViewController { self.revealViewController().frontViewController.show(controller, sender: self) self.revealViewController().revealToggle(self) return } let navigationController = self.storyboard?.instantiateViewController(withIdentifier: "GuestNavigationController") as! UINavigationController navigationController.pushViewController(controller, animated: false) self.revealViewController().pushFrontViewController(navigationController, animated: true) } else { let controller = self.storyboard?.instantiateViewController(withIdentifier: "HostProvideServiceViewController") as! HostProvideServiceViewController if self.revealViewController().frontViewController is HostHomeViewController { self.revealViewController().frontViewController.show(controller, sender: self) self.revealViewController().revealToggle(self) return } let navigationController = self.storyboard?.instantiateViewController(withIdentifier: "HostNavigationController") as! UINavigationController navigationController.pushViewController(controller, animated: false) self.revealViewController().pushFrontViewController(navigationController, animated: true) } } @IBAction func profileAction(sender: UIButton) { let controller = self.storyboard?.instantiateViewController(withIdentifier: "HostProfileViewController") as! HostProfileViewController controller.userID = StandardUserDefaults.userID() controller.presentFromMainMenu = true let navigationController = UINavigationController.init(rootViewController: controller) navigationController.isNavigationBarHidden = true self.revealViewController().pushFrontViewController(navigationController, animated: true) } @IBAction func homeAction(sender: UIButton) { if !self.hostSwitch.isOn { let controller = self.storyboard?.instantiateViewController(withIdentifier: "GuestNavigationController"); self.revealViewController().pushFrontViewController(controller, animated: true) } else { let controller = self.storyboard?.instantiateViewController(withIdentifier: "HostNavigationController"); self.revealViewController().pushFrontViewController(controller, animated: true) } } @IBAction func logOut(sender : UIButton) { // do log out NetworkManager.sharedInstance.logout() self.dismiss(animated: true, completion: nil) } @IBAction func aboutUs(sender: UIButton) { let controller = self.storyboard?.instantiateViewController(withIdentifier: "AboutUsViewController"); self.revealViewController().pushFrontViewController(controller, animated: true) } @IBAction func helpAction(_ sender: UIButton) { if MFMailComposeViewController.canSendMail() { let mail = MFMailComposeViewController() mail.mailComposeDelegate = self mail.setSubject("Help") mail.setToRecipients(["[email protected]"]) present(mail, animated: true) } else { CustomAlert.presentAlert(message: "Please check your email settings", controller: self) } } @IBAction func comingSoon(sender: UIButton) { CustomAlert.presentAlert(message: "Coming soon :-)", controller: self) } // MARK: - MFMailComposeViewController Methods func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true) } }
96c4c2ae25ddef618d7058880d631779
43.298701
160
0.698036
false
false
false
false
crossroadlabs/ExpressCommandLine
refs/heads/master
swift-express/Core/Step.swift
gpl-3.0
1
//===--- Step.swift ---------------------------------------------------------===// //Copyright (c) 2015-2016 Daniel Leping (dileping) // //This file is part of Swift Express Command Line // //Swift Express Command Line is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //Swift Express Command Line is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>. // //===------------------------------------------------------------------------===// import Result protocol Step { var dependsOn : [Step] { get } func run(params: [String: Any], combinedOutput: StepResponse) throws -> [String: Any] func cleanup(params:[String: Any], output: StepResponse) throws // Optional. Return unique string key for object func uniqueKey() -> String // Optional. Implement only if step depends on any another step and need to convert call parameters func callParams(ownParams: [String: Any], forStep: Step, previousStepsOutput: StepResponse) throws -> [String: Any] // Optional. Implement if you want handle revert on error. Error provided if generated by self. func revert(params:[String: Any], output: [String: Any]?, error: SwiftExpressError?) } extension Step { // Default realisation of callParams. Return own params func callParams(ownParams: [String: Any], forStep: Step, previousStepsOutput: StepResponse) throws -> [String: Any] { return ownParams } // Default realization of revert. Forward call to cleanup func revert(params:[String: Any], output: [String: Any]?, error: SwiftExpressError?) { if error != nil { print("Unhandled error in \(self.uniqueKey()). Error: \(error!)") } } // Default implementation of uniqueKey. Returns class name func uniqueKey() -> String { return String(self.dynamicType) } } class StepResponse { private let response:[String:Any]? private let params:[String:Any]? let parents:[String: StepResponse]? init(params:[String: Any], response: [String: Any]) { self.response = response self.params = params self.parents = nil } init(parents: [String: StepResponse]) { self.response = nil self.params = nil self.parents = parents } init(params: [String: Any], response: [String: Any], parents: [String: StepResponse]) { self.response = response self.parents = parents self.params = params } func ownParam(key: String) -> Any? { if response != nil { if let val = response![key] { return val } } return nil } func parentsParam(key: String) -> Any? { if parents != nil { for (_, parent) in parents! { if let val = parent.ownParam(key) { return val } } for (_, parent) in parents! { if let val = parent.parentsParam(key) { return val } } } return nil } subscript(key: String) -> Any? { if response != nil { if let val = response![key] { return val } } if parents != nil { for (_, parent) in parents! { if let val = parent[key] { return val } } } return nil } } struct StepRunner { private let _step: Step init(step: Step) { self._step = step } private func runRevert(steps: [Step], combinedOutput: [String: StepResponse]) { for errStep in steps.reverse() { errStep.revert(combinedOutput[errStep.uniqueKey()]!.params!, output: combinedOutput[errStep.uniqueKey()]?.response, error: nil) if errStep.dependsOn.count > 0 { runRevert(errStep.dependsOn, combinedOutput: combinedOutput[errStep.uniqueKey()]!.parents!) } } } private func runStep(step: Step, params: [String: Any]) throws -> StepResponse { var combinedOutput = [String : StepResponse]() for index in 0..<step.dependsOn.count { let prevStep = step.dependsOn[index] do { let prevParams = try step.callParams(params, forStep: prevStep, previousStepsOutput: StepResponse(parents: combinedOutput)) combinedOutput[prevStep.uniqueKey()] = try runStep(prevStep, params: prevParams) } catch let err as SwiftExpressError { runRevert(Array(step.dependsOn[0..<index]), combinedOutput: combinedOutput) throw err } catch { let err = SwiftExpressError.UnknownError(error: error) runRevert(Array(step.dependsOn[0..<index]), combinedOutput: combinedOutput) throw err } } do { let response = try step.run(params, combinedOutput: StepResponse(parents: combinedOutput)) return StepResponse(params:params, response: response, parents: combinedOutput) } catch let err as SwiftExpressError { step.revert(params, output: nil, error: err) runRevert(step.dependsOn, combinedOutput: combinedOutput) throw err } catch { let err = SwiftExpressError.UnknownError(error: error) step.revert(params, output: nil, error: err) runRevert(step.dependsOn, combinedOutput: combinedOutput) throw err } } private func runCleanup(step: Step, params: [String: Any], output: StepResponse) throws { do { try step.cleanup(params, output: output) } catch let err as SwiftExpressError { step.revert(params, output: output.response, error: err) if step.dependsOn.count > 0 { runRevert(step.dependsOn, combinedOutput: output.parents!) } throw err } catch { let err = SwiftExpressError.UnknownError(error: error) step.revert(params, output: output.response, error: err) if step.dependsOn.count > 0 { runRevert(step.dependsOn, combinedOutput: output.parents!) } throw err } for index in (0..<step.dependsOn.count).reverse() { do { let parStep = step.dependsOn[index] let parOut = output.parents![parStep.uniqueKey()]! try runCleanup(parStep, params: parOut.params!, output: parOut) } catch { runRevert(Array(step.dependsOn[0..<index]), combinedOutput: output.parents!) throw error } } } func run(params: [String: Any]) throws { let response = try runStep(self._step, params: params) try runCleanup(self._step, params: params, output: response) } }
a69975c017487f20e88df8626ff6b3e2
35.441748
139
0.577594
false
false
false
false
JGiola/swift-corelibs-foundation
refs/heads/master
Foundation/NSNumber.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if os(macOS) || os(iOS) internal let kCFNumberSInt8Type = CFNumberType.sInt8Type internal let kCFNumberSInt16Type = CFNumberType.sInt16Type internal let kCFNumberSInt32Type = CFNumberType.sInt32Type internal let kCFNumberSInt64Type = CFNumberType.sInt64Type internal let kCFNumberFloat32Type = CFNumberType.float32Type internal let kCFNumberFloat64Type = CFNumberType.float64Type internal let kCFNumberCharType = CFNumberType.charType internal let kCFNumberShortType = CFNumberType.shortType internal let kCFNumberIntType = CFNumberType.intType internal let kCFNumberLongType = CFNumberType.longType internal let kCFNumberLongLongType = CFNumberType.longLongType internal let kCFNumberFloatType = CFNumberType.floatType internal let kCFNumberDoubleType = CFNumberType.doubleType internal let kCFNumberCFIndexType = CFNumberType.cfIndexType internal let kCFNumberNSIntegerType = CFNumberType.nsIntegerType internal let kCFNumberCGFloatType = CFNumberType.cgFloatType internal let kCFNumberSInt128Type = CFNumberType(rawValue: 17)! #else internal let kCFNumberSInt128Type: CFNumberType = 17 #endif extension Int8 : _ObjectiveCBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.int8Value } public init(truncating number: NSNumber) { self = number.int8Value } public init?(exactly number: NSNumber) { let value = number.int8Value guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Int8?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Int8?) -> Bool { guard let value = Int8(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int8 { var result: Int8? guard let src = source else { return Int8(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Int8(0) } return result! } } extension UInt8 : _ObjectiveCBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.uint8Value } public init(truncating number: NSNumber) { self = number.uint8Value } public init?(exactly number: NSNumber) { let value = number.uint8Value guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt8?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt8?) -> Bool { guard let value = UInt8(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt8 { var result: UInt8? guard let src = source else { return UInt8(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return UInt8(0) } return result! } } extension Int16 : _ObjectiveCBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.int16Value } public init(truncating number: NSNumber) { self = number.int16Value } public init?(exactly number: NSNumber) { let value = number.int16Value guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Int16?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Int16?) -> Bool { guard let value = Int16(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int16 { var result: Int16? guard let src = source else { return Int16(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Int16(0) } return result! } } extension UInt16 : _ObjectiveCBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.uint16Value } public init(truncating number: NSNumber) { self = number.uint16Value } public init?(exactly number: NSNumber) { let value = number.uint16Value guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt16?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt16?) -> Bool { guard let value = UInt16(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt16 { var result: UInt16? guard let src = source else { return UInt16(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return UInt16(0) } return result! } } extension Int32 : _ObjectiveCBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.int32Value } public init(truncating number: NSNumber) { self = number.int32Value } public init?(exactly number: NSNumber) { let value = number.int32Value guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Int32?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Int32?) -> Bool { guard let value = Int32(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int32 { var result: Int32? guard let src = source else { return Int32(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Int32(0) } return result! } } extension UInt32 : _ObjectiveCBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.uint32Value } public init(truncating number: NSNumber) { self = number.uint32Value } public init?(exactly number: NSNumber) { let value = number.uint32Value guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt32?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt32?) -> Bool { guard let value = UInt32(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt32 { var result: UInt32? guard let src = source else { return UInt32(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return UInt32(0) } return result! } } extension Int64 : _ObjectiveCBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.int64Value } public init(truncating number: NSNumber) { self = number.int64Value } public init?(exactly number: NSNumber) { let value = number.int64Value guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Int64?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Int64?) -> Bool { guard let value = Int64(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int64 { var result: Int64? guard let src = source else { return Int64(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Int64(0) } return result! } } extension UInt64 : _ObjectiveCBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.uint64Value } public init(truncating number: NSNumber) { self = number.uint64Value } public init?(exactly number: NSNumber) { let value = number.uint64Value guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt64?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt64?) -> Bool { guard let value = UInt64(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt64 { var result: UInt64? guard let src = source else { return UInt64(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return UInt64(0) } return result! } } extension Int : _ObjectiveCBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.intValue } public init(truncating number: NSNumber) { self = number.intValue } public init?(exactly number: NSNumber) { let value = number.intValue guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Int?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Int?) -> Bool { guard let value = Int(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int { var result: Int? guard let src = source else { return Int(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Int(0) } return result! } } extension UInt : _ObjectiveCBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.uintValue } public init(truncating number: NSNumber) { self = number.uintValue } public init?(exactly number: NSNumber) { let value = number.uintValue guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt?) -> Bool { guard let value = UInt(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt { var result: UInt? guard let src = source else { return UInt(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return UInt(0) } return result! } } extension Float : _ObjectiveCBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.floatValue } public init(truncating number: NSNumber) { self = number.floatValue } public init?(exactly number: NSNumber) { let type = number.objCType.pointee if type == 0x49 || type == 0x4c || type == 0x51 { guard let result = Float(exactly: number.uint64Value) else { return nil } self = result } else if type == 0x69 || type == 0x6c || type == 0x71 { guard let result = Float(exactly: number.int64Value) else { return nil } self = result } else { guard let result = Float(exactly: number.doubleValue) else { return nil } self = result } } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Float?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Float?) -> Bool { if x.floatValue.isNaN { result = x.floatValue return true } result = Float(exactly: x) return result != nil } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Float { var result: Float? guard let src = source else { return Float(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Float(0) } return result! } } extension Double : _ObjectiveCBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.doubleValue } public init(truncating number: NSNumber) { self = number.doubleValue } public init?(exactly number: NSNumber) { let type = number.objCType.pointee if type == 0x51 { guard let result = Double(exactly: number.uint64Value) else { return nil } self = result } else if type == 0x71 { guard let result = Double(exactly: number.int64Value) else { return nil } self = result } else { // All other integer types and single-precision floating points will // fit in a `Double` without truncation. guard let result = Double(exactly: number.doubleValue) else { return nil } self = result } } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Double?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Double?) -> Bool { if x.doubleValue.isNaN { result = x.doubleValue return true } result = Double(exactly: x) return result != nil } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Double { var result: Double? guard let src = source else { return Double(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Double(0) } return result! } } extension Bool : _ObjectiveCBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.boolValue } public init(truncating number: NSNumber) { self = number.boolValue } public init?(exactly number: NSNumber) { if number === kCFBooleanTrue || NSNumber(value: 1) == number { self = true } else if number === kCFBooleanFalse || NSNumber(value: 0) == number { self = false } else { return nil } } public func _bridgeToObjectiveC() -> NSNumber { return unsafeBitCast(self ? kCFBooleanTrue : kCFBooleanFalse, to: NSNumber.self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Bool?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Bool?) -> Bool { if x === kCFBooleanTrue || NSNumber(value: 1) == x { result = true return true } else if x === kCFBooleanFalse || NSNumber(value: 0) == x { result = false return true } result = nil return false } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Bool { var result: Bool? guard let src = source else { return false } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return false } return result! } } extension Bool : _CFBridgeable { typealias CFType = CFBoolean var _cfObject: CFType { return self ? kCFBooleanTrue : kCFBooleanFalse } } extension NSNumber : ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral, ExpressibleByBooleanLiteral { } private struct CFSInt128Struct { var high: Int64 var low: UInt64 } fileprivate func cast<T, U>(_ t: T) -> U { return t as! U } open class NSNumber : NSValue { typealias CFType = CFNumber // This layout MUST be the same as CFNumber so that they are bridgeable private var _base = _CFInfo(typeID: CFNumberGetTypeID()) private var _pad: UInt64 = 0 internal var _cfObject: CFType { return unsafeBitCast(self, to: CFType.self) } open override var hash: Int { return Int(bitPattern: CFHash(_cfObject)) } open override func isEqual(_ value: Any?) -> Bool { // IMPORTANT: // .isEqual() is invoked by the bridging machinery that gets triggered whenever you use '(-a NSNumber value-) as{,?,!} Int', so using a refutable pattern ('case let other as NSNumber') below will cause an infinite loop if value is an Int, and similarly for other types we can bridge to. // To prevent this, _this check must come first._ If you change it, _do not use the 'as' operator_ or any of its variants _unless_ you know that value _is_ actually a NSNumber to avoid infinite loops. ('is' is fine.) if let value = value, value is NSNumber { return compare(value as! NSNumber) == .orderedSame } switch value { case let other as Int: return intValue == other case let other as Double: return doubleValue == other case let other as Bool: return boolValue == other default: return false } } open override var objCType: UnsafePointer<Int8> { func _objCType(_ staticString: StaticString) -> UnsafePointer<Int8> { return UnsafeRawPointer(staticString.utf8Start).assumingMemoryBound(to: Int8.self) } let numberType = _CFNumberGetType2(_cfObject) switch numberType { case kCFNumberSInt8Type: return _objCType("c") case kCFNumberSInt16Type: return _objCType("s") case kCFNumberSInt32Type: return _objCType("i") case kCFNumberSInt64Type: return _objCType("q") case kCFNumberFloat32Type: return _objCType("f") case kCFNumberFloat64Type: return _objCType("d") case kCFNumberSInt128Type: return _objCType("Q") default: fatalError("unsupported CFNumberType: '\(numberType)'") } } internal var _swiftValueOfOptimalType: Any { if self === kCFBooleanTrue { return true } else if self === kCFBooleanFalse { return false } let numberType = _CFNumberGetType2(_cfObject) switch numberType { case kCFNumberSInt8Type: return Int(int8Value) case kCFNumberSInt16Type: return Int(int16Value) case kCFNumberSInt32Type: return Int(int32Value) case kCFNumberSInt64Type: return int64Value < Int.max ? Int(int64Value) : int64Value case kCFNumberFloat32Type: return floatValue case kCFNumberFloat64Type: return doubleValue case kCFNumberSInt128Type: // If the high portion is 0, return just the low portion as a UInt64, which reasonably fixes trying to roundtrip UInt.max and UInt64.max. if int128Value.high == 0 { return int128Value.low } else { return int128Value } default: fatalError("unsupported CFNumberType: '\(numberType)'") } } deinit { _CFDeinit(self) } private convenience init(bytes: UnsafeRawPointer, numberType: CFNumberType) { let cfnumber = CFNumberCreate(nil, numberType, bytes) self.init(factory: { cast(unsafeBitCast(cfnumber, to: NSNumber.self)) }) } public convenience init(value: Int8) { var value = value self.init(bytes: &value, numberType: kCFNumberSInt8Type) } public convenience init(value: UInt8) { var value = Int16(value) self.init(bytes: &value, numberType: kCFNumberSInt16Type) } public convenience init(value: Int16) { var value = value self.init(bytes: &value, numberType: kCFNumberSInt16Type) } public convenience init(value: UInt16) { var value = Int32(value) self.init(bytes: &value, numberType: kCFNumberSInt32Type) } public convenience init(value: Int32) { var value = value self.init(bytes: &value, numberType: kCFNumberSInt32Type) } public convenience init(value: UInt32) { var value = Int64(value) self.init(bytes: &value, numberType: kCFNumberSInt64Type) } public convenience init(value: Int) { var value = value #if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le) self.init(bytes: &value, numberType: kCFNumberSInt64Type) #elseif arch(i386) || arch(arm) self.init(bytes: &value, numberType: kCFNumberSInt32Type) #endif } public convenience init(value: UInt) { #if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le) if value > UInt64(Int64.max) { var value = CFSInt128Struct(high: 0, low: UInt64(value)) self.init(bytes: &value, numberType: kCFNumberSInt128Type) } else { var value = Int64(value) self.init(bytes: &value, numberType: kCFNumberSInt64Type) } #elseif arch(i386) || arch(arm) var value = Int64(value) self.init(bytes: &value, numberType: kCFNumberSInt64Type) #endif } public convenience init(value: Int64) { var value = value self.init(bytes: &value, numberType: kCFNumberSInt64Type) } public convenience init(value: UInt64) { if value > UInt64(Int64.max) { var value = CFSInt128Struct(high: 0, low: UInt64(value)) self.init(bytes: &value, numberType: kCFNumberSInt128Type) } else { var value = Int64(value) self.init(bytes: &value, numberType: kCFNumberSInt64Type) } } public convenience init(value: Float) { var value = value self.init(bytes: &value, numberType: kCFNumberFloatType) } public convenience init(value: Double) { var value = value self.init(bytes: &value, numberType: kCFNumberDoubleType) } public convenience init(value: Bool) { self.init(factory: cast(value._bridgeToObjectiveC)) } override internal init() { super.init() } public required convenience init(bytes buffer: UnsafeRawPointer, objCType: UnsafePointer<Int8>) { guard let type = _NSSimpleObjCType(UInt8(objCType.pointee)) else { fatalError("NSNumber.init: unsupported type encoding spec '\(String(cString: objCType))'") } switch type { case .Bool: self.init(value:buffer.load(as: Bool.self)) case .Char: self.init(value:buffer.load(as: Int8.self)) case .UChar: self.init(value:buffer.load(as: UInt8.self)) case .Short: self.init(value:buffer.load(as: Int16.self)) case .UShort: self.init(value:buffer.load(as: UInt16.self)) case .Int, .Long: self.init(value:buffer.load(as: Int32.self)) case .UInt, .ULong: self.init(value:buffer.load(as: UInt32.self)) case .LongLong: self.init(value:buffer.load(as: Int64.self)) case .ULongLong: self.init(value:buffer.load(as: UInt64.self)) case .Float: self.init(value:buffer.load(as: Float.self)) case .Double: self.init(value:buffer.load(as: Double.self)) default: fatalError("NSNumber.init: unsupported type encoding spec '\(String(cString: objCType))'") } } public required convenience init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.number") { let number = aDecoder._decodePropertyListForKey("NS.number") if let val = number as? Double { self.init(value:val) } else if let val = number as? Int { self.init(value:val) } else if let val = number as? Bool { self.init(value:val) } else { return nil } } else { if aDecoder.containsValue(forKey: "NS.boolval") { self.init(value: aDecoder.decodeBool(forKey: "NS.boolval")) } else if aDecoder.containsValue(forKey: "NS.intval") { self.init(value: aDecoder.decodeInt64(forKey: "NS.intval")) } else if aDecoder.containsValue(forKey: "NS.dblval") { self.init(value: aDecoder.decodeDouble(forKey: "NS.dblval")) } else { return nil } } } open var int8Value: Int8 { var value: Int64 = 0 CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value) return .init(truncatingIfNeeded: value) } open var uint8Value: UInt8 { var value: Int64 = 0 CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value) return .init(truncatingIfNeeded: value) } open var int16Value: Int16 { var value: Int64 = 0 CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value) return .init(truncatingIfNeeded: value) } open var uint16Value: UInt16 { var value: Int64 = 0 CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value) return .init(truncatingIfNeeded: value) } open var int32Value: Int32 { var value: Int64 = 0 CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value) return .init(truncatingIfNeeded: value) } open var uint32Value: UInt32 { var value: Int64 = 0 CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value) return .init(truncatingIfNeeded: value) } open var int64Value: Int64 { var value: Int64 = 0 CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value) return .init(truncatingIfNeeded: value) } open var uint64Value: UInt64 { var value = CFSInt128Struct(high: 0, low: 0) CFNumberGetValue(_cfObject, kCFNumberSInt128Type, &value) return .init(truncatingIfNeeded: value.low) } private var int128Value: CFSInt128Struct { var value = CFSInt128Struct(high: 0, low: 0) CFNumberGetValue(_cfObject, kCFNumberSInt128Type, &value) return value } open var floatValue: Float { var value: Float = 0 CFNumberGetValue(_cfObject, kCFNumberFloatType, &value) return value } open var doubleValue: Double { var value: Double = 0 CFNumberGetValue(_cfObject, kCFNumberDoubleType, &value) return value } open var boolValue: Bool { // Darwin Foundation NSNumber appears to have a bug and return false for NSNumber(value: Int64.min).boolValue, // even though the documentation says: // "A 0 value always means false, and any nonzero value is interpreted as true." return (int64Value != 0) && (int64Value != Int64.min) } open var intValue: Int { var val: Int = 0 withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<Int>) -> Void in CFNumberGetValue(_cfObject, kCFNumberLongType, value) } return val } open var uintValue: UInt { var val: UInt = 0 withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<UInt>) -> Void in CFNumberGetValue(_cfObject, kCFNumberLongType, value) } return val } open var stringValue: String { return self.description } /// Create an instance initialized to `value`. public required convenience init(integerLiteral value: Int) { self.init(value: value) } /// Create an instance initialized to `value`. public required convenience init(floatLiteral value: Double) { self.init(value: value) } /// Create an instance initialized to `value`. public required convenience init(booleanLiteral value: Bool) { self.init(value: value) } open func compare(_ otherNumber: NSNumber) -> ComparisonResult { switch (_cfNumberType(), otherNumber._cfNumberType()) { case (kCFNumberFloatType, _), (_, kCFNumberFloatType): fallthrough case (kCFNumberDoubleType, _), (_, kCFNumberDoubleType): let (lhs, rhs) = (doubleValue, otherNumber.doubleValue) // Apply special handling for NaN as <, >, == always return false // when comparing with NaN if lhs.isNaN && rhs.isNaN { return .orderedSame } if lhs.isNaN { return .orderedAscending } if rhs.isNaN { return .orderedDescending } if lhs < rhs { return .orderedAscending } if lhs > rhs { return .orderedDescending } return .orderedSame default: // For signed and unsigned integers expand upto S128Int let (lhs, rhs) = (int128Value, otherNumber.int128Value) if lhs.high < rhs.high { return .orderedAscending } if lhs.high > rhs.high { return .orderedDescending } if lhs.low < rhs.low { return .orderedAscending } if lhs.low > rhs.low { return .orderedDescending } return .orderedSame } } open func description(withLocale locale: Locale?) -> String { guard let locale = locale else { return self.description } switch _CFNumberGetType2(_cfObject) { case kCFNumberSInt8Type, kCFNumberCharType: return String(format: "%d", locale: locale, self.int8Value) case kCFNumberSInt16Type, kCFNumberShortType: return String(format: "%hi", locale: locale, self.int16Value) case kCFNumberSInt32Type: return String(format: "%d", locale: locale, self.int32Value) case kCFNumberIntType, kCFNumberLongType, kCFNumberNSIntegerType, kCFNumberCFIndexType: return String(format: "%ld", locale: locale, self.intValue) case kCFNumberSInt64Type, kCFNumberLongLongType: return String(format: "%lld", locale: locale, self.int64Value) case kCFNumberSInt128Type: let value = self.int128Value if value.high == 0 { return value.low.description // BUG: "%llu" doesnt work correctly and treats number as signed } else { // BUG: Note the locale is actually ignored here as this is converted using CFNumber.c:emit128() return String(format: "%@", locale: locale, unsafeBitCast(_cfObject, to: UnsafePointer<CFNumber>.self)) } case kCFNumberFloatType, kCFNumberCGFloatType, kCFNumberFloatType: return String(format: "%0.7g", locale: locale, self.floatValue) case kCFNumberFloat64Type, kCFNumberDoubleType: return String(format: "%0.16g", locale: locale, self.doubleValue) case kCFNumberCGFloatType: if Int.max == Int32.max { return String(format: "%0.7g", locale: locale, self.floatValue) } else { return String(format: "%0.16g", locale: locale, self.doubleValue) } default: fatalError("Unknown NSNumber Type") } } override open var _cfTypeID: CFTypeID { return CFNumberGetTypeID() } open override var description: String { switch _CFNumberGetType2(_cfObject) { case kCFNumberSInt8Type, kCFNumberCharType, kCFNumberSInt16Type, kCFNumberShortType, kCFNumberSInt32Type, kCFNumberIntType, kCFNumberLongType, kCFNumberNSIntegerType, kCFNumberCFIndexType: return self.intValue.description case kCFNumberSInt64Type, kCFNumberLongLongType: return self.int64Value.description case kCFNumberSInt128Type: let value = self.int128Value if value.high == 0 { return value.low.description } else { return String(format: "%@", locale: nil, unsafeBitCast(_cfObject, to: UnsafePointer<CFNumber>.self)) } case kCFNumberFloatType, kCFNumberCGFloatType, kCFNumberFloatType: return self.floatValue.description case kCFNumberFloat64Type, kCFNumberDoubleType: return self.doubleValue.description case kCFNumberCGFloatType: if Int.max == Int32.max { return self.floatValue.description } else { return self.doubleValue.description } default: fatalError("Unknown NSNumber Type") } } internal func _cfNumberType() -> CFNumberType { switch objCType.pointee { case 0x42: return kCFNumberCharType case 0x63: return kCFNumberCharType case 0x43: return kCFNumberShortType case 0x73: return kCFNumberShortType case 0x53: return kCFNumberIntType case 0x69: return kCFNumberIntType case 0x49: return Int(uint32Value) < Int(Int32.max) ? kCFNumberIntType : kCFNumberLongLongType case 0x6C: return kCFNumberLongType case 0x4C: return uintValue < UInt(Int.max) ? kCFNumberLongType : kCFNumberLongLongType case 0x66: return kCFNumberFloatType case 0x64: return kCFNumberDoubleType case 0x71: return kCFNumberLongLongType case 0x51: return kCFNumberLongLongType default: fatalError() } } internal func _getValue(_ valuePtr: UnsafeMutableRawPointer, forType type: CFNumberType) -> Bool { switch type { case kCFNumberSInt8Type: valuePtr.assumingMemoryBound(to: Int8.self).pointee = int8Value break case kCFNumberSInt16Type: valuePtr.assumingMemoryBound(to: Int16.self).pointee = int16Value break case kCFNumberSInt32Type: valuePtr.assumingMemoryBound(to: Int32.self).pointee = int32Value break case kCFNumberSInt64Type: valuePtr.assumingMemoryBound(to: Int64.self).pointee = int64Value break case kCFNumberSInt128Type: struct CFSInt128Struct { var high: Int64 var low: UInt64 } let val = int64Value valuePtr.assumingMemoryBound(to: CFSInt128Struct.self).pointee = CFSInt128Struct.init(high: (val < 0) ? -1 : 0, low: UInt64(bitPattern: val)) break case kCFNumberFloat32Type: valuePtr.assumingMemoryBound(to: Float.self).pointee = floatValue break case kCFNumberFloat64Type: valuePtr.assumingMemoryBound(to: Double.self).pointee = doubleValue default: fatalError() } return true } open override func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } if let keyedCoder = aCoder as? NSKeyedArchiver { keyedCoder._encodePropertyList(self) } else { if CFGetTypeID(self) == CFBooleanGetTypeID() { aCoder.encode(boolValue, forKey: "NS.boolval") } else { switch objCType.pointee { case 0x42: aCoder.encode(boolValue, forKey: "NS.boolval") break case 0x63: fallthrough case 0x43: fallthrough case 0x73: fallthrough case 0x53: fallthrough case 0x69: fallthrough case 0x49: fallthrough case 0x6C: fallthrough case 0x4C: fallthrough case 0x71: fallthrough case 0x51: aCoder.encode(int64Value, forKey: "NS.intval") case 0x66: fallthrough case 0x64: aCoder.encode(doubleValue, forKey: "NS.dblval") default: break } } } } open override var classForCoder: AnyClass { return NSNumber.self } } extension CFNumber : _NSBridgeable { typealias NSType = NSNumber internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) } } internal func _CFSwiftNumberGetType(_ obj: CFTypeRef) -> CFNumberType { return unsafeBitCast(obj, to: NSNumber.self)._cfNumberType() } internal func _CFSwiftNumberGetValue(_ obj: CFTypeRef, _ valuePtr: UnsafeMutableRawPointer, _ type: CFNumberType) -> Bool { return unsafeBitCast(obj, to: NSNumber.self)._getValue(valuePtr, forType: type) } internal func _CFSwiftNumberGetBoolValue(_ obj: CFTypeRef) -> Bool { return unsafeBitCast(obj, to: NSNumber.self).boolValue } protocol _NSNumberCastingWithoutBridging { var _swiftValueOfOptimalType: Any { get } } extension NSNumber: _NSNumberCastingWithoutBridging {}
ec8b2524328877cfb6a47cc742a09265
34.220104
294
0.628186
false
false
false
false
manfengjun/KYMart
refs/heads/master
Section/Cart/View/KYOrderTVCell.swift
mit
1
// // KYOrderTVCell.swift // KYMart // // Created by JUN on 2017/7/5. // Copyright © 2017年 JUN. All rights reserved. // import UIKit class KYOrderTVCell: UITableViewCell { @IBOutlet weak var productIV: UIImageView! @IBOutlet weak var productInfoL: UILabel! @IBOutlet weak var productPropertyL: UILabel! @IBOutlet weak var moneyL: UILabel! @IBOutlet weak var countL: UILabel! var model:OrderCartList? { didSet { if let text = model?.goods_name { productInfoL.text = text } if let text = model?.goods_id { let url = imageUrl(goods_id: text) productIV.sd_setImage(with: url, placeholderImage: nil) } if let text = model?.goods_price { moneyL.text = "¥\(text)" } if let text = model?.goods_num { countL.text = "X\(text)" } if let text = model?.spec_key_name { productPropertyL.text = text } } } 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 } }
590fb98e9af2a9ab3aef28cdf52a7d34
25.647059
71
0.552612
false
false
false
false
OlivierBoucher/StreamCenter
refs/heads/master
StreamCenter/Event.swift
mit
3
// // Event.swift // GamingStreamsTVApp // // Created by Olivier Boucher on 2015-10-28. // Copyright © 2015 Rivus Media Inc. All rights reserved. // import Foundation struct Event { let name : String var properties : [String : AnyObject] init(name : String, properties : [String : AnyObject]?) { self.name = name if let properties = properties { self.properties = properties } else { self.properties = [ : ] } self.properties["time"] = NSDate().timeIntervalSince1970 } mutating func signedSelf(token : String) -> Event { self.properties["token"] = token return self } static func InitializeEvent() -> Event { return Event(name: "App start", properties: nil) } static func ServiceAuthenticationEvent(serviceName: String) -> Event { return Event(name: "Service Authentication", properties: ["service" : serviceName]) } var jsonDictionary: [String : AnyObject] { get { return [ "event" : self.name, "properties" : self.properties ] } } }
671467105b927d69d9826d48b0104cd9
23.666667
91
0.568412
false
false
false
false
honghaoz/UW-Quest-iOS
refs/heads/master
UW Quest/PersonalInformation/Cells/PhoneNumberCollectionViewCell.swift
apache-2.0
1
// // PhoneNumberCollectionViewCell.swift // UW Quest // // Created by Honghao on 1/14/15. // Copyright (c) 2015 Honghao. All rights reserved. // import UIKit class PhoneNumberCollectionViewCell: TitleSubTitleCollectionViewCell { func config(phoneNumber: PersonalInformation.PhoneNumber) { self.configWithType(phoneNumber.type, preferred: phoneNumber.isPreferred, country: phoneNumber.country, telephone: phoneNumber.telephone, ext: phoneNumber.ext) } func configWithType(type: String, preferred: Bool, country: String, telephone: String, ext: String) { let title = type + (preferred ? " (preferred)" : "") var tuples = [(String, String)]() let countryTuple = ("Country code", country) tuples.append(countryTuple) let telephoneTuple = ("Telephone", telephone) tuples.append(telephoneTuple) let extensionTuple = ("Extension", ext + (ext.isEmpty ? "-" : "")) tuples.append(extensionTuple) self.config(title: title, subLabelTuples: tuples) } }
dd207506c06dd81d33c21a8d3bb48771
33.967742
167
0.660517
false
true
false
false
zavsby/ProjectHelpersSwift
refs/heads/master
Classes/SettingsManager/PHUserDefaultsSettingsStorage.swift
mit
1
// // PHUserDefaultsSettingsStorage.swift // ProjectHelpers-Swift // // Created by Sergey on 06.11.15. // Copyright © 2015 Sergey Plotkin. All rights reserved. // import Foundation public class PHUserDefaultsSettingsStorage { private let userDefaults = NSUserDefaults.standardUserDefaults() private var settings: [String: Any] = [:] } extension PHUserDefaultsSettingsStorage: PHSettingsStorageProtocol { public func saveObject<T: AnyObject>(obj: T, forKey key: String) { userDefaults.setObject(obj, forKey: key) settings[key] = obj } public func objectForKey(key: String) -> Any? { if let value = settings[key] { return value } else if let value = userDefaults.objectForKey(key) { settings[key] = value return value } else { return nil } } public func removeObjectForKey(key: String) { userDefaults.removeObjectForKey(key) settings.removeValueForKey(key) } public func supportsCache() -> Bool { return true } public func invalidateCache() { settings.removeAll() } public func clearStorage() { let appDomain = NSBundle.mainBundle().bundleIdentifier! userDefaults.removePersistentDomainForName(appDomain) invalidateCache() } }
b77ddb7fa98d4f95660ddc9c1dc5d52b
24.62963
70
0.63196
false
false
false
false
patbonecrusher/Cards
refs/heads/master
Cards/Card.swift
mit
1
// // Card.swift // PaymeSwiftly // // Created by pat on 6/13/14. // Copyright (c) 2014 CovenOfChaos. All rights reserved. // import Foundation //------------------------------------------------------------------------------------------------- public class Card: CustomStringConvertible, Equatable { public let suit: Suit public let rank: Rank public var isWild: Bool = false // MARK: Initializer/Deinitializer //--------------------------------------------------------------------------------------------- public init(rank: Rank, suit: Suit) { self.suit = suit self.rank = rank } // MARK: Public API //--------------------------------------------------------------------------------------------- public func isSameSuit(card: Card) -> Bool { return self.suit == card.suit } public func isSameRank(card: Card) -> Bool { return self.rank == card.rank } // MARK: Printable protocol //--------------------------------------------------------------------------------------------- public var description: String { get { return (suit == Suit.Special ? "\(rank)" : "\(rank) of \(suit)") } } } //------------------------------------------------------------------------------------------------- public func == (this: Card, that: Card) -> Bool { return this.suit == that.suit && this.rank == that.rank } public func != (this: Card, that: Card) -> Bool { return this.suit != that.suit || this.rank != that.rank } // This assumes Aces are low. //------------------------------------------------------------------------------------------------- public func < (this: Card, that: Card) -> Bool { return (this.suit.rawValue != that.suit.rawValue ? this.suit.rawValue < that.suit.rawValue : this.rank.rawValue < that.rank.rawValue) } // This assumes Aces are low. //------------------------------------------------------------------------------------------------- public func > (this: Card, that: Card) -> Bool { return (this.suit.rawValue != that.suit.rawValue ? this.suit.rawValue > that.suit.rawValue : this.rank.rawValue > that.rank.rawValue) } // This assumes Aces are low. //------------------------------------------------------------------------------------------------- public func <= (this: Card, that: Card) -> Bool { return (this.suit.rawValue != that.suit.rawValue ? this.suit.rawValue <= that.suit.rawValue : this.rank.rawValue <= that.rank.rawValue) } // This assumes Aces are low. //------------------------------------------------------------------------------------------------- public func >= (this: Card, that: Card) -> Bool { return (this.suit.rawValue != that.suit.rawValue ? this.suit.rawValue >= that.suit.rawValue : this.rank.rawValue >= that.rank.rawValue) }
6c51576604e5fc6161aa2710e558f8d7
41.184615
138
0.45093
false
false
false
false
KaushalElsewhere/MockingBird
refs/heads/master
MockingBird/Managers/UserServiceManager.swift
mit
1
// // UserServiceManager.swift // MockingBird // // Created by Kaushal Elsewhere on 29/07/16. // Copyright © 2016 Elsewhere. All rights reserved. // import UIKit import Firebase import FirebaseDatabase import FirebaseAuth import ARSLineProgress class UserServiceManager: NSObject { static let sharedManager = UserServiceManager() var currentUser: User? func logout(){ do { try FIRAuth.auth()?.signOut() } catch let error { print(error) return } } typealias handler = () -> Void func login(complete: handler){ } func fetechUser(){ ARSLineProgress.show() if let uid = FIRAuth.auth()?.currentUser?.uid { FIRDatabase.database().reference().child("users").child(uid).observeSingleEventOfType(.Value, withBlock: { (snapshot) in if let dictionary = snapshot.value as? [String: AnyObject] { let user = User() user.setValuesForKeysWithDictionary(dictionary) self.currentUser = user ARSLineProgress.hide() } }, withCancelBlock: nil) } } }
18ef3440447d679f5ae3dda1716073fb
23.454545
132
0.522677
false
false
false
false
TLOpenSpring/TLTranstionLib-swift
refs/heads/master
TLTranstionLib-swift/Classes/Animator/TLExplodeAnimator.swift
mit
1
// // TLExplodeAnimator.swift // Pods // 爆炸效果 // Created by Andrew on 16/5/31. // // import UIKit public class TLExplodeAnimator: TLBaseAnimator { public override func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let model = TransitionModel(context: transitionContext) model.containerView.addSubview(model.toView) model.containerView.sendSubviewToBack(model.toView) let size = model.toView.frame.size var snapshots = [UIView]() let xFactor:CGFloat = 20 let yFactor = xFactor * size.height / size.width; //开始屏幕截图 var fromViewSnapshot : UIView! //如果是UINavigation的push操作 if self.showType == .push || showType == .pop { fromViewSnapshot = model.fromView.snapshotViewAfterScreenUpdates(false) }else if self.showType == .present || showType == .dismiss{ //那就一定是使用UIViewController的 Present方式 fromViewSnapshot = model.fromView.snapshotViewAfterScreenUpdates(true) } //创建屏幕截图的每个爆炸碎片 for (var x:CGFloat = 0; x<size.width; x=x+size.width/xFactor) { for (var y:CGFloat = 0; y<size.height; y+=size.height/yFactor) { var snapshotRegion = CGRectMake(x, y, size.width/xFactor, size.height/yFactor); var flag = false if self.showType == .push{ flag = false }else if showType == .present { flag = true } var snapshot = fromViewSnapshot.resizableSnapshotViewFromRect(snapshotRegion, afterScreenUpdates: flag, withCapInsets:UIEdgeInsetsZero) snapshot.frame = snapshotRegion; model.containerView.addSubview(snapshot) snapshots.append(snapshot) } } model.containerView.sendSubviewToBack(model.fromView) let duration = self.animatorDuration UIView.animateWithDuration(duration, animations: { for item in snapshots{ let xOffset = self.randomFloatBetween(-100, bigNumber: 100) let yOffset = self.randomFloatBetween(-100, bigNumber: 100) item.frame = CGRectOffset(item.frame, xOffset, yOffset) item.alpha = 0 let transform = CGAffineTransformMakeRotation(self.randomFloatBetween(-10, bigNumber: 10)) item.transform = CGAffineTransformScale(transform, 0.01, 0.01) } }) { (finished) in for item in snapshots{ item.removeFromSuperview() } transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) } } func randomFloatBetween(smallNumber:Float,bigNumber:Float) -> CGFloat { var diff = bigNumber - smallNumber; let result = (((Float) (Float(arc4random()) % (Float(RAND_MAX) + 1)) / Float(RAND_MAX)) * diff) + smallNumber; return CGFloat(result) } }
2d1ca6c7af96fe809a0a1acce858894c
29.743119
151
0.554163
false
false
false
false
marcelganczak/swift-js-transpiler
refs/heads/master
test/weheartswift/conditionals-10.swift
mit
1
var x = 1 var y = 2 var lowX = 1 var lowY = 1 var highX = 3 var highY = 3 if x >= lowX && y >= lowY && x <= highX && y <= highY { print("inside") } else { print("not inside") }
e7af1853d59c514e505dbe4f8e65c892
14.5
55
0.524324
false
false
false
false
bhold6160/GITList
refs/heads/master
GITList/GITList/DateController.swift
mit
1
// // DateController.swift // GITList // // Created by Kenny J Hong on 8/23/17. // Copyright © 2017 Brandon Holderman. All rights reserved. // import UIKit import UserNotifications class DateViewController: UIViewController { @IBAction func action(_ sender: Any) { let content = UNMutableNotificationContent() content.title = "Milk is expring in 2days" content.subtitle = datePickerText.text! content.body = "This is body text lorem ipsum" content.badge = 1 let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger) UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) } @IBOutlet weak var datePickerText: UITextField! let datePicker = UIDatePicker() override func viewDidLoad() { super.viewDidLoad() self.view.layer.cornerRadius = 5 self.view.layer.borderWidth = 5 self.view.layer.masksToBounds = true self.view.layer.borderColor = UIColor.white.cgColor UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { didAllow, error in }) createDatePicker() // Do any additional setup after loading the view. } func createDatePicker() { //format for picker datePicker.datePickerMode = .date //toolbar let toolbar = UIToolbar() toolbar.sizeToFit() //bar button item let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed)) toolbar.setItems([doneButton], animated: false) datePickerText.inputAccessoryView = toolbar //assinging date picker to text field datePickerText.inputView = datePicker } func donePressed() { // format date let dateFormatter = DateFormatter() dateFormatter.dateStyle = .short dateFormatter.timeStyle = .none datePickerText.text = dateFormatter.string(from: datePicker.date) self.view.endEditing(true) } }
6eeeb98c8cb0506a507b64983f3238d0
26.848837
117
0.615866
false
false
false
false
weareopensource/Sample-iOS_Swift_Instagram
refs/heads/master
Sample-Swift_instagram/APIController.swift
mit
1
// // APIController.swift // Sample-Swift_instagram // // Created by RYPE on 14/05/2015. // Copyright (c) 2015 weareopensource. All rights reserved. // import Foundation /**************************************************************************************************/ // Protocol /**************************************************************************************************/ protocol APIControllerProtocol { func didReceiveAPIResults(results: NSArray) } /**************************************************************************************************/ // Class /**************************************************************************************************/ class APIController { /*************************************************/ // Main /*************************************************/ // Var /*************************/ var delegate: APIControllerProtocol // init /*************************/ init(delegate: APIControllerProtocol) { self.delegate = delegate } /*************************************************/ // Functions /*************************************************/ func get(path: String) { let url = NSURL(string: path) let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in print("Task completed") if(error != nil) { // If there is an error in the web request, print it to the console print(error!.localizedDescription) } //let jsonString = "{\"name\":\"Fred\", \"age\":40}" //let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)! do { let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary //print(jsonResult["data"]) if let results = jsonResult["data"] as? NSArray { self.delegate.didReceiveAPIResults(results) } } catch let error as NSError { print(error.description) } }) // The task is just an object with all these properties set // In order to actually make the web request, we need to "resume" task.resume() } func instagram() { get("https://api.instagram.com/v1/users/\(GlobalConstants.TwitterInstaUserId)/media/recent/?access_token=\(GlobalConstants.TwitterInstaAccessToken)") } }
20a586fbdde7e1cabfb2a4a284643887
32.17284
157
0.43022
false
false
false
false
ECP-CANDLE/Supervisor
refs/heads/master
workflows/cp-leaveout/swift/recur-3.swift
mit
1
/* WORKFLOWS SWIFT Simply run with: 'swift-t recur-1.swift | nl' Or specify the N, S values: 'swift-t workflow.swift -N=6 -S=6 | nl' for 55,986 tasks. */ /* CP LEAVEOUT SWIFT Main workflow */ import assert; import files; import io; import python; import unix; import sys; import string; import location; import math; string FRAMEWORK = "keras"; string xcorr_root = getenv("XCORR_ROOT"); string preprocess_rnaseq = getenv("PREPROP_RNASEQ"); string emews_root = getenv("EMEWS_PROJECT_ROOT"); string turbine_output = getenv("TURBINE_OUTPUT"); printf("TURBINE_OUTPUT: " + turbine_output); string db_file = argv("db_file"); string cache_dir = argv("cache_dir"); // string xcorr_data_dir = argv("xcorr_data_dir"); string gpus = argv("gpus", ""); // string restart_number = argv("restart_number", "1"); string site = argv("site"); // dummy() is now unused- retaining for debugging/demos // app (void v) dummy(string parent, int stage, int id, void block) // { // "echo" ("parent='%3s'"%parent) ("stage="+stage) ("id="+id) ; // } // Data split factor with default N = string2int(argv("N", "2")); // Maximum stage number with default // (tested up to S=7, 21,844 dummy tasks) S = string2int(argv("S", "2")); (void v) run_stage(int N, int S, string parent, int stage, int id, void block) { string node; if (parent == "") { node = int2string(id); } else { node = parent+"."+int2string(id); } // node = parent+"."+int2string(id); v = run_node(parent, stage, id, block); if (stage < S) { foreach id_child in [0:N-1] { run_stage(N, S, node, stage+1, id_child, v); } } } (void v) run_node(string node, int stage, int id, void block) { if (stage == 0) { v = propagate(); } else { // dummy() is now unused- retaining for debugging/demos // v = dummy(parent, stage, id, block); json = "{\"node\": \"%s\"}"%node; s = obj(json, node); v = propagate(s); } } stage = 0; id = 0; run_stage(N, S, "", stage, id, propagate());
c647ba52c5e2d0b7a261c84b0e77de2d
20.020833
78
0.61447
false
false
false
false
Fenrikur/ef-app_ios
refs/heads/master
Pods/Down/Source/Renderers/DownGroffRenderable.swift
mit
1
// // DownGroffRenderable.swift // Down // // Created by Rob Phillips on 5/31/16. // Copyright © 2016-2019 Glazed Donut, LLC. All rights reserved. // import Foundation import libcmark public protocol DownGroffRenderable: DownRenderable { func toGroff(_ options: DownOptions, width: Int32) throws -> String } extension DownGroffRenderable { /// Generates a groff man string from the `markdownString` property /// /// - Parameters: /// - options: `DownOptions` to modify parsing or rendering, defaulting to `.default` /// - width: The width to break on, defaulting to 0 /// - Returns: groff man string /// - Throws: `DownErrors` depending on the scenario public func toGroff(_ options: DownOptions = .default, width: Int32 = 0) throws -> String { let ast = try DownASTRenderer.stringToAST(markdownString, options: options) let groff = try DownGroffRenderer.astToGroff(ast, options: options, width: width) cmark_node_free(ast) return groff } } public struct DownGroffRenderer { /// Generates a groff man string from the given abstract syntax tree /// /// **Note:** caller is responsible for calling `cmark_node_free(ast)` after this returns /// /// - Parameters: /// - ast: The `cmark_node` representing the abstract syntax tree /// - options: `DownOptions` to modify parsing or rendering, defaulting to `.default` /// - width: The width to break on, defaulting to 0 /// - Returns: groff man string /// - Throws: `ASTRenderingError` if the AST could not be converted public static func astToGroff(_ ast: UnsafeMutablePointer<cmark_node>, options: DownOptions = .default, width: Int32 = 0) throws -> String { guard let cGroffString = cmark_render_man(ast, options.rawValue, width) else { throw DownErrors.astRenderingError } defer { free(cGroffString) } guard let groffString = String(cString: cGroffString, encoding: String.Encoding.utf8) else { throw DownErrors.astRenderingError } return groffString } }
0bc73f37ae94d6463cf7597f5476cf19
37.438596
100
0.646737
false
false
false
false
PiXeL16/BudgetShare
refs/heads/master
BudgetShareTests/Modules/BudgetDetail/BudgetDetailList/Interactor/BudgetDetailListInteractorProviderSpec.swift
mit
1
// // Created by Chris Jimenez on 8/20/18. // Copyright (c) 2018 Chris Jimenez. All rights reserved. // import Foundation import Nimble import Quick import RxSwift import FirebaseDatabase @testable import BudgetShare class BudgetDetailListInteractorProviderSpec: QuickSpec { override func spec() { describe("The Budget Detail Interactor Implementation") { var subject: BudgetDetailListInteractorProvider! var budgetService: MockFirebaseBudgetService! var output: MockBudgetDetailListInteractorOutput! beforeEach { budgetService = MockFirebaseBudgetService() subject = BudgetDetailListInteractorProvider(service: budgetService) output = MockBudgetDetailListInteractorOutput() subject.output = output } it("Inits correctly") { expect(subject.service).toNot(beNil()) } it("Gets budget information") { subject.getBudgetsInfo(budgetId: "123") expect(budgetService.invokedFetchBudgetInfo).to(beTrue()) } it("Observes budget with id successfully") { let observable: Observable<DataSnapshot> = Observable.create { observer in observer.onNext(MockFirebaseDataSnapshot()) return Disposables.create { } } budgetService.stubbedObserveBudgetResult = observable subject.observeBudget(budgetId: "123") expect(budgetService.invokedObserveBudget).to(beTrue()) expect(output.invokedBudgetInfoSucceed).to(beTrue()) } it("Observes budget with id with error") { let observable: Observable<DataSnapshot> = Observable.create { observer in observer.onError(NSError(domain: "test", code: 400)) return Disposables.create { } } budgetService.stubbedObserveBudgetResult = observable subject.observeBudget(budgetId: "123") expect(budgetService.invokedObserveBudget).to(beTrue()) expect(output.invokedBudgetInfoFailed).to(beTrue()) expect(output.invokedBudgetInfoSucceed).to(beFalse()) } } } }
c29867ade232e1ef531e1deec0cb376d
32.347222
90
0.596002
false
false
false
false
proversity-org/edx-app-ios
refs/heads/master
Source/CourseLastAccessedController.swift
apache-2.0
1
// // CourseLastAccessedController.swift // edX // // Created by Ehmad Zubair Chughtai on 03/07/2015. // Copyright (c) 2015 edX. All rights reserved. // import UIKit public protocol CourseLastAccessedControllerDelegate : class { func courseLastAccessedControllerDidFetchLastAccessedItem(item : CourseLastAccessed?) } public class CourseLastAccessedController: NSObject { private let lastAccessedLoader = BackedStream<(CourseBlock, CourseLastAccessed)>() private let blockID : CourseBlockID? private let dataManager : DataManager private let networkManager : NetworkManager private let courseQuerier : CourseOutlineQuerier private let lastAccessedProvider : LastAccessedProvider? private let courseOutlineMode : CourseOutlineMode private var courseID : String { return courseQuerier.courseID } public weak var delegate : CourseLastAccessedControllerDelegate? /// Strictly a test variable used as a trigger flag. Not to be used out of the test scope private var t_hasTriggeredSetLastAccessed = false public init(blockID : CourseBlockID?, dataManager : DataManager, networkManager : NetworkManager, courseQuerier: CourseOutlineQuerier, lastAccessedProvider : LastAccessedProvider? = nil, forMode mode: CourseOutlineMode) { self.blockID = blockID self.dataManager = dataManager self.networkManager = networkManager self.courseQuerier = courseQuerier self.lastAccessedProvider = lastAccessedProvider ?? dataManager.interface courseOutlineMode = mode super.init() addListener() } fileprivate var canShowLastAccessed : Bool { // We only show at the root level return blockID == nil && courseOutlineMode == .full } fileprivate var canUpdateLastAccessed : Bool { return blockID != nil && courseOutlineMode == .full } public func loadLastAccessed(forMode mode: CourseOutlineMode) { if !canShowLastAccessed { return } if let firstLoad = lastAccessedProvider?.getLastAccessedSectionForCourseID(courseID: self.courseID) { let blockStream = expandAccessStream(stream: OEXStream(value : firstLoad), forMode : mode) lastAccessedLoader.backWithStream(blockStream) } let request = UserAPI.requestLastVisitedModuleForCourseID(courseID: courseID) let lastAccessed = self.networkManager.streamForRequest(request) lastAccessedLoader.backWithStream(expandAccessStream(stream: lastAccessed, forMode : mode)) } public func saveLastAccessed() { if !canUpdateLastAccessed { return } if let currentCourseBlockID = self.blockID { t_hasTriggeredSetLastAccessed = true let request = UserAPI.setLastVisitedModuleForBlockID(blockID: self.courseID, module_id: currentCourseBlockID) let courseID = self.courseID expandAccessStream(stream: self.networkManager.streamForRequest(request)).extendLifetimeUntilFirstResult {[weak self] result in result.ifSuccess() {info in let block = info.0 let lastAccessedItem = info.1 if let owner = self { owner.lastAccessedProvider?.setLastAccessedSubSectionWithID(subsectionID: lastAccessedItem.moduleId, subsectionName: block.displayName, courseID: courseID, timeStamp: (DateFormatting.serverString(withDate: NSDate())) ?? "") } } } } } func addListener() { lastAccessedLoader.listen(self) {[weak self] info in info.ifSuccess { let block = $0.0 var item = $0.1 item.moduleName = block.displayName self?.lastAccessedProvider?.setLastAccessedSubSectionWithID(subsectionID: item.moduleId, subsectionName: block.displayName, courseID: self?.courseID, timeStamp: DateFormatting.serverString(withDate: NSDate()) ?? "") self?.delegate?.courseLastAccessedControllerDidFetchLastAccessedItem(item: item) } info.ifFailure { [weak self] error in self?.delegate?.courseLastAccessedControllerDidFetchLastAccessedItem(item: nil) } } } private func expandAccessStream(stream: OEXStream<CourseLastAccessed>, forMode mode: CourseOutlineMode = .full) -> OEXStream<(CourseBlock, CourseLastAccessed)> { return stream.transform {[weak self] lastAccessed in return joinStreams((self?.courseQuerier.blockWithID(id: lastAccessed.moduleId, mode: mode)) ?? OEXStream<CourseBlock>(), OEXStream(value: lastAccessed)) } } } extension CourseLastAccessedController { public func t_canShowLastAccessed() -> Bool{ return canShowLastAccessed } public func t_canUpdateLastAccessed() -> Bool{ return canUpdateLastAccessed } }
c245a82548e5f5376d0c9d00504b9522
39.170543
231
0.65824
false
false
false
false
ericberman/MyFlightbookiOS
refs/heads/master
MyFlightbookWatch Extension/CurrencyInterfaceController.swift
gpl-3.0
1
/* MyFlightbook for iOS - provides native access to MyFlightbook pilot's logbook Copyright (C) 2017 MyFlightbook, LLC This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ // // CurrencyInterfaceController.swift // MFBSample // // Created by Eric Berman on 10/29/15. // // import WatchKit import WatchConnectivity import Foundation class CurrencyInterfaceController: RefreshableTableController { var lastData : [SimpleCurrencyItem]? override func awake(withContext context: Any?) { super.awake(withContext: context) } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() // force a refresh of totals if (a) we have no data, (b) we have no totals, (c) we have no lastUpdate or (d) lastUpdate is more than 1 hour old if (lastData == nil || self.dataIsExpired()) { refresh(); } updateTable() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } override func updateTable() { if let items = lastData { self.table.setNumberOfRows(items.count, withRowType: "tblCurrency") if (items.count == 0) { lblError.setHidden(false) } for (index, item) in items.enumerated() { let row = self.table.rowController(at: index) as! CurrencyTableRowController row.lblCurrencyTitle.setText(item.attribute as String) row.lblCurrencyStatus.setText(item.value as String) row.lblCurrencyDiscrepancy.setText(item.discrepancy as String) switch (item.state) { case MFBWebServiceSvc_CurrencyState_NotCurrent: row.lblCurrencyStatus.setTextColor(UIColor.red) case MFBWebServiceSvc_CurrencyState_GettingClose: row.lblCurrencyStatus.setTextColor(UIColor.blue) case MFBWebServiceSvc_CurrencyState_OK: row.lblCurrencyStatus.setTextColor(UIColor(red: 0, green: 0.5, blue: 0, alpha: 1.0)) default: break; } } } } override func refreshRequest() -> [String : String] { return [WATCH_MESSAGE_REQUEST_DATA : WATCH_REQUEST_CURRENCY] } override func bindRefreshResult(_ dictResult: NSDictionary!) { if let statusData = dictResult[WATCH_RESPONSE_CURRENCY] as? Data { if let data = NSKeyedUnarchiver.unarchiveObject(with: statusData) as? [SimpleCurrencyItem] { self.lastData = data self.lastUpdate = Date() self.updateTable() } } } }
02137684949d5e87b75bac420474d288
35.210526
151
0.636919
false
false
false
false
Ashok28/Kingfisher
refs/heads/master
DYLive/Pods/Kingfisher/Sources/Extensions/NSTextAttachment+Kingfisher.swift
mit
4
// // NSTextAttachment+Kingfisher.swift // Kingfisher // // Created by Benjamin Briggs on 22/07/2019. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if !os(watchOS) #if os(macOS) import AppKit #else import UIKit #endif extension KingfisherWrapper where Base: NSTextAttachment { // MARK: Setting Image /// Sets an image to the text attachment with a source. /// /// - Parameters: /// - source: The `Source` object defines data information from network or a data provider. /// - attributedView: The owner of the attributed string which this `NSTextAttachment` is added. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// /// Internally, this method will use `KingfisherManager` to get the requested source /// Since this method will perform UI changes, you must call it from the main thread. /// /// The retrieved image will be set to `NSTextAttachment.image` property. Because it is not an image view based /// rendering, options related to view, such as `.transition`, are not supported. /// /// Kingfisher will call `setNeedsDisplay` on the `attributedView` when the image task done. It gives the view a /// chance to render the attributed string again for displaying the downloaded image. For example, if you set an /// attributed with this `NSTextAttachment` to a `UILabel` object, pass it as the `attributedView` parameter. /// /// Here is a typical use case: /// /// ```swift /// let attributedText = NSMutableAttributedString(string: "Hello World") /// let textAttachment = NSTextAttachment() /// /// textAttachment.kf.setImage( /// with: URL(string: "https://onevcat.com/assets/images/avatar.jpg")!, /// attributedView: label, /// options: [ /// .processor( /// ResizingImageProcessor(referenceSize: .init(width: 30, height: 30)) /// |> RoundCornerImageProcessor(cornerRadius: 15)) /// ] /// ) /// attributedText.replaceCharacters(in: NSRange(), with: NSAttributedString(attachment: textAttachment)) /// label.attributedText = attributedText /// ``` /// @discardableResult public func setImage( with source: Source?, attributedView: @autoclosure @escaping () -> KFCrossPlatformView, placeholder: KFCrossPlatformImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) return setImage( with: source, attributedView: attributedView, placeholder: placeholder, parsedOptions: options, progressBlock: progressBlock, completionHandler: completionHandler ) } /// Sets an image to the text attachment with a source. /// /// - Parameters: /// - resource: The `Resource` object contains information about the resource. /// - attributedView: The owner of the attributed string which this `NSTextAttachment` is added. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// /// Internally, this method will use `KingfisherManager` to get the requested source /// Since this method will perform UI changes, you must call it from the main thread. /// /// The retrieved image will be set to `NSTextAttachment.image` property. Because it is not an image view based /// rendering, options related to view, such as `.transition`, are not supported. /// /// Kingfisher will call `setNeedsDisplay` on the `attributedView` when the image task done. It gives the view a /// chance to render the attributed string again for displaying the downloaded image. For example, if you set an /// attributed with this `NSTextAttachment` to a `UILabel` object, pass it as the `attributedView` parameter. /// /// Here is a typical use case: /// /// ```swift /// let attributedText = NSMutableAttributedString(string: "Hello World") /// let textAttachment = NSTextAttachment() /// /// textAttachment.kf.setImage( /// with: URL(string: "https://onevcat.com/assets/images/avatar.jpg")!, /// attributedView: label, /// options: [ /// .processor( /// ResizingImageProcessor(referenceSize: .init(width: 30, height: 30)) /// |> RoundCornerImageProcessor(cornerRadius: 15)) /// ] /// ) /// attributedText.replaceCharacters(in: NSRange(), with: NSAttributedString(attachment: textAttachment)) /// label.attributedText = attributedText /// ``` /// @discardableResult public func setImage( with resource: Resource?, attributedView: @autoclosure @escaping () -> KFCrossPlatformView, placeholder: KFCrossPlatformImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) return setImage( with: resource.map { .network($0) }, attributedView: attributedView, placeholder: placeholder, parsedOptions: options, progressBlock: progressBlock, completionHandler: completionHandler ) } func setImage( with source: Source?, attributedView: @escaping () -> KFCrossPlatformView, placeholder: KFCrossPlatformImage? = nil, parsedOptions: KingfisherParsedOptionsInfo, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { var mutatingSelf = self guard let source = source else { base.image = placeholder mutatingSelf.taskIdentifier = nil completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) return nil } var options = parsedOptions if !options.keepCurrentImageWhileLoading { base.image = placeholder } let issuedIdentifier = Source.Identifier.next() mutatingSelf.taskIdentifier = issuedIdentifier if let block = progressBlock { options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] } if let provider = ImageProgressiveProvider(options, refresh: { image in self.base.image = image }) { options.onDataReceived = (options.onDataReceived ?? []) + [provider] } options.onDataReceived?.forEach { $0.onShouldApply = { issuedIdentifier == self.taskIdentifier } } let task = KingfisherManager.shared.retrieveImage( with: source, options: options, completionHandler: { result in CallbackQueue.mainCurrentOrAsync.execute { guard issuedIdentifier == self.taskIdentifier else { let reason: KingfisherError.ImageSettingErrorReason do { let value = try result.get() reason = .notCurrentSourceTask(result: value, error: nil, source: source) } catch { reason = .notCurrentSourceTask(result: nil, error: error, source: source) } let error = KingfisherError.imageSettingError(reason: reason) completionHandler?(.failure(error)) return } mutatingSelf.imageTask = nil mutatingSelf.taskIdentifier = nil switch result { case .success(let value): self.base.image = value.image let view = attributedView() #if canImport(UIKit) view.setNeedsDisplay() #else view.setNeedsDisplay(view.bounds) #endif case .failure: if let image = options.onFailureImage { self.base.image = image } } completionHandler?(result) } } ) mutatingSelf.imageTask = task return task } // MARK: Cancelling Image /// Cancel the image download task bounded to the text attachment if it is running. /// Nothing will happen if the downloading has already finished. public func cancelDownloadTask() { imageTask?.cancel() } } private var taskIdentifierKey: Void? private var imageTaskKey: Void? // MARK: Properties extension KingfisherWrapper where Base: NSTextAttachment { public private(set) var taskIdentifier: Source.Identifier.Value? { get { let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey) return box?.value } set { let box = newValue.map { Box($0) } setRetainedAssociatedObject(base, &taskIdentifierKey, box) } } private var imageTask: DownloadTask? { get { return getAssociatedObject(base, &imageTaskKey) } set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} } } #endif
862841e090d99c5c1bb6086f647369f4
41.935484
119
0.629017
false
false
false
false
antonio081014/LeeCode-CodeBase
refs/heads/main
Swift/verify-preorder-serialization-of-a-binary-tree.swift
mit
2
/** * https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ * * */ // Date: Tue Apr 21 15:41:04 PDT 2020 /// Ref: https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/discuss/78551/7-lines-Easy-Java-Solution /// Some used stack. Some used the depth of a stack. Here I use a different perspective. In a binary tree, if we consider null as leaves, then /// /// all non-null node provides 2 outdegree and 1 indegree (2 children and 1 parent), except root /// all null node provides 0 outdegree and 1 indegree (0 child and 1 parent). /// Suppose we try to build this tree. During building, we record the difference between out degree and in degree diff = outdegree - indegree. When the next node comes, we then decrease diff by 1, because the node provides an in degree. If the node is not null, we increase diff by 2, because it provides two out degrees. If a serialization is correct, diff should never be negative and diff will be zero when finished. /// /// - Complexity: /// - Time: O(n), n is the number elements in the tree. /// - Space: O(1) /// class Solution { func isValidSerialization(_ preorder: String) -> Bool { let nodes = preorder.split(separator: ",") var degree = 1 for node in nodes { degree -= 1 if degree < 0 { return false } degree += node == "#" ? 0 : 2 } return degree == 0 } } /** * https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ * * */ // Date: Tue Apr 21 16:12:15 PDT 2020 /// Using stack. /// - Complexity: /// - Time: O(n), n is the number elements in the tree. /// - Space: O(1) class Solution { func isValidSerialization(_ preorder: String) -> Bool { var stack: [String] = [] let nodes = preorder.split(separator: ",") for node in nodes { stack.append(String(node)) if node == "#" { // 1,#,2,#,3,#,# while stack.count > 2 { let n = stack.count if stack[n - 1] == "#" && stack[n - 2] == "#" && stack[n - 3] != "#" { stack.removeLast() stack.removeLast() stack.removeLast() stack.append(String(node)) } else { break } } } } return stack.count == 1 && stack[0] == "#" } }
42ebf3dbaace1cb97f2cc080592fe37f
38.609375
419
0.557002
false
false
false
false
Ehrippura/firefox-ios
refs/heads/master
Storage/Bookmarks/BookmarksModel.swift
mpl-2.0
5
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Deferred import Foundation import Shared private let log = Logger.syncLogger /** * The kinda-immutable base interface for bookmarks and folders. */ open class BookmarkNode { open var id: Int? open let guid: GUID open let title: String open let isEditable: Bool open var favicon: Favicon? init(guid: GUID, title: String, isEditable: Bool=false) { self.guid = guid self.title = title self.isEditable = isEditable } open var canDelete: Bool { return self.isEditable } } open class BookmarkSeparator: BookmarkNode { init(guid: GUID) { super.init(guid: guid, title: "—") } } /** * An immutable item representing a bookmark. * * To modify this, issue changes against the backing store and get an updated model. */ open class BookmarkItem: BookmarkNode { open let url: String! public init(guid: String, title: String, url: String, isEditable: Bool=false) { self.url = url super.init(guid: guid, title: title, isEditable: isEditable) } } /** * A folder is an immutable abstraction over a named * thing that can return its child nodes by index. */ open class BookmarkFolder: BookmarkNode { open var count: Int { return 0 } open subscript(index: Int) -> BookmarkNode? { return nil } open func itemIsEditableAtIndex(_ index: Int) -> Bool { return self[index]?.canDelete ?? false } override open var canDelete: Bool { return false } open func removeItemWithGUID(_ guid: GUID) -> BookmarkFolder? { return nil } } /** * A model is a snapshot of the bookmarks store, suitable for backing a table view. * * Navigation through the folder hierarchy produces a sequence of models. * * Changes to the backing store implicitly invalidates a subset of models. * * 'Refresh' means requesting a new model from the store. */ open class BookmarksModel: BookmarksModelFactorySource { fileprivate let factory: BookmarksModelFactory open let modelFactory: Deferred<Maybe<BookmarksModelFactory>> open let current: BookmarkFolder public init(modelFactory: BookmarksModelFactory, root: BookmarkFolder) { self.factory = modelFactory self.modelFactory = deferMaybe(modelFactory) self.current = root } /** * Produce a new model rooted at the appropriate folder. Fails if the folder doesn't exist. */ open func selectFolder(_ folder: BookmarkFolder) -> Deferred<Maybe<BookmarksModel>> { return self.factory.modelForFolder(folder) } /** * Produce a new model rooted at the appropriate folder. Fails if the folder doesn't exist. */ open func selectFolder(_ guid: String) -> Deferred<Maybe<BookmarksModel>> { return self.factory.modelForFolder(guid) } /** * Produce a new model rooted at the base of the hierarchy. Should never fail. */ open func selectRoot() -> Deferred<Maybe<BookmarksModel>> { return self.factory.modelForRoot() } /** * Produce a new model with a memory-backed root with the given GUID removed from the current folder */ open func removeGUIDFromCurrent(_ guid: GUID) -> BookmarksModel { if let removedRoot = self.current.removeItemWithGUID(guid) { return BookmarksModel(modelFactory: self.factory, root: removedRoot) } log.warning("BookmarksModel.removeGUIDFromCurrent did not remove anything. Check to make sure you're not using the abstract BookmarkFolder class.") return self } /** * Produce a new model rooted at the same place as this model. Can fail if * the folder has been deleted from the backing store. */ open func reloadData() -> Deferred<Maybe<BookmarksModel>> { return self.factory.modelForFolder(current) } open var canDelete: Bool { return false } } public protocol BookmarksModelFactorySource { var modelFactory: Deferred<Maybe<BookmarksModelFactory>> { get } } public protocol BookmarksModelFactory { func factoryForIndex(_ index: Int, inFolder folder: BookmarkFolder) -> BookmarksModelFactory func modelForFolder(_ folder: BookmarkFolder) -> Deferred<Maybe<BookmarksModel>> func modelForFolder(_ guid: GUID) -> Deferred<Maybe<BookmarksModel>> func modelForFolder(_ guid: GUID, title: String) -> Deferred<Maybe<BookmarksModel>> func modelForRoot() -> Deferred<Maybe<BookmarksModel>> // Whenever async construction is necessary, we fall into a pattern of needing // a placeholder that behaves correctly for the period between kickoff and set. var nullModel: BookmarksModel { get } func isBookmarked(_ url: String) -> Deferred<Maybe<Bool>> func removeByGUID(_ guid: GUID) -> Success @discardableResult func removeByURL(_ url: String) -> Success } /* * A folder that contains an array of children. */ open class MemoryBookmarkFolder: BookmarkFolder, Sequence { let children: [BookmarkNode] public init(guid: GUID, title: String, children: [BookmarkNode]) { self.children = children super.init(guid: guid, title: title) } public struct BookmarkNodeGenerator: IteratorProtocol { public typealias Element = BookmarkNode let children: [BookmarkNode] var index: Int = 0 init(children: [BookmarkNode]) { self.children = children } public mutating func next() -> BookmarkNode? { if index < children.count { defer { index += 1 } return children[index] } return nil } } override open var favicon: Favicon? { get { if let path = Bundle.main.path(forResource: "bookmarkFolder", ofType: "png") { let url = URL(fileURLWithPath: path) return Favicon(url: url.absoluteString, date: Date(), type: IconType.local) } return nil } set { } } override open var count: Int { return children.count } override open subscript(index: Int) -> BookmarkNode { get { return children[index] } } override open func itemIsEditableAtIndex(_ index: Int) -> Bool { return true } override open func removeItemWithGUID(_ guid: GUID) -> BookmarkFolder? { let without = children.filter { $0.guid != guid } return MemoryBookmarkFolder(guid: self.guid, title: self.title, children: without) } open func makeIterator() -> BookmarkNodeGenerator { return BookmarkNodeGenerator(children: self.children) } /** * Return a new immutable folder that's just like this one, * but also contains the new items. */ func append(_ items: [BookmarkNode]) -> MemoryBookmarkFolder { if items.isEmpty { return self } return MemoryBookmarkFolder(guid: self.guid, title: self.title, children: self.children + items) } } open class MemoryBookmarksSink: ShareToDestination { var queue: [BookmarkNode] = [] public init() { } open func shareItem(_ item: ShareItem) -> Success { let title = item.title == nil ? "Untitled" : item.title! func exists(_ e: BookmarkNode) -> Bool { if let bookmark = e as? BookmarkItem { return bookmark.url == item.url } return false } // Don't create duplicates. if !queue.contains(where: exists) { queue.append(BookmarkItem(guid: Bytes.generateGUID(), title: title, url: item.url)) } return succeed() } } private extension SuggestedSite { func asBookmark() -> BookmarkNode { let b = BookmarkItem(guid: self.guid ?? Bytes.generateGUID(), title: self.title, url: self.url) b.favicon = self.icon return b } } open class PrependedBookmarkFolder: BookmarkFolder { let main: BookmarkFolder fileprivate let prepend: BookmarkNode init(main: BookmarkFolder, prepend: BookmarkNode) { self.main = main self.prepend = prepend super.init(guid: main.guid, title: main.guid) } override open var count: Int { return self.main.count + 1 } override open subscript(index: Int) -> BookmarkNode? { if index == 0 { return self.prepend } return self.main[index - 1] } override open func itemIsEditableAtIndex(_ index: Int) -> Bool { return index > 0 && self.main.itemIsEditableAtIndex(index - 1) } override open func removeItemWithGUID(_ guid: GUID) -> BookmarkFolder? { guard let removedFolder = main.removeItemWithGUID(guid) else { log.warning("Failed to remove child item from prepended folder. Check that main folder overrides removeItemWithGUID.") return nil } return PrependedBookmarkFolder(main: removedFolder, prepend: prepend) } } open class ConcatenatedBookmarkFolder: BookmarkFolder { fileprivate let main: BookmarkFolder fileprivate let append: BookmarkFolder init(main: BookmarkFolder, append: BookmarkFolder) { self.main = main self.append = append super.init(guid: main.guid, title: main.title) } var pivot: Int { return main.count } override open var count: Int { return main.count + append.count } override open subscript(index: Int) -> BookmarkNode? { return index < main.count ? main[index] : append[index - main.count] } override open func itemIsEditableAtIndex(_ index: Int) -> Bool { return index < main.count ? main.itemIsEditableAtIndex(index) : append.itemIsEditableAtIndex(index - main.count) } override open func removeItemWithGUID(_ guid: GUID) -> BookmarkFolder? { let newMain = main.removeItemWithGUID(guid) ?? main let newAppend = append.removeItemWithGUID(guid) ?? append return ConcatenatedBookmarkFolder(main: newMain, append: newAppend) } } /** * A trivial offline model factory that represents a simple hierarchy. */ open class MockMemoryBookmarksStore: BookmarksModelFactory, ShareToDestination { let mobile: MemoryBookmarkFolder let root: MemoryBookmarkFolder var unsorted: MemoryBookmarkFolder let sink: MemoryBookmarksSink public init() { let res = [BookmarkItem]() mobile = MemoryBookmarkFolder(guid: BookmarkRoots.MobileFolderGUID, title: "Mobile Bookmarks", children: res) unsorted = MemoryBookmarkFolder(guid: BookmarkRoots.UnfiledFolderGUID, title: "Unsorted Bookmarks", children: []) sink = MemoryBookmarksSink() root = MemoryBookmarkFolder(guid: BookmarkRoots.RootGUID, title: "Root", children: [mobile, unsorted]) } public func factoryForIndex(_ index: Int, inFolder folder: BookmarkFolder) -> BookmarksModelFactory { return self } open func modelForFolder(_ folder: BookmarkFolder) -> Deferred<Maybe<BookmarksModel>> { return self.modelForFolder(folder.guid, title: folder.title) } open func modelForFolder(_ guid: GUID) -> Deferred<Maybe<BookmarksModel>> { return self.modelForFolder(guid, title: "") } open func modelForFolder(_ guid: GUID, title: String) -> Deferred<Maybe<BookmarksModel>> { var m: BookmarkFolder switch guid { case BookmarkRoots.MobileFolderGUID: // Transparently merges in any queued items. m = self.mobile.append(self.sink.queue) break case BookmarkRoots.RootGUID: m = self.root break case BookmarkRoots.UnfiledFolderGUID: m = self.unsorted break default: return deferMaybe(DatabaseError(description: "No such folder \(guid).")) } return deferMaybe(BookmarksModel(modelFactory: self, root: m)) } open func modelForRoot() -> Deferred<Maybe<BookmarksModel>> { return deferMaybe(BookmarksModel(modelFactory: self, root: self.root)) } /** * This class could return the full data immediately. We don't, because real DB-backed code won't. */ open var nullModel: BookmarksModel { let f = MemoryBookmarkFolder(guid: BookmarkRoots.RootGUID, title: "Root", children: []) return BookmarksModel(modelFactory: self, root: f) } open func shareItem(_ item: ShareItem) -> Success { return self.sink.shareItem(item) } open func isBookmarked(_ url: String) -> Deferred<Maybe<Bool>> { return deferMaybe(DatabaseError(description: "Not implemented")) } open func removeByGUID(_ guid: GUID) -> Success { return deferMaybe(DatabaseError(description: "Not implemented")) } open func removeByURL(_ url: String) -> Success { return deferMaybe(DatabaseError(description: "Not implemented")) } open func clearBookmarks() -> Success { return succeed() } }
89ee8989f2982b935ca9c442e10330cf
30.772182
155
0.653936
false
false
false
false
developerY/Swift2_Playgrounds
refs/heads/master
Start-Dev-iOS-Apps/FoodTracker - Persist Data/FoodTracker/MealTableViewController.swift
mit
1
// // MealTableViewController.swift // FoodTracker // // Created by Jane Appleseed on 5/27/15. // Copyright © 2015 Apple Inc. All rights reserved. // See LICENSE.txt for this sample’s licensing information. // import UIKit class MealTableViewController: UITableViewController { // MARK: Properties var meals = [Meal]() override func viewDidLoad() { super.viewDidLoad() // Use the edit button item provided by the table view controller. navigationItem.leftBarButtonItem = editButtonItem() // Load any saved meals, otherwise load sample data. if let savedMeals = loadMeals() { meals += savedMeals } else { // Load the sample data. loadSampleMeals() } } func loadSampleMeals() { let photo1 = UIImage(named: "meal1")! let meal1 = Meal(name: "Caprese Salad", photo: photo1, rating: 4)! let photo2 = UIImage(named: "meal2")! let meal2 = Meal(name: "Chicken and Potatoes", photo: photo2, rating: 5)! let photo3 = UIImage(named: "meal3")! let meal3 = Meal(name: "Pasta with Meatballs", photo: photo3, rating: 3)! meals += [meal1, meal2, meal3] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return meals.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Table view cells are reused and should be dequeued using a cell identifier. let cellIdentifier = "MealTableViewCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! MealTableViewCell // Fetches the appropriate meal for the data source layout. let meal = meals[indexPath.row] cell.nameLabel.text = meal.name cell.photoImageView.image = meal.photo cell.ratingControl.rating = meal.rating return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source meals.removeAtIndex(indexPath.row) saveMeals() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowDetail" { let mealDetailViewController = segue.destinationViewController as! MealViewController // Get the cell that generated this segue. if let selectedMealCell = sender as? MealTableViewCell { let indexPath = tableView.indexPathForCell(selectedMealCell)! let selectedMeal = meals[indexPath.row] mealDetailViewController.meal = selectedMeal } } else if segue.identifier == "AddItem" { print("Adding new meal.") } } @IBAction func unwindToMealList(sender: UIStoryboardSegue) { if let sourceViewController = sender.sourceViewController as? MealViewController, meal = sourceViewController.meal { if let selectedIndexPath = tableView.indexPathForSelectedRow { // Update an existing meal. meals[selectedIndexPath.row] = meal tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None) } else { // Add a new meal. let newIndexPath = NSIndexPath(forRow: meals.count, inSection: 0) meals.append(meal) tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom) } // Save the meals. saveMeals() } } // MARK: NSCoding func saveMeals() { let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(meals, toFile: Meal.ArchiveURL.path!) if !isSuccessfulSave { print("Failed to save meals...") } } func loadMeals() -> [Meal]? { return NSKeyedUnarchiver.unarchiveObjectWithFile(Meal.ArchiveURL.path!) as? [Meal] } }
a29fa7db466e8ae200874c637b10f69e
35.38125
157
0.637691
false
false
false
false
aestesis/Aether
refs/heads/master
Project/sources/Media/Camera.swift
apache-2.0
1
// // Camera.swift // Alib // // Created by renan jegouzo on 28/02/2017. // Copyright © 2017 aestesis. All rights reserved. // import Foundation import AVFoundation import Metal import MetalKit /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public class Camera : NodeUI { /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public let onNewFrame = Event<Void>() public private(set) var preview:Texture2D? { didSet { if let o = oldValue { o.detach() } } } /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// var textureCache: CVMetalTextureCache? var session: AVCaptureSession? /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public init(parent:NodeUI) { super.init(parent:parent) let result = CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, viewport!.gpu.device!, nil, &textureCache) if result != kCVReturnSuccess { Debug.error("CVMetalTextureCacheCreate() error: \(result)") } } /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// override public func detach() { super.detach() } /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// func metal(buffer:CVPixelBuffer) -> MTLTexture? { if let textureCache = self.textureCache { let width = CVPixelBufferGetWidth(buffer) let height = CVPixelBufferGetHeight(buffer) var imageTexture: CVMetalTexture? let result = CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, textureCache, buffer, nil, MTLPixelFormat.bgra8Unorm, width, height, 0, &imageTexture) if result == kCVReturnSuccess, let t = imageTexture { return CVMetalTextureGetTexture(t) } } return nil } /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public func start() { session = AVCaptureSession() session!.sessionPreset = AVCaptureSession.Preset.high let vdev = AVCaptureDevice.default(for:AVMediaType.video) if let vdev = vdev { do { let vinput = try AVCaptureDeviceInput(device: vdev) session!.addInput(vinput) let voutput = AVCaptureVideoDataOutput() voutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as AnyHashable as! String:kCVPixelFormatType_32BGRA] voutput.alwaysDiscardsLateVideoFrames = true let vdel = VideoDelegate() vdel.onFrame.alive(self) { sampleBuffer in if let imgbuf = CMSampleBufferGetImageBuffer(sampleBuffer), let mt = self.metal(buffer: imgbuf) { let w = CVPixelBufferGetWidth(imgbuf) let h = CVPixelBufferGetHeight(imgbuf) self.preview = Texture2D(parent:self,size:Size(w,h),texture:mt) self.onNewFrame.dispatch(()) } } voutput.setSampleBufferDelegate(vdel,queue:DispatchQueue.main) session!.addOutput(voutput) session!.startRunning() } catch { Debug.error("Camera.start(), error!") } } } /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public func stop() { if let session = self.session { session.stopRunning() // TODO: self.session = nil } } /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class VideoDelegate : NSObject,AVCaptureVideoDataOutputSampleBufferDelegate { let onFrame = Event<CMSampleBuffer>() public func captureOutput(_ captureOutput: AVCaptureOutput, didDrop sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { onFrame.dispatch(sampleBuffer) } } /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
75c59fb914b82bb7fc5b45c21af0ada5
55.559633
174
0.329765
false
false
false
false
jovito-royeca/ManaKit
refs/heads/master
Sources/Classes/ManaKit+TcgPlayer.swift
mit
1
// // ManaKit+TcgPlayer.swift // Pods // // Created by Vito Royeca on 11/27/19. // import Foundation import PromiseKit extension ManaKit { public func authenticateTcgPlayer() -> Promise<Void> { return Promise { seal in guard let _ = tcgPlayerPartnerKey, let tcgPlayerPublicKey = tcgPlayerPublicKey, let tcgPlayerPrivateKey = tcgPlayerPrivateKey else { let error = NSError(domain: "Error", code: 401, userInfo: [NSLocalizedDescriptionKey: "No TCGPlayer keys found."]) seal.reject(error) return } let dateFormat = DateFormatter() var willAuthenticate = true dateFormat.dateStyle = .medium if let _ = keychain[UserDefaultsKeys.TcgPlayerToken], let expiration = keychain[UserDefaultsKeys.TcgPlayerExpiration], let expirationDate = dateFormat.date(from: expiration) { if Date() <= expirationDate { willAuthenticate = false } } if willAuthenticate { guard let urlString = "https://api.tcgplayer.com/token".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: urlString) else { fatalError("Malformed url") } let query = "grant_type=client_credentials&client_id=\(tcgPlayerPublicKey)&client_secret=\(tcgPlayerPrivateKey)" var rq = URLRequest(url: url) rq.httpMethod = "POST" rq.setValue("application/json", forHTTPHeaderField: "Content-Type") rq.httpBody = query.data(using: .utf8) firstly { URLSession.shared.dataTask(.promise, with: rq) }.compactMap { try JSONSerialization.jsonObject(with: $0.data) as? [String: Any] }.done { json in guard let token = json["access_token"] as? String, let expiresIn = json["expires_in"] as? Double else { let error = NSError(domain: "Error", code: 401, userInfo: [NSLocalizedDescriptionKey: "No TCGPlayer token found."]) seal.reject(error) return } let date = Date().addingTimeInterval(expiresIn) self.keychain[UserDefaultsKeys.TcgPlayerToken] = token self.keychain[UserDefaultsKeys.TcgPlayerExpiration] = dateFormat.string(from: date) seal.fulfill(()) }.catch { error in print("\(error)") seal.reject(error) } } else { seal.fulfill(()) } } } // public func getTcgPlayerPrices(forSet set: CMSet) -> Promise<Void> { // return Promise { seal in // guard let urlString = "https://api.tcgplayer.com/\(Constants.TcgPlayerApiVersion)/pricing/group/\(set.tcgPlayerID)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), // let url = URL(string: urlString) else { // fatalError("Malformed url") // } // // guard let token = keychain[UserDefaultsKeys.TcgPlayerToken] else { // fatalError("No TCGPlayer token found.") // } // // var rq = URLRequest(url: url) // rq.httpMethod = "GET" // rq.setValue("application/json", forHTTPHeaderField: "Content-Type") // rq.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") // // firstly { // URLSession.shared.dataTask(.promise, with:rq) // }.compactMap { // try JSONSerialization.jsonObject(with: $0.data) as? [String: Any] // }.done { json in // guard let results = json["results"] as? [[String: Any]] else { // fatalError("results is nil") // } // // try! self.realm.write { // // delete first // for card in set.cards { // for pricing in card.pricings { // self.realm.delete(pricing) // } // self.realm.add(card) // } // // for dict in results { // if let productId = dict["productId"] as? Int, // let card = self.realm.objects(CMCard.self).filter("tcgPlayerID = %@", productId).first { // // let pricing = CMCardPricing() // pricing.card = card // if let d = dict["lowPrice"] as? Double { // pricing.lowPrice = d // } // if let d = dict["midPrice"] as? Double { // pricing.midPrice = d // } // if let d = dict["highPrice"] as? Double { // pricing.highPrice = d // } // if let d = dict["marketPrice"] as? Double { // pricing.marketPrice = d // } // if let d = dict["directLowPrice"] as? Double { // pricing.directLowPrice = d // } // if let d = dict["subTypeName"] as? String { // if d == "Normal" { // pricing.isFoil = false // } else if d == "Foil" { // pricing.isFoil = true // } // } // self.realm.add(pricing) // // card.pricings.append(pricing) // card.tcgPlayerID = Int32(productId) // card.tcgPlayerLstUpdate = Date() // self.realm.add(card) // } // } // seal.fulfill(()) // } // }.catch { error in // print("\(error)") // seal.reject(error) // } // } // } // // public func getTcgPlayerPrices(forCards cards: [CMCard]) -> Promise<Void> { // return Promise { seal in // let productIds = cards.map({ $0.tcgPlayerID }).map(String.init).joined(separator: ",") // guard let urlString = "https://api.tcgplayer.com/\(Constants.TcgPlayerApiVersion)/pricing/product/\(productIds)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), // let url = URL(string: urlString) else { // fatalError("Malformed url") // } // // guard let token = keychain[UserDefaultsKeys.TcgPlayerToken] else { // fatalError("No TCGPlayer token found.") // } // // var rq = URLRequest(url: url) // rq.httpMethod = "GET" // rq.setValue("application/json", forHTTPHeaderField: "Content-Type") // rq.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") // // firstly { // URLSession.shared.dataTask(.promise, with:rq) // }.compactMap { // try JSONSerialization.jsonObject(with: $0.data) as? [String: Any] // }.done { json in // guard let results = json["results"] as? [[String: Any]] else { // fatalError("results is nil") // } // // try! self.realm.write { // // delete first // for card in cards { // for pricing in card.pricings { // self.realm.delete(pricing) // } // self.realm.add(card) // } // // for dict in results { // if let productId = dict["productId"] as? Int, // let card = cards.filter({ it -> Bool in // it.tcgPlayerID == productId // }).first { // // let pricing = CMCardPricing() // pricing.card = card // if let d = dict["lowPrice"] as? Double { // pricing.lowPrice = d // } // if let d = dict["midPrice"] as? Double { // pricing.midPrice = d // } // if let d = dict["highPrice"] as? Double { // pricing.highPrice = d // } // if let d = dict["marketPrice"] as? Double { // pricing.marketPrice = d // } // if let d = dict["directLowPrice"] as? Double { // pricing.directLowPrice = d // } // if let d = dict["subTypeName"] as? String { // if d == "Normal" { // pricing.isFoil = false // } else if d == "Foil" { // pricing.isFoil = true // } // } // self.realm.add(pricing) // // card.pricings.append(pricing) // card.tcgPlayerID = Int32(productId) // card.tcgPlayerLstUpdate = Date() // self.realm.add(card) // } // } // seal.fulfill(()) // } // }.catch { error in // print("\(error)") // seal.reject(error) // } // } // } // // public func fetchTCGPlayerCardPricing(card: CMCard) -> Promise<Void> { // return Promise { seal in // if card.willUpdateTCGPlayerCardPricing() { // guard let tcgPlayerPartnerKey = tcgPlayerPartnerKey, // let set = card.set, // let tcgPlayerSetName = set.tcgplayerName, // let cardName = card.name, // let urlString = "http:partner.tcgplayer.com/x3/phl.asmx/p?pk=\(tcgPlayerPartnerKey)&s=\("tcgPlayerSetName")&p=\(cardName)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), // let url = URL(string: urlString) else { // // seal.fulfill(()) // return // } // // var rq = URLRequest(url: url) // rq.httpMethod = "GET" // // firstly { // URLSession.shared.dataTask(.promise, with: rq) // }.map { // try! XML(xml: $0.data, encoding: .utf8) // }.done { xml in // let pricing = card.pricing != nil ? card.pricing : CMCardPricing() // // try! self.realm.write { // for product in xml.xpath("product") { // if let id = product.xpath("id").first?.text, // let hiprice = product.xpath("hiprice").first?.text, // let lowprice = product.xpath("lowprice").first?.text, // let avgprice = product.xpath("avgprice").first?.text, // let foilavgprice = product.xpath("foilavgprice").first?.text, // let link = product.xpath("link").first?.text { // pricing!.id = Int64(id)! // pricing!.high = Double(hiprice)! // pricing!.low = Double(lowprice)! // pricing!.average = Double(avgprice)! // pricing!.foil = Double(foilavgprice)! // pricing!.link = link // } // } // pricing!.lastUpdate = Date() // card.pricing = pricing // // self.realm.add(pricing!) // self.realm.add(card, update: true) // seal.fulfill(()) // } // }.catch { error in // seal.reject(error) // } // } else { // seal.fulfill(()) // } // } // } // // public func fetchTCGPlayerStorePricing(card: CMCard) -> Promise<Void> { // return Promise { seal in // if card.willUpdateTCGPlayerStorePricing() { // guard let tcgPlayerPartnerKey = tcgPlayerPartnerKey, //// let set = card.set, //// let tcgPlayerSetName = set.tcgplayerName, // let cardName = card.name, // let urlString = "http://partner.tcgplayer.com/x3/pv.asmx/p?pk=\(tcgPlayerPartnerKey)&s=\("tcgPlayerSetName")&p=\(cardName)&v=8".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), // let url = URL(string: urlString) else { // // seal.fulfill(()) // return // } // // var rq = URLRequest(url: url) // rq.httpMethod = "GET" // // firstly { // URLSession.shared.dataTask(.promise, with: rq) // }.map { // try! XML(xml: $0.data, encoding: .utf8) // }.done { xml in // try! self.realm.write { // var storePricing: CMStorePricing? // // // cleanup existing storePricing, if there is any // if let sp = card.tcgplayerStorePricing { // for sup in sp.suppliers { // self.realm.delete(sup) // } // self.realm.delete(sp) // storePricing = sp // } else { // storePricing = CMStorePricing() // } // // for supplier in xml.xpath("//supplier") { // if let name = supplier.xpath("name").first?.text, // let condition = supplier.xpath("condition").first?.text, // let qty = supplier.xpath("qty").first?.text, // let price = supplier.xpath("price").first?.text, // let link = supplier.xpath("link").first?.text { // // let id = "\(name)_\(condition)_\(qty)_\(price)" // var sup: CMStoreSupplier? // // if let s = self.realm.objects(CMStoreSupplier.self).filter("id = %@", id).first { // sup = s // } else { // sup = CMStoreSupplier() // } // sup!.id = id // sup!.name = name // sup!.condition = condition // sup!.qty = Int32(qty)! // sup!.price = Double(price)! // sup!.link = link // self.realm.add(sup!) // storePricing!.suppliers.append(sup!) // } // } // if let note = xml.xpath("//note").first?.text { // storePricing!.notes = note // } // storePricing!.lastUpdate = Date() // self.realm.add(storePricing!) // // seal.fulfill(()) // } // // }.catch { error in // seal.reject(error) // } // } else { // seal.fulfill(()) // } // } // } }
77b7ac4ac991c6801476ecc9131b79eb
44.924119
213
0.406999
false
false
false
false
wesj/firefox-ios-1
refs/heads/master
Providers/FileThumbnails.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Storage private let ThumbnailsDirName = "thumbnails" /** * Disk-backed implementation of the Thumbnails protocol. */ public class FileThumbnails: Thumbnails { private let files: FileAccessor private let thumbnailsDir: String required public init(files: FileAccessor) { self.files = files thumbnailsDir = files.getAndEnsureDirectory(relativeDir: ThumbnailsDirName)! } public func clear(complete: ((success: Bool) -> Void)?) { let success = files.removeFilesInDirectory(relativePath: ThumbnailsDirName) dispatch_async(dispatch_get_main_queue()) { complete?(success: success) return } } public func get(url: NSURL, complete: (thumbnail: Thumbnail?) -> Void) { var thumbnail: Thumbnail? = nil if let filename = getFilename(url) { let thumbnailPath = thumbnailsDir.stringByAppendingPathComponent(filename) if let data = NSData(contentsOfFile: thumbnailPath) { if let image = UIImage(data: data) { thumbnail = Thumbnail(image: image) } } } dispatch_async(dispatch_get_main_queue()) { complete(thumbnail: thumbnail) return } } public func set(url: NSURL, thumbnail: Thumbnail, complete: ((success: Bool) -> Void)?) { var success = false if let filename = getFilename(url) { let thumbnailPath = thumbnailsDir.stringByAppendingPathComponent(filename) let data = UIImagePNGRepresentation(thumbnail.image) success = data.writeToFile(thumbnailPath, atomically: false) } dispatch_async(dispatch_get_main_queue()) { complete?(success: success) return } } /** * Returns a hex encoded String of the URL's SHA1 hash, * which is used as the thumbnail filename. */ private func getFilename(url: NSURL) -> String? { return url.absoluteString?.sha1.hexEncodedString } }
95b6cc87ab1a0dbd893d23bd8cd3b6f7
31.183099
93
0.629759
false
false
false
false
cdmx/MiniMancera
refs/heads/master
miniMancera/View/Basic/VGradient.swift
mit
2
import UIKit class VGradient:UIView { private static let kLocationStart:NSNumber = 0 private static let kLocationEnd:NSNumber = 1 class func diagonal(colorLeftBottom:UIColor, colorTopRight:UIColor) -> VGradient { let colors:[CGColor] = [ colorLeftBottom.cgColor, colorTopRight.cgColor] let locations:[NSNumber] = [ kLocationStart, kLocationEnd] let startPoint:CGPoint = CGPoint(x:0, y:1) let endPoint:CGPoint = CGPoint(x:1, y:0) let gradient:VGradient = VGradient( colors:colors, locations:locations, startPoint:startPoint, endPoint:endPoint) return gradient } class func horizontal(colorLeft:UIColor, colorRight:UIColor) -> VGradient { let colors:[CGColor] = [ colorLeft.cgColor, colorRight.cgColor] let locations:[NSNumber] = [ kLocationStart, kLocationEnd] let startPoint:CGPoint = CGPoint(x:0, y:0.5) let endPoint:CGPoint = CGPoint(x:1, y:0.5) let gradient:VGradient = VGradient( colors:colors, locations:locations, startPoint:startPoint, endPoint:endPoint) return gradient } private init( colors:[CGColor], locations:[NSNumber], startPoint:CGPoint, endPoint:CGPoint) { super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false isUserInteractionEnabled = false guard let gradientLayer:CAGradientLayer = self.layer as? CAGradientLayer else { return } gradientLayer.startPoint = startPoint gradientLayer.endPoint = endPoint gradientLayer.locations = locations gradientLayer.colors = colors } required init?(coder:NSCoder) { return nil } override open class var layerClass:AnyClass { get { return CAGradientLayer.self } } }
491d0ecb7d289ae5872dc96145492cd9
25
84
0.565871
false
false
false
false
linebounce/HLT-Challenge
refs/heads/master
HLTChallenge/FlickrConstants.swift
mit
1
// // FlickrConstants.swift // HLTChallenge // // Created by Key Hoffman on 10/4/16. // Copyright © 2016 Key Hoffman. All rights reserved. // import Foundation // MARK: - FlickrConstants struct FlickrConstants { // MARK: - API struct API { static let scheme = "https" static let host = "api.flickr.com" static let path = "/services/rest" } // MARK: - Parameters struct Parameters { // MARK: - Keys struct Keys { // MARK: General struct General { static let apiKey = "api_key" static let responseFormat = "format" static let noJSONCallback = "nojsoncallback" } // MARK: - MetadataCollection struct MetadataCollection { static let method = "method" static let picturesPerPage = "per_page" static let pageNumber = "page" static let text = "text" static let extras = "extras" static let safeSearch = "safe_search" } // MARK: CommentCollection struct CommentCollection { static let method = "method" static let photoID = "photo_id" } } // MARK: - Values struct Values { // MARK: General struct General { static let apiKey = "c9025518af10cb3bb1ec3fd80ea2fd52" static let responseFormat = "json" static let noJSONCallback = "1" } // MARK: MetadataCollection struct MetadataCollection { static let picturesPerPage = "10" static let extras = "url_m, owner_name" enum Method: String { case search = "flickr.photos.search" case getRecent = "flickr.photos.getRecent" } enum SafeSearch: String { case safe = "1", moderate = "2", restricted = "3" } } // MARK: CommentCollection struct CommentCollection { static let method = "flickr.photos.comments.getList" } } } // MARK: - Response struct Response { // MARK: - Keys struct Keys { // MARK: General struct General { static let status = "stat" } // MARK: - MetadataCollection struct MetadataCollection { static let photoDictionary = "photos" static let photoArray = "photo" } // MARK: Metadata struct Metadata { static let title = "title" static let id = "id" static let ownerID = "owner" static let url = "url_m" static let ownerName = "ownername" } // MARK: - CommentCollection struct CommentCollection { static let commentDictionary = "comments" static let commentArray = "comment" } // MARK: Comment struct Comment { static let id = "id" static let ownerName = "authorname" static let ownerID = "author" static let date = "datecreate" static let content = "_content" } } // MARK: - Values struct Values { // MARK: Status struct Status { static let error = "fail" static let success = "ok" } } } }
37869979fb2cf5800504b27fedfdd817
26.567742
78
0.411889
false
false
false
false
luizlopezm/ios-Luis-Trucking
refs/heads/master
Pods/Eureka/Source/Rows/TextAreaRow.swift
mit
1
// // AlertRow.swift // Eureka // // Created by Martin Barreto on 2/23/16. // Copyright © 2016 Xmartlabs. All rights reserved. // import Foundation protocol TextAreaConformance : FormatterConformance { var placeholder : String? { get set } } /** * Protocol for cells that contain a UITextView */ public protocol AreaCell { var textView: UITextView { get } } public class _TextAreaCell<T where T: Equatable, T: InputTypeInitiable> : Cell<T>, UITextViewDelegate, AreaCell { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public lazy var placeholderLabel : UILabel = { let v = UILabel() v.translatesAutoresizingMaskIntoConstraints = false v.numberOfLines = 0 v.textColor = UIColor(white: 0, alpha: 0.22) return v }() public lazy var textView : UITextView = { let v = UITextView() v.translatesAutoresizingMaskIntoConstraints = false return v }() private var dynamicConstraints = [NSLayoutConstraint]() public override func setup() { super.setup() height = { 110 } textView.keyboardType = .Default textView.delegate = self textView.font = .preferredFontForTextStyle(UIFontTextStyleBody) textView.textContainer.lineFragmentPadding = 0 textView.textContainerInset = UIEdgeInsetsZero placeholderLabel.font = textView.font selectionStyle = .None contentView.addSubview(textView) contentView.addSubview(placeholderLabel) imageView?.addObserver(self, forKeyPath: "image", options: NSKeyValueObservingOptions.Old.union(.New), context: nil) let views : [String: AnyObject] = ["textView": textView, "label": placeholderLabel] contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[label]", options: [], metrics: nil, views: views)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[textView]-|", options: [], metrics: nil, views: views)) } deinit { textView.delegate = nil imageView?.removeObserver(self, forKeyPath: "image") } public override func update() { super.update() textLabel?.text = nil detailTextLabel?.text = nil textView.editable = !row.isDisabled textView.textColor = row.isDisabled ? .grayColor() : .blackColor() textView.text = row.displayValueFor?(row.value) placeholderLabel.text = (row as? TextAreaConformance)?.placeholder placeholderLabel.sizeToFit() placeholderLabel.hidden = textView.text.characters.count != 0 } public override func cellCanBecomeFirstResponder() -> Bool { return !row.isDisabled && textView.canBecomeFirstResponder() } public override func cellBecomeFirstResponder(fromDiretion: Direction) -> Bool { return textView.becomeFirstResponder() } public override func cellResignFirstResponder() -> Bool { return textView.resignFirstResponder() } public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if let obj = object, let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKindKey] where obj === imageView && keyPathValue == "image" && changeType.unsignedLongValue == NSKeyValueChange.Setting.rawValue { setNeedsUpdateConstraints() updateConstraintsIfNeeded() } } //Mark: Helpers private func displayValue(useFormatter useFormatter: Bool) -> String? { guard let v = row.value else { return nil } if let formatter = (row as? FormatterConformance)?.formatter where useFormatter { return textView.isFirstResponder() ? formatter.editingStringForObjectValue(v as! AnyObject) : formatter.stringForObjectValue(v as! AnyObject) } return String(v) } //MARK: TextFieldDelegate public func textViewDidBeginEditing(textView: UITextView) { formViewController()?.beginEditing(self) formViewController()?.textInputDidBeginEditing(textView, cell: self) if let textAreaConformance = (row as? TextAreaConformance), let _ = textAreaConformance.formatter where textAreaConformance.useFormatterOnDidBeginEditing ?? textAreaConformance.useFormatterDuringInput { textView.text = self.displayValue(useFormatter: true) } else { textView.text = self.displayValue(useFormatter: false) } } public func textViewDidEndEditing(textView: UITextView) { formViewController()?.endEditing(self) formViewController()?.textInputDidEndEditing(textView, cell: self) textViewDidChange(textView) textView.text = displayValue(useFormatter: (row as? FormatterConformance)?.formatter != nil) } public func textViewDidChange(textView: UITextView) { placeholderLabel.hidden = textView.text.characters.count != 0 guard let textValue = textView.text else { row.value = nil return } if let fieldRow = row as? FieldRowConformance, let formatter = fieldRow.formatter { if fieldRow.useFormatterDuringInput { let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.alloc(1)) let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?> = nil if formatter.getObjectValue(value, forString: textValue, errorDescription: errorDesc) { row.value = value.memory as? T if var selStartPos = textView.selectedTextRange?.start { let oldVal = textView.text textView.text = row.displayValueFor?(row.value) if let f = formatter as? FormatterProtocol { selStartPos = f.getNewPosition(forPosition: selStartPos, inTextInput: textView, oldValue: oldVal, newValue: textView.text) } textView.selectedTextRange = textView.textRangeFromPosition(selStartPos, toPosition: selStartPos) } return } } else { let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.alloc(1)) let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?> = nil if formatter.getObjectValue(value, forString: textValue, errorDescription: errorDesc) { row.value = value.memory as? T } return } } guard !textValue.isEmpty else { row.value = nil return } guard let newValue = T.init(string: textValue) else { return } row.value = newValue } public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { return formViewController()?.textInput(textView, shouldChangeCharactersInRange: range, replacementString: text, cell: self) ?? true } public func textViewShouldBeginEditing(textView: UITextView) -> Bool { return formViewController()?.textInputShouldBeginEditing(textView, cell: self) ?? true } public func textViewShouldEndEditing(textView: UITextView) -> Bool { return formViewController()?.textInputShouldEndEditing(textView, cell: self) ?? true } public override func updateConstraints(){ contentView.removeConstraints(dynamicConstraints) dynamicConstraints = [] var views : [String: AnyObject] = ["textView": textView, "label": placeholderLabel] if let imageView = imageView, let _ = imageView.image { views["imageView"] = imageView dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:[imageView]-[textView]-|", options: [], metrics: nil, views: views) dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:[imageView]-[label]-|", options: [], metrics: nil, views: views) } else{ contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[textView]-|", options: [], metrics: nil, views: views)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-|", options: [], metrics: nil, views: views)) } contentView.addConstraints(dynamicConstraints) super.updateConstraints() } } public class TextAreaCell : _TextAreaCell<String>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } } public class AreaRow<T: Equatable, Cell: CellType where Cell: BaseCell, Cell: TypedCellType, Cell: AreaCell, Cell.Value == T>: Row<T, Cell>, TextAreaConformance { public var placeholder : String? public var formatter: NSFormatter? public var useFormatterDuringInput = false public var useFormatterOnDidBeginEditing: Bool? public required init(tag: String?) { super.init(tag: tag) self.displayValueFor = { [unowned self] value in guard let v = value else { return nil } if let formatter = self.formatter { if self.cell.textView.isFirstResponder(){ return self.useFormatterDuringInput ? formatter.editingStringForObjectValue(v as! AnyObject) : String(v) } return formatter.stringForObjectValue(v as! AnyObject) } return String(v) } } } public class _TextAreaRow: AreaRow<String, TextAreaCell> { required public init(tag: String?) { super.init(tag: tag) } } /// A row with a UITextView where the user can enter large text. public final class TextAreaRow: _TextAreaRow, RowType { required public init(tag: String?) { super.init(tag: tag) } }
729bfb5715a5d5fece2acb34f8975a23
40.915323
228
0.654738
false
false
false
false
raulriera/Bike-Compass
refs/heads/master
App/Carthage/Checkouts/Alamofire/Source/Response.swift
mit
2
// // Response.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Used to store all response data returned from a completed `Request`. public struct Response<Value, Error: ErrorProtocol> { /// The URL request sent to the server. public let request: Foundation.URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The result of response serialization. public let result: Result<Value, Error> /// The timeline of the complete lifecycle of the `Request`. public let timeline: Timeline /** Initializes the `Response` instance with the specified URL request, URL response, server data and response serialization result. - parameter request: The URL request sent to the server. - parameter response: The server's response to the URL request. - parameter data: The data returned by the server. - parameter result: The result of response serialization. - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. - returns: the new `Response` instance. */ public init( request: Foundation.URLRequest?, response: HTTPURLResponse?, data: Data?, result: Result<Value, Error>, timeline: Timeline = Timeline()) { self.request = request self.response = response self.data = data self.result = result self.timeline = timeline } } // MARK: - CustomStringConvertible extension Response: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } } // MARK: - CustomDebugStringConvertible extension Response: 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("[Data]: \(data?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "\n") } }
7d76867c7cc3195491fd6c8f408bd703
38.515464
119
0.690843
false
false
false
false
Mrwerdo/QuickShare
refs/heads/master
LibQuickShare/Sources/Core/Packet.swift
mit
1
// // Packet.swift // QuickShare // // Copyright (c) 2016 Andrew Thompson // // 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 Support public typealias PIDType = UInt64 public struct Packet { public var fileID: FIDType /// Read as 'Packet Identifier' public var packetID: PIDType public var data: [UInt8] public init(fileID: FIDType, packetID: PIDType, data: [UInt8]) { self.fileID = fileID self.packetID = packetID self.data = data } } // Packet should be packed as follows: // // File ID : UInt32 // Packet ID : UInt64 // Length : UInt16 // Data : [UInt8] // extension Packet : Encodable { public var length: UInt16 { return 14 + UInt16(data.count) } public static var minimumLength: UInt16 { return 15 // Can't have no data } public func fill(inout buff: [UInt8], offset: Int) { buff[offset +< 0...3] = fileID.bytes[0...3] buff[offset +< 4...11] = packetID.bytes[0...7] buff[offset +< 12...13] = length.bytes[0...1] buff[offset +< 14..<(14 + data.count)] = data[0..<(data.count)] } } extension Packet : Decodable { public init?(buff: [UInt8]) { guard buff.count > 14 else { return nil } self.fileID = UInt32(bytes: buff[0...3]) self.packetID = UInt64(bytes: buff[4...11]) let length = Int(UInt16(bytes: buff[12...13])) guard length == buff.count else { return nil } self.data = buff[14..<(length)].map { $0 } } } public struct PacketStatus { public enum State : UInt8 { case Missing = 1 case Corrupt = 2 case Good = 3 } public var fileID: FIDType public var packetID: PIDType public var state: State public var percentageComplete: UInt16 public init(fileID: FIDType, packetID: PIDType, state: State, percentageComplete: UInt16) { self.fileID = fileID self.packetID = packetID self.state = state self.percentageComplete = percentageComplete } } // Packet Status should be packed as follows: // // File ID : UInt32 // Packet ID : UInt64 // State : UInt8 // Percentage Complete : UInt16 // extension PacketStatus : Encodable { public var length: UInt16 { return 15 } public static var minimumLength: UInt16 { return 15 } public func fill(inout buff: [UInt8], offset: Int) { buff[offset +< 0...3] = fileID.bytes[0...3] buff[offset +< 4...11] = packetID.bytes[0...7] buff[offset + 12] = state.rawValue buff[offset +< 13...14] = percentageComplete.bytes[0...1] } } extension PacketStatus : Decodable { public init?(buff: [UInt8]) { guard buff.count == 15 else { return nil } self.fileID = UInt32(bytes: buff[0...3]) self.packetID = UInt64(bytes: buff[4...11]) guard let state = State(rawValue: buff[12]) else { return nil } self.state = state self.percentageComplete = UInt16(bytes: buff[13...14]) } }
8d1f2ecb15a9cdc5a26a8bfde9467210
28.20979
95
0.624372
false
false
false
false
blue42u/swift-t
refs/heads/master
turbine/code/export/python.swift
apache-2.0
1
/* * Copyright 2013 University of Chicago and Argonne National Laboratory * * 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 */ /** To use Python compiled packages, you may have to modify Tcl to use dlopen(..., RTLD_NOW | RTLD_GLOBAL) Cf. http://stackoverflow.com/questions/8302810/undefined-symbol-in-c-when-loading-a-python-shared-library */ @dispatch=WORKER (string output) python(string code, string expr="\"\"", boolean exceptions_are_errors=true) "turbine" "0.1.0" [ "set <<output>> [ turbine::python 0 <<exceptions_are_errors>> <<code>> <<expr>> ]" ]; @dispatch=WORKER (string output) python_persist(string code, string expr="\"\"", boolean exceptions_are_errors=true) "turbine" "0.1.0" [ "set <<output>> [ turbine::python 1 <<exceptions_are_errors>> <<code>> <<expr>> ]" ];
a75f0ac8e042201d8bbc0b63116d80f8
40.121212
108
0.685335
false
false
false
false
Pradeepkn/Mysore_App
refs/heads/master
MysoreApp/AppDelegate/AppDelegate.swift
mit
1
// // AppDelegate.swift // MysoreApp // // Created by Pradeep on 6/26/17. // Copyright © 2017 Pradeep. All rights reserved. // import UIKit import CoreData import SlideMenuControllerSwift let kLoginFlowEnabled = false let kEncryptionEnabled = false let kSyncEnabled = false let kSyncGatewayUrl = URL(string: "http://localhost:4984/todo/")! let kLoggingEnabled = false let kUsePrebuiltDb = false let kConflictResolution = false @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var database: CBLDatabase! var pusher: CBLReplication! var puller: CBLReplication! var syncError: NSError? var conflictsLiveQuery: CBLLiveQuery? var accessDocuments: Array<CBLDocument> = []; func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { if kLoggingEnabled { enableLogging() } if kLoginFlowEnabled { login() } else { do { try startSession(username: "mysoreapp") } catch let error as NSError { NSLog("Cannot start a session: %@", error) return false } } self.createMenuView() return true } fileprivate func createMenuView() { // create viewController code... let storyboard = UIStoryboard(name: "Main", bundle: nil) let mainViewController = storyboard.instantiateViewController(withIdentifier: MyBaseViewController.self.className) as! MyBaseViewController let leftViewController = storyboard.instantiateViewController(withIdentifier: MyMenuViewController.self.className) as! MyMenuViewController let nvc: UINavigationController = UINavigationController(rootViewController: mainViewController) UINavigationBar.appearance().tintColor = UIColor.blue leftViewController.mainViewController = nvc let slideMenuController = SlideMenuController(mainViewController:nvc, leftMenuViewController: leftViewController, rightMenuViewController: UIViewController()) slideMenuController.automaticallyAdjustsScrollViewInsets = true slideMenuController.delegate = mainViewController slideMenuController.changeLeftViewWidth((self.window?.frame.size.width)! - 60) self.window?.backgroundColor = mainViewController.view.backgroundColor self.window?.rootViewController = slideMenuController self.window?.makeKeyAndVisible() UIApplication.shared.statusBarStyle = .lightContent } // MARK: - Logging func enableLogging() { CBLManager.enableLogging("CBLDatabase") CBLManager.enableLogging("View") CBLManager.enableLogging("ViewVerbose") CBLManager.enableLogging("Query") CBLManager.enableLogging("Sync") CBLManager.enableLogging("SyncVerbose") } // MARK: - Session func startSession(username:String, withPassword password:String? = nil, withNewPassword newPassword:String? = nil) throws { // installPrebuiltDb() try openDatabase(username: username, withKey: password, withNewKey: newPassword) Session.username = username startReplication(withUsername: username, andPassword: newPassword ?? password) showApp() startConflictLiveQuery() } func installPrebuiltDb() { // TRAINING: Install pre-built database guard kUsePrebuiltDb else { return } let db = CBLManager.sharedInstance().databaseExistsNamed("mysoreapp") if (!db) { let dbPath = Bundle.main.path(forResource: "mysoreapp", ofType: "cblite2") do { try CBLManager.sharedInstance().replaceDatabaseNamed("mysoreapp", withDatabaseDir: dbPath!) } catch let error as NSError { NSLog("Cannot replace the database %@", error) } } } func openDatabase(username:String, withKey key:String?, withNewKey newKey:String?) throws { // TRAINING: Create a database let dbname = username let options = CBLDatabaseOptions() options.create = true if kEncryptionEnabled { if let encryptionKey = key { options.encryptionKey = encryptionKey } } try database = CBLManager.sharedInstance().openDatabaseNamed(dbname, with: options) if newKey != nil { try database.changeEncryptionKey(newKey) } NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.observeDatabaseChange), name:Notification.Name.cblDatabaseChange, object: database) } func observeDatabaseChange(notification: Notification) { if(!(notification.userInfo?["external"] as! Bool)) { return; } for change in notification.userInfo?["changes"] as! Array<CBLDatabaseChange> { if(!change.isCurrentRevision) { continue; } let changedDoc = database.existingDocument(withID: change.documentID); if(changedDoc == nil) { return; } let docType = changedDoc?.properties?["type"] as! String?; if(docType == nil) { continue; } if(docType != "menu-list.user") { continue; } let username = changedDoc?.properties?["username"] as! String?; if(username != database.name) { continue; } accessDocuments.append(changedDoc!); NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.handleAccessChange), name: NSNotification.Name.cblDocumentChange, object: changedDoc); } } func handleAccessChange(notification: Notification) throws { let change = notification.userInfo?["change"] as! CBLDatabaseChange; let changedDoc = database.document(withID: change.documentID); if(changedDoc == nil || !(changedDoc?.isDeleted)!) { return; } let deletedRev = try changedDoc?.getLeafRevisions()[0]; let listId = (deletedRev?["menuList"] as! Dictionary<String, NSObject>)["id"] as! String?; if(listId == nil) { return; } accessDocuments.remove(at: accessDocuments.index(of: changedDoc!)!); let listDoc = database.existingDocument(withID: listId!); try listDoc?.purgeDocument(); try changedDoc?.purgeDocument() } func closeDatabase() throws { stopConflictLiveQuery() try database.close() } // MARK: - Login func login(username: String? = nil) { let storyboard = window!.rootViewController!.storyboard let navigation = storyboard!.instantiateViewController( withIdentifier: "MyLoginViewController") as! UINavigationController let loginController = navigation.topViewController as! MyLoginViewController // loginController.delegate = self // loginController.username = username window!.rootViewController = navigation } func logout() { stopReplication() do { try closeDatabase() } catch let error as NSError { NSLog("Cannot close database: %@", error) } let oldUsername = Session.username Session.username = nil login(username: oldUsername) } func showApp() { guard let root = window?.rootViewController, let storyboard = root.storyboard else { return } let controller = storyboard.instantiateInitialViewController() window!.rootViewController = controller } // MARK: - LoginViewControllerDelegate func login(controller: UIViewController, withUsername username: String, andPassword password: String) { processLogin(controller: controller, withUsername: username, withPassword: password) } func processLogin(controller: UIViewController, withUsername username: String, withPassword password: String, withNewPassword newPassword: String? = nil) { do { try startSession(username: username, withPassword: password, withNewPassword: newPassword) } catch let error as NSError { if error.code == 401 { handleEncryptionError(controller: controller, withUsername: username, withPassword: password) } else { Ui.showMessageDialog( onController: controller, withTitle: "Error", withMessage: "Login has an error occurred, code = \(error.code).") NSLog("Cannot start a session: %@", error) } } } func handleEncryptionError(controller: UIViewController, withUsername username: String, withPassword password: String) { Ui.showEncryptionErrorDialog( onController: controller, onMigrateAction: { oldPassword in self.processLogin(controller: controller, withUsername: username, withPassword: oldPassword, withNewPassword: password) }, onDeleteAction: { // Delete database: self.deleteDatabase(dbName: username) // login: self.processLogin(controller: controller, withUsername: username, withPassword: password) } ) } func deleteDatabase(dbName: String) { // Delete the database by using file manager. Currently CBL doesn't have // an API to delete an encrypted database so we remove the database // file manually as a workaround. let dir = NSURL(fileURLWithPath: CBLManager.sharedInstance().directory) let dbFile = dir.appendingPathComponent("\(dbName).cblite2") do { try FileManager.default.removeItem(at: dbFile!) } catch let err as NSError { NSLog("Error when deleting the database file: %@", err) } } // MARK: - Replication func startReplication(withUsername username:String, andPassword password:String? = "") { guard kSyncEnabled else { return } syncError = nil // TRAINING: Start push/pull replications pusher = database.createPushReplication(kSyncGatewayUrl) pusher.continuous = true // Runs forever in background NotificationCenter.default.addObserver(self, selector: #selector(replicationProgress(notification:)), name: NSNotification.Name.cblReplicationChange, object: pusher) puller = database.createPullReplication(kSyncGatewayUrl) puller.continuous = true // Runs forever in background NotificationCenter.default.addObserver(self, selector: #selector(replicationProgress(notification:)), name: NSNotification.Name.cblReplicationChange, object: puller) if kLoginFlowEnabled { let authenticator = CBLAuthenticator.basicAuthenticator(withName: username, password: password!) pusher.authenticator = authenticator puller.authenticator = authenticator } pusher.start() puller.start() } func stopReplication() { guard kSyncEnabled else { return } pusher.stop() NotificationCenter.default.removeObserver( self, name: NSNotification.Name.cblReplicationChange, object: pusher) puller.stop() NotificationCenter.default.removeObserver( self, name: NSNotification.Name.cblReplicationChange, object: puller) } func replicationProgress(notification: NSNotification) { UIApplication.shared.isNetworkActivityIndicatorVisible = (pusher.status == .active || puller.status == .active) let error = pusher.lastError as NSError?; if (error != syncError) { syncError = error if let errorCode = error?.code { NSLog("Replication Error: \(error!)") if errorCode == 401 { Ui.showMessageDialog( onController: self.window!.rootViewController!, withTitle: "Authentication Error", withMessage:"Your username or password is not correct.", withError: nil, onClose: { self.logout() }) } } } } // MARK: - Conflicts Resolution // TRAINING: Responding to Live Query changes override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if object as? NSObject == conflictsLiveQuery { resolveConflicts() } } func startConflictLiveQuery() { guard kConflictResolution else { return } // TRAINING: Detecting when conflicts occur conflictsLiveQuery = database.createAllDocumentsQuery().asLive() conflictsLiveQuery!.allDocsMode = .onlyConflicts conflictsLiveQuery!.addObserver(self, forKeyPath: "rows", options: .new, context: nil) conflictsLiveQuery!.start() } func stopConflictLiveQuery() { conflictsLiveQuery?.removeObserver(self, forKeyPath: "rows") conflictsLiveQuery?.stop() conflictsLiveQuery = nil } func resolveConflicts() { let rows = conflictsLiveQuery?.rows while let row = rows?.nextRow() { if let revs = row.conflictingRevisions, revs.count > 1 { let defaultWinning = revs[0] let type = (defaultWinning["type"] as? String) ?? "" switch type { // TRAINING: Automatic conflict resolution case "menu-list", "menu-list.user": let props = defaultWinning.userProperties let image = defaultWinning.attachmentNamed("image") resolveConflicts(revisions: revs, withProps: props, andImage: image) // TRAINING: N-way merge conflict resolution case "menu": let merged = nWayMergeConflicts(revs: revs) resolveConflicts(revisions: revs, withProps: merged.props, andImage: merged.image) default: break } } } } func resolveConflicts(revisions revs: [CBLRevision], withProps desiredProps: [String: Any]?, andImage desiredImage: CBLAttachment?) { database.inTransaction { var i = 0 for rev in revs as! [CBLSavedRevision] { let newRev = rev.createRevision() // Create new revision if (i == 0) { // That's the current / winning revision newRev.userProperties = desiredProps // Set properties to desired properties if rev.attachmentNamed("image") != desiredImage { newRev.setAttachmentNamed("image", withContentType: "image/jpg", content: desiredImage?.content) } } else { // That's a conflicting revision, delete it newRev.isDeletion = true } do { try newRev.saveAllowingConflict() // Persist the new revisions } catch let error as NSError { NSLog("Cannot resolve conflicts with error: %@", error) return false } i += 1 } return true } } func nWayMergeConflicts(revs: [CBLRevision]) -> (props: [String: Any]?, image: CBLAttachment?) { guard let parent = findCommonParent(revisions: revs) else { let defaultWinning = revs[0] let props = defaultWinning.userProperties let image = defaultWinning.attachmentNamed("image") return (props, image) } var mergedProps = parent.userProperties ?? [:] var mergedImage = parent.attachmentNamed("image") var gotTask = false, gotComplete = false, gotImage = false for rev in revs { if let props = rev.userProperties { if !gotTask { let task = props["menu"] as? String if task != mergedProps["menu"] as? String { mergedProps["menu"] = task gotTask = true } } if !gotComplete { let complete = props["complete"] as? Bool if complete != mergedProps["complete"] as? Bool { mergedProps["complete"] = complete gotComplete = true } } } if !gotImage { let attachment = rev.attachmentNamed("image") let attachmentDiggest = attachment?.metadata["digest"] as? String if (attachmentDiggest != mergedImage?.metadata["digest"] as? String) { mergedImage = attachment gotImage = true } } if gotTask && gotComplete && gotImage { break } } return (mergedProps, mergedImage) } func findCommonParent(revisions: [CBLRevision]) -> CBLRevision? { var minHistoryCount = 0 var histories : [[CBLRevision]] = [] for rev in revisions { let history = (try? rev.getHistory()) ?? [] histories.append(history) minHistoryCount = minHistoryCount > 0 ? min(minHistoryCount, history.count) : history.count } if minHistoryCount == 0 { return nil } var commonParent : CBLRevision? = nil for i in 0...minHistoryCount { var rev: CBLRevision? = nil for history in histories { if rev == nil { rev = history[i] } else if rev!.revisionID != history[i].revisionID { rev = nil break } } if rev == nil { break } commonParent = rev } if let deleted = commonParent?.isDeletion , deleted { commonParent = nil } return commonParent } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded 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. */ let container = NSPersistentContainer(name: "mysoreapp") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() 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. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
c8a1b81b62e710ae24a2245db5bdf683
39.524702
285
0.583782
false
false
false
false
mindbody/Conduit
refs/heads/main
Tests/ConduitTests/Networking/Serialization/FormEncodedRequestSerializerTests.swift
apache-2.0
1
// // FormEncodedRequestSerializerTests.swift // ConduitTests // // Created by John Hammerlund on 7/10/17. // Copyright © 2017 MINDBODY. All rights reserved. // import XCTest import Conduit class FormEncodedRequestSerializerTests: XCTestCase { private func makeRequest() throws -> URLRequest { let url = try URL(absoluteString: "https://httpbin.org") var request = URLRequest(url: url) request.httpMethod = "POST" return request } func testURIEncodesBodyParameters() throws { let request = try makeRequest() let serializer = FormEncodedRequestSerializer() let tests: [([String: String], [String])] = [ (["foo": "bar"], ["foo=bar"]), (["foo": "bar", "bing": "bang"], ["foo=bar", "bing=bang"]) ] for test in tests { let serializedRequest = try serializer.serialize(request: request, bodyParameters: test.0) guard let body = serializedRequest.httpBody else { XCTFail("Expected body") return } let resultBodyString = String(data: body, encoding: .utf8) for expectation in test.1 { XCTAssert(resultBodyString?.contains(expectation) == true) } } } func testDoesntReplaceCustomDefinedHeaders() throws { var request = try makeRequest() let serializer = FormEncodedRequestSerializer() let customDefaultHeaderFields = [ "Accept-Language": "FlyingSpaghettiMonster", "User-Agent": "Chromebook. Remember those?", "Content-Type": "application/its-not-xml-but-it-kind-of-is-aka-soap" ] request.allHTTPHeaderFields = customDefaultHeaderFields guard let modifiedRequest = try? serializer.serialize(request: request, bodyParameters: nil) else { XCTFail("Serialization failed") return } for customHeader in customDefaultHeaderFields { XCTAssert(modifiedRequest.value(forHTTPHeaderField: customHeader.0) == customHeader.1) } } func testEncodesPlusSymbolsByDefault() throws { let request = try makeRequest() let serializer = FormEncodedRequestSerializer() let parameters = [ "foo": "bar+baz" ] let serializedRequest = try? serializer.serialize(request: request, bodyParameters: parameters) guard let body = serializedRequest?.httpBody else { XCTFail("Expected body") return } let resultBodyString = String(data: body, encoding: .utf8) XCTAssert(resultBodyString == "foo=bar%2Bbaz") } }
b5bd939581e5984853c3332bcc2e1764
32.222222
107
0.616871
false
true
false
false
kevinvanderlugt/Exercism-Solutions
refs/heads/master
swift/meetup/Meetup.swift
mit
1
// // MeetUp.swift // exercism-test-runner // // Created by Kevin VanderLugt on 3/20/15. // Copyright (c) 2015 Alpine Pipeline, LLC. All rights reserved. // import Foundation struct Meetup { var month: Int var year: Int let calendar = NSCalendar.currentCalendar() private let invalidDate = NSDate.distantFuture() as NSDate init(year: Int, month: Int) { self.year = year self.month = month } func day(day: Int, which: String) -> NSDate { let components = NSDateComponents() components.weekday = day var dateOptions = NSCalendarOptions.MatchNextTime var weeks = 0, dayOffset = 0, monthOffset = 0 switch which { case "1st": weeks = 0 case "2nd": weeks = 1 case "3rd": weeks = 2 case "4th": weeks = 3 case "teenth": dayOffset = 12 case "last": dayOffset = 1 monthOffset = 1 dateOptions = dateOptions | NSCalendarOptions.SearchBackwards default: return invalidDate } var returnDate = invalidDate if let startingDate = startDate(dayOffset: dayOffset, monthOffset: monthOffset) { var dateCount = 0 calendar.enumerateDatesStartingAfterDate(startingDate, matchingComponents: components, options: dateOptions) { (date: NSDate!, exactMatch: Bool, stop: UnsafeMutablePointer<ObjCBool>) in if dateCount == weeks { stop.memory = true returnDate = date } dateCount++ } } return returnDate } func startDate(dayOffset: Int = 0, monthOffset: Int = 0) -> NSDate? { return calendar.dateWithEra(1, year: year, month: month + monthOffset, day: 0 + dayOffset, hour: 0, minute: 0, second: 0, nanosecond: 0) } }
136585d475d20a265d77ab69de41cf85
29.859375
120
0.559271
false
false
false
false
kumabook/MusicFav
refs/heads/master
MusicFav/UpdateChecker.swift
mit
1
// // UpdateChecker.swift // MusicFav // // Created by Hiroki Kumamoto on 5/11/15. // Copyright (c) 2015 Hiroki Kumamoto. All rights reserved. // import Foundation import ReactiveSwift import FeedlyKit import MusicFeeder class UpdateChecker { let apiClient = CloudAPIClient.shared let perPage = 3 let newerThan: Date init() { if let fromDate = CloudAPIClient.lastChecked { newerThan = fromDate } else { newerThan = Date().yesterDay } } var nextNotificationDate: Date? { if let components = CloudAPIClient.notificationDateComponents { return Date.nextDateFromComponents(components as DateComponents) } return nil } func check(_ application: UIApplication, completionHandler: ((UIBackgroundFetchResult) -> Void)?) { if let fireDate = nextNotificationDate { fetchNewTracks().on( failed: { error in UIScheduler().schedule { completionHandler?(UIBackgroundFetchResult.failed) } }, completed: { }, interrupted: { UIScheduler().schedule { completionHandler?(UIBackgroundFetchResult.failed) } }, value: { tracks in UIScheduler().schedule { let tracksInfo = UILocalNotification.buildNewTracksInfo(application, tracks: tracks) application.cancelAllLocalNotifications() if tracksInfo.count > 0 { let notification = UILocalNotification.newTracksNotification(tracksInfo, fireDate: fireDate) application.scheduleLocalNotification(notification) completionHandler?(UIBackgroundFetchResult.newData) } else { completionHandler?(UIBackgroundFetchResult.noData) } } CloudAPIClient.lastChecked = Date() }).start() } else { application.cancelAllLocalNotifications() completionHandler?(UIBackgroundFetchResult.noData) } } func fetchNewTracks() -> SignalProducer<[Track], NSError> { var entriesSignal: SignalProducer<[Entry], NSError>! if let profile = CloudAPIClient.profile { entriesSignal = apiClient.fetchEntries(streamId: FeedlyKit.Category.all(profile.id).streamId, newerThan: newerThan.timestamp, unreadOnly: true, perPage: perPage) .map { $0.items } } else { entriesSignal = SubscriptionRepository().loadLocalSubscriptions() .map { (table: [FeedlyKit.Category: [FeedlyKit.Stream]]) -> [FeedlyKit.Stream] in return table.values.flatMap { $0 } }.map { streams in return streams.map { stream in return self.apiClient.fetchEntries(streamId: stream.streamId, newerThan: self.newerThan.timestamp, unreadOnly: true, perPage: self.perPage).map { $0.items } }.reduce(SignalProducer<[Entry], NSError>(value: [])) { SignalProducer.combineLatest($0, $1).map { var list = $0.0; list.append(contentsOf: $0.1); return list } } }.flatten(FlattenStrategy.concat) } return entriesSignal.map { entries in entries.reduce(SignalProducer<[Track], NSError>(value: [])) { SignalProducer.combineLatest($0, self.fetchPlaylistOfEntry($1)).map { var list = $0.0; list.append(contentsOf: $0.1.tracks); return list } } }.flatten(.concat) } func fetchPlaylistOfEntry(_ entry: Entry) -> SignalProducer<PlaylistifiedEntry, NSError> { if let url = entry.url { return PinkSpiderAPIClient.shared.playlistify(url, errorOnFailure: false) } else { return SignalProducer<PlaylistifiedEntry, NSError>.empty } } }
94dbf18341bba4006faebd4ce61c3031
43.272727
116
0.542779
false
false
false
false
OpenTimeApp/OpenTimeIOSSDK
refs/heads/master
OpenTimeSDK/Classes/OTDeserializedMeetingAttendee.swift
mit
1
// // OTDeserializedMeetingAttendee.swift // OpenTimeSDK // // Created by Josh Woodcock on 12/26/15. // Copyright © 2015 Connecting Open Time, LLC. All rights reserved. // public class OTDeserializedMeetingAttendee : OTDeserializer { private struct Keys { static let USER_ID = "user_id"; static let STATUS = "status"; static let LAST_UPDATED = "last_updated"; } private var _userID: OpenTimeUserID; private var _status: MeetingAttendeeStatus; private var _lastUpdated: OpenTimeTimeStamp; public required init(dictionary: NSDictionary){ self._userID = dictionary.value(forKey: Keys.USER_ID) as! OpenTimeUserID; self._status = dictionary.value(forKey: Keys.STATUS) as! MeetingAttendeeStatus; self._lastUpdated = dictionary.value(forKey: Keys.LAST_UPDATED) as! OpenTimeTimeStamp; } public func getUserID() -> OpenTimeUserID { return self._userID; } public func getStatus() -> MeetingAttendeeStatus { return self._status; } public func getLastUpdated() -> OpenTimeTimeStamp { return self._lastUpdated; } }
7227b427edec856577fc0654cd75460a
29.333333
94
0.652578
false
false
false
false
mownier/photostream
refs/heads/master
Photostream/Modules/Post Discovery/Module/PostDiscoveryModule.swift
mit
1
// // PostDiscoveryModule.swift // Photostream // // Created by Mounir Ybanez on 20/12/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // protocol PostDiscoveryModuleInterface: BaseModuleInterface { var postCount: Int { get } func viewDidLoad() func initialLoad() func refreshPosts() func loadMorePosts() func unlikePost(at index: Int) func likePost(at index: Int) func toggleLike(at index: Int) func post(at index: Int) -> PostDiscoveryData? func initialPostWillShow() } protocol PostDiscoveryBuilder: BaseModuleBuilder { func build(root: RootWireframe?, posts: [PostDiscoveryData], initialPostIndex: Int) } class PostDiscoveryModule: BaseModule, BaseModuleInteractable { typealias ModuleView = PostDiscoveryScene typealias ModuleInteractor = PostDiscoveryInteractor typealias ModulePresenter = PostDiscoveryPresenter typealias ModuleWireframe = PostDiscoveryWireframe var view: ModuleView! var interactor: ModuleInteractor! var presenter: ModulePresenter! var wireframe: ModuleWireframe! required init(view: ModuleView) { self.view = view } } extension PostDiscoveryModule: PostDiscoveryBuilder { func build(root: RootWireframe?) { let auth = AuthSession() let service = PostServiceProvider(session: auth) interactor = PostDiscoveryInteractor(service: service) presenter = PostDiscoveryPresenter() wireframe = PostDiscoveryWireframe(root: root) interactor.output = presenter view.presenter = presenter presenter.interactor = interactor presenter.view = view presenter.wireframe = wireframe } func build(root: RootWireframe?, posts: [PostDiscoveryData], initialPostIndex: Int) { build(root: root) presenter.posts = posts presenter.initialPostIndex = initialPostIndex } }
e8f2e2fb5aa05f2465240bca03b479c4
26.555556
89
0.6875
false
false
false
false
amosavian/swift-corelibs-foundation
refs/heads/master
Foundation/NSDictionary.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation import Dispatch open class NSDictionary : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding { private let _cfinfo = _CFInfo(typeID: CFDictionaryGetTypeID()) internal var _storage: [NSObject: AnyObject] open var count: Int { guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else { NSRequiresConcreteImplementation() } return _storage.count } open func object(forKey aKey: Any) -> Any? { guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else { NSRequiresConcreteImplementation() } if let val = _storage[_SwiftValue.store(aKey)] { return _SwiftValue.fetch(nonOptional: val) } return nil } open func value(forKey key: String) -> Any? { NSUnsupported() } open func keyEnumerator() -> NSEnumerator { guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else { NSRequiresConcreteImplementation() } return NSGeneratorEnumerator(_storage.keys.map { _SwiftValue.fetch(nonOptional: $0) }.makeIterator()) } public override convenience init() { self.init(objects: [], forKeys: [], count: 0) } public required init(objects: UnsafePointer<AnyObject>!, forKeys keys: UnsafePointer<NSObject>!, count cnt: Int) { _storage = [NSObject : AnyObject](minimumCapacity: cnt) for idx in 0..<cnt { let key = keys[idx].copy() let value = objects[idx] _storage[key as! NSObject] = value } } public required convenience init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.objects") { let keys = aDecoder._decodeArrayOfObjectsForKey("NS.keys").map() { return $0 as! NSObject } let objects = aDecoder._decodeArrayOfObjectsForKey("NS.objects") self.init(objects: objects as! [NSObject], forKeys: keys) } else { var objects = [AnyObject]() var keys = [NSObject]() var count = 0 while let key = aDecoder.decodeObject(forKey: "NS.key.\(count)"), let object = aDecoder.decodeObject(forKey: "NS.object.\(count)") { keys.append(key as! NSObject) objects.append(object as! NSObject) count += 1 } self.init(objects: objects, forKeys: keys) } } open func encode(with aCoder: NSCoder) { if let keyedArchiver = aCoder as? NSKeyedArchiver { keyedArchiver._encodeArrayOfObjects(self.allKeys._nsObject, forKey:"NS.keys") keyedArchiver._encodeArrayOfObjects(self.allValues._nsObject, forKey:"NS.objects") } else { NSUnimplemented() } } public static var supportsSecureCoding: Bool { return true } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { if type(of: self) === NSDictionary.self { // return self for immutable type return self } else if type(of: self) === NSMutableDictionary.self { let dictionary = NSDictionary() dictionary._storage = self._storage return dictionary } return NSDictionary(objects: self.allValues, forKeys: self.allKeys.map({ $0 as! NSObject})) } open override func mutableCopy() -> Any { return mutableCopy(with: nil) } open func mutableCopy(with zone: NSZone? = nil) -> Any { if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self { // always create and return an NSMutableDictionary let mutableDictionary = NSMutableDictionary() mutableDictionary._storage = self._storage return mutableDictionary } return NSMutableDictionary(objects: self.allValues, forKeys: self.allKeys.map { _SwiftValue.store($0) } ) } public convenience init(object: Any, forKey key: NSCopying) { self.init(objects: [object], forKeys: [key as! NSObject]) } public convenience init(objects: [Any], forKeys keys: [NSObject]) { let keyBuffer = UnsafeMutablePointer<NSObject>.allocate(capacity: keys.count) keyBuffer.initialize(from: keys, count: keys.count) let valueBuffer = UnsafeMutablePointer<AnyObject>.allocate(capacity: objects.count) valueBuffer.initialize(from: objects.map { _SwiftValue.store($0) }, count: objects.count) self.init(objects: valueBuffer, forKeys:keyBuffer, count: keys.count) keyBuffer.deinitialize(count: keys.count) valueBuffer.deinitialize(count: objects.count) keyBuffer.deallocate(capacity: keys.count) valueBuffer.deallocate(capacity: objects.count) } public convenience init(dictionary otherDictionary: [AnyHashable : Any]) { self.init(objects: Array(otherDictionary.values), forKeys: otherDictionary.keys.map { _SwiftValue.store($0) }) } open override func isEqual(_ value: Any?) -> Bool { switch value { case let other as Dictionary<AnyHashable, Any>: return isEqual(to: other) case let other as NSDictionary: return isEqual(to: Dictionary._unconditionallyBridgeFromObjectiveC(other)) default: return false } } open override var hash: Int { return self.count } open var allKeys: [Any] { if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self { return Array(_storage.keys) } else { var keys = [Any]() let enumerator = keyEnumerator() while let key = enumerator.nextObject() { keys.append(key) } return keys } } open var allValues: [Any] { if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self { return Array(_storage.values) } else { var values = [Any]() let enumerator = keyEnumerator() while let key = enumerator.nextObject() { values.append(object(forKey: key)!) } return values } } /// Alternative pseudo funnel method for fastpath fetches from dictionaries /// - Experiment: This is a draft API currently under consideration for official import into Foundation /// - Note: Since this API is under consideration it may be either removed or revised in the near future open func getObjects(_ objects: inout [Any], andKeys keys: inout [Any], count: Int) { if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self { for (key, value) in _storage { keys.append(_SwiftValue.fetch(nonOptional: key)) objects.append(_SwiftValue.fetch(nonOptional: value)) } } else { let enumerator = keyEnumerator() while let key = enumerator.nextObject() { let value = object(forKey: key)! keys.append(key) objects.append(value) } } } open subscript (key: Any) -> Any? { return object(forKey: key) } open func allKeys(for anObject: Any) -> [Any] { var matching = Array<Any>() enumerateKeysAndObjects(options: []) { key, value, _ in if let val = value as? AnyHashable, let obj = anObject as? AnyHashable { if val == obj { matching.append(key) } } } return matching } /// A string that represents the contents of the dictionary, formatted as /// a property list (read-only) /// /// If each key in the dictionary is an NSString object, the entries are /// listed in ascending order by key, otherwise the order in which the entries /// are listed is undefined. This property is intended to produce readable /// output for debugging purposes, not for serializing data. If you want to /// store dictionary data for later retrieval, see /// [Property List Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/Introduction/Introduction.html#//apple_ref/doc/uid/10000048i) /// and [Archives and Serializations Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Archiving/Archiving.html#//apple_ref/doc/uid/10000047i). open override var description: String { return description(withLocale: nil) } private func getDescription(of object: Any) -> String? { switch object { case is NSArray.Type: return (object as! NSArray).description(withLocale: nil, indent: 1) case is NSDecimalNumber.Type: return (object as! NSDecimalNumber).description(withLocale: nil) case is NSDate.Type: return (object as! NSDate).description(with: nil) case is NSOrderedSet.Type: return (object as! NSOrderedSet).description(withLocale: nil) case is NSSet.Type: return (object as! NSSet).description(withLocale: nil) case is NSDictionary.Type: return (object as! NSDictionary).description(withLocale: nil) default: if let hashableObject = object as? Dictionary<AnyHashable, Any> { return hashableObject._nsObject.description(withLocale: nil, indent: 1) } else { return nil } } } open var descriptionInStringsFileFormat: String { var lines = [String]() for key in self.allKeys { let line = NSMutableString(capacity: 0) line.append("\"") if let descriptionByType = getDescription(of: key) { line.append(descriptionByType) } else { line.append("\(key)") } line.append("\"") line.append(" = ") line.append("\"") let value = self.object(forKey: key)! if let descriptionByTypeValue = getDescription(of: value) { line.append(descriptionByTypeValue) } else { line.append("\(value)") } line.append("\"") line.append(";") lines.append(line._bridgeToSwift()) } return lines.joined(separator: "\n") } /// Returns a string object that represents the contents of the dictionary, /// formatted as a property list. /// /// - parameter locale: An object that specifies options used for formatting /// each of the dictionary’s keys and values; pass `nil` if you don’t /// want them formatted. open func description(withLocale locale: Locale?) -> String { return description(withLocale: locale, indent: 0) } /// Returns a string object that represents the contents of the dictionary, /// formatted as a property list. /// /// - parameter locale: An object that specifies options used for formatting /// each of the dictionary’s keys and values; pass `nil` if you don’t /// want them formatted. /// /// - parameter level: Specifies a level of indentation, to make the output /// more readable: the indentation is (4 spaces) * level. /// /// - returns: A string object that represents the contents of the dictionary, /// formatted as a property list. open func description(withLocale locale: Locale?, indent level: Int) -> String { if level > 100 { return "..." } var lines = [String]() let indentation = String(repeating: " ", count: level * 4) lines.append(indentation + "{") for key in self.allKeys { var line = String(repeating: " ", count: (level + 1) * 4) if key is NSArray { line += (key as! NSArray).description(withLocale: locale, indent: level + 1) } else if key is Date { line += (key as! NSDate).description(with: locale) } else if key is NSDecimalNumber { line += (key as! NSDecimalNumber).description(withLocale: locale) } else if key is NSDictionary { line += (key as! NSDictionary).description(withLocale: locale, indent: level + 1) } else if key is NSOrderedSet { line += (key as! NSOrderedSet).description(withLocale: locale, indent: level + 1) } else if key is NSSet { line += (key as! NSSet).description(withLocale: locale) } else { line += "\(key)" } line += " = " let object = self.object(forKey: key)! if object is NSArray { line += (object as! NSArray).description(withLocale: locale, indent: level + 1) } else if object is Date { line += (object as! NSDate).description(with: locale) } else if object is NSDecimalNumber { line += (object as! NSDecimalNumber).description(withLocale: locale) } else if object is NSDictionary { line += (object as! NSDictionary).description(withLocale: locale, indent: level + 1) } else if object is NSOrderedSet { line += (object as! NSOrderedSet).description(withLocale: locale, indent: level + 1) } else if object is NSSet { line += (object as! NSSet).description(withLocale: locale) } else { if let hashableObject = object as? Dictionary<AnyHashable, Any> { line += hashableObject._nsObject.description(withLocale: nil, indent: level+1) } else { line += "\(object)" } } line += ";" lines.append(line) } lines.append(indentation + "}") return lines.joined(separator: "\n") } open func isEqual(to otherDictionary: [AnyHashable : Any]) -> Bool { if count != otherDictionary.count { return false } for key in keyEnumerator() { if let otherValue = otherDictionary[key as! AnyHashable] as? AnyHashable, let value = object(forKey: key)! as? AnyHashable { if otherValue != value { return false } } else if let otherBridgeable = otherDictionary[key as! AnyHashable] as? _ObjectBridgeable, let bridgeable = object(forKey: key)! as? _ObjectBridgeable { if !(otherBridgeable._bridgeToAnyObject() as! NSObject).isEqual(bridgeable._bridgeToAnyObject()) { return false } } else { return false } } return true } public struct Iterator : IteratorProtocol { let dictionary : NSDictionary var keyGenerator : Array<Any>.Iterator public mutating func next() -> (key: Any, value: Any)? { if let key = keyGenerator.next() { return (key, dictionary.object(forKey: key)!) } else { return nil } } init(_ dict : NSDictionary) { self.dictionary = dict self.keyGenerator = dict.allKeys.makeIterator() } } internal struct ObjectGenerator: IteratorProtocol { let dictionary : NSDictionary var keyGenerator : Array<Any>.Iterator mutating func next() -> Any? { if let key = keyGenerator.next() { return dictionary.object(forKey: key)! } else { return nil } } init(_ dict : NSDictionary) { self.dictionary = dict self.keyGenerator = dict.allKeys.makeIterator() } } open func objectEnumerator() -> NSEnumerator { return NSGeneratorEnumerator(ObjectGenerator(self)) } open func objects(forKeys keys: [Any], notFoundMarker marker: Any) -> [Any] { var objects = [Any]() for key in keys { if let object = object(forKey: key) { objects.append(object) } else { objects.append(marker) } } return objects } open func write(toFile path: String, atomically useAuxiliaryFile: Bool) -> Bool { return write(to: URL(fileURLWithPath: path), atomically: useAuxiliaryFile) } // the atomically flag is ignored if url of a type that cannot be written atomically. open func write(to url: URL, atomically: Bool) -> Bool { do { let pListData = try PropertyListSerialization.data(fromPropertyList: self, format: PropertyListSerialization.PropertyListFormat.xml, options: 0) try pListData.write(to: url, options: atomically ? .atomic : []) return true } catch { return false } } open func enumerateKeysAndObjects(_ block: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { enumerateKeysAndObjects(options: [], using: block) } open func enumerateKeysAndObjects(options opts: NSEnumerationOptions = [], using block: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Void) { let count = self.count var keys = [Any]() var objects = [Any]() var sharedStop = ObjCBool(false) let lock = NSLock() getObjects(&objects, andKeys: &keys, count: count) let iteration: (Int) -> Void = withoutActuallyEscaping(block) { (closure: @escaping (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Void) -> (Int) -> Void in return { (idx) in lock.lock() var stop = sharedStop lock.unlock() if stop.boolValue { return } closure(keys[idx], objects[idx], &stop) if stop.boolValue { lock.lock() sharedStop = stop lock.unlock() return } } } if opts.contains(.concurrent) { DispatchQueue.concurrentPerform(iterations: count, execute: iteration) } else { for idx in 0..<count { iteration(idx) } } } open func keysSortedByValue(comparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] { return keysSortedByValue(options: [], usingComparator: cmptr) } open func keysSortedByValue(options opts: NSSortOptions = [], usingComparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] { let sorted = allKeys.sorted { lhs, rhs in return cmptr(lhs, rhs) == .orderedSame } return sorted } open func keysOfEntries(passingTest predicate: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> { return keysOfEntries(options: [], passingTest: predicate) } open func keysOfEntries(options opts: NSEnumerationOptions = [], passingTest predicate: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> { var matching = Set<AnyHashable>() enumerateKeysAndObjects(options: opts) { key, value, stop in if predicate(key, value, stop) { matching.insert(key as! AnyHashable) } } return matching } override open var _cfTypeID: CFTypeID { return CFDictionaryGetTypeID() } required public convenience init(dictionaryLiteral elements: (Any, Any)...) { var keys = [NSObject]() var values = [Any]() for (key, value) in elements { keys.append(_SwiftValue.store(key)) values.append(value) } self.init(objects: values, forKeys: keys) } } extension NSDictionary : _CFBridgeable, _SwiftBridgeable { internal var _cfObject: CFDictionary { return unsafeBitCast(self, to: CFDictionary.self) } internal var _swiftObject: Dictionary<AnyHashable, Any> { return Dictionary._unconditionallyBridgeFromObjectiveC(self) } } extension NSMutableDictionary { internal var _cfMutableObject: CFMutableDictionary { return unsafeBitCast(self, to: CFMutableDictionary.self) } } extension CFDictionary : _NSBridgeable, _SwiftBridgeable { internal var _nsObject: NSDictionary { return unsafeBitCast(self, to: NSDictionary.self) } internal var _swiftObject: [AnyHashable: Any] { return _nsObject._swiftObject } } extension Dictionary : _NSBridgeable, _CFBridgeable { internal var _nsObject: NSDictionary { return _bridgeToObjectiveC() } internal var _cfObject: CFDictionary { return _nsObject._cfObject } } open class NSMutableDictionary : NSDictionary { open func removeObject(forKey aKey: Any) { guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else { NSRequiresConcreteImplementation() } _storage.removeValue(forKey: _SwiftValue.store(aKey)) } /// - Note: this diverges from the darwin version that requires NSCopying (this differential preserves allowing strings and such to be used as keys) open func setObject(_ anObject: Any, forKey aKey: AnyHashable) { guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else { NSRequiresConcreteImplementation() } _storage[(aKey as! NSObject)] = _SwiftValue.store(anObject) } public convenience required init() { self.init(capacity: 0) } public convenience init(capacity numItems: Int) { self.init(objects: [], forKeys: [], count: 0) // It is safe to reset the storage here because we know is empty _storage = [NSObject: AnyObject](minimumCapacity: numItems) } public required init(objects: UnsafePointer<AnyObject>!, forKeys keys: UnsafePointer<NSObject>!, count cnt: Int) { super.init(objects: objects, forKeys: keys, count: cnt) } public convenience init?(contentsOfFile path: String) { self.init(contentsOfURL: URL(fileURLWithPath: path)) } public convenience init?(contentsOfURL url: URL) { do { guard let plistDoc = try? Data(contentsOf: url) else { return nil } let plistDict = try PropertyListSerialization.propertyList(from: plistDoc, options: [], format: nil) as? Dictionary<AnyHashable,Any> guard let plistDictionary = plistDict else { return nil } self.init(dictionary: plistDictionary) } catch { return nil } } } extension NSMutableDictionary { open func addEntries(from otherDictionary: [AnyHashable : Any]) { for (key, obj) in otherDictionary { setObject(obj, forKey: key) } } open func removeAllObjects() { if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self { _storage.removeAll() } else { for key in allKeys { removeObject(forKey: key) } } } open func removeObjects(forKeys keyArray: [Any]) { for key in keyArray { removeObject(forKey: key) } } open func setDictionary(_ otherDictionary: [AnyHashable : Any]) { removeAllObjects() for (key, obj) in otherDictionary { setObject(obj, forKey: key) } } /// - Note: See setObject(_:,forKey:) for details on the differential here public subscript (key: AnyHashable) -> Any? { get { return object(forKey: key) } set { if let val = newValue { setObject(val, forKey: key) } else { removeObject(forKey: key) } } } } extension NSDictionary : Sequence { public func makeIterator() -> Iterator { return Iterator(self) } } // MARK - Shared Key Sets extension NSDictionary { /* Use this method to create a key set to pass to +dictionaryWithSharedKeySet:. The keys are copied from the array and must be copyable. If the array parameter is nil or not an NSArray, an exception is thrown. If the array of keys is empty, an empty key set is returned. The array of keys may contain duplicates, which are ignored (it is undefined which object of each duplicate pair is used). As for any usage of hashing, is recommended that the keys have a well-distributed implementation of -hash, and the hash codes must satisfy the hash/isEqual: invariant. Keys with duplicate hash codes are allowed, but will cause lower performance and increase memory usage. */ open class func sharedKeySet(forKeys keys: [NSCopying]) -> Any { NSUnimplemented() } } extension NSMutableDictionary { /* Create a mutable dictionary which is optimized for dealing with a known set of keys. Keys that are not in the key set can still be set into the dictionary, but that usage is not optimal. As with any dictionary, the keys must be copyable. If keyset is nil, an exception is thrown. If keyset is not an object returned by +sharedKeySetForKeys:, an exception is thrown. */ public convenience init(sharedKeySet keyset: Any) { NSUnimplemented() } } extension NSDictionary : ExpressibleByDictionaryLiteral { } extension NSDictionary : CustomReflectable { public var customMirror: Mirror { NSUnimplemented() } } extension NSDictionary : _StructTypeBridgeable { public typealias _StructType = Dictionary<AnyHashable,Any> public func _bridgeToSwift() -> _StructType { return _StructType._unconditionallyBridgeFromObjectiveC(self) } }
aeee2c29bfb18177793f57c024efdb09
37.527221
188
0.597575
false
false
false
false
renyufei8023/WeiBo
refs/heads/master
weibo/Classes/Home/Controller/BaseTableViewController.swift
mit
1
// // BaseTableViewController.swift // weibo // // Created by 任玉飞 on 16/4/25. // Copyright © 2016年 任玉飞. All rights reserved. // import UIKit class BaseTableViewController: UITableViewController { var userLogin = false override func loadView() { userLogin ? super.loadView() : setupVisitorView() } private func setupVisitorView() { } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
d3dd7511bbb8690632ba57449e15142b
31.75
157
0.679096
false
false
false
false
ricardopereira/ColiseuPlayer
refs/heads/master
ColiseuPlayer/ColiseuPlayer.swift
mit
1
// // ColiseuPlayer.swift // Coliseu // // Copyright (c) 2014 Ricardo Pereira (http://ricardopereira.eu) // // 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 AVFoundation import MediaPlayer protocol AudioPlayerProtocol: AVAudioPlayerDelegate { func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) } /* A protocol for delegates of ColiseuPlayer */ @objc public protocol ColiseuPlayerDelegate: class { /* audioPlayer:didReceiveRemoteControlPlayEvent: is called when play button is clicked from remote control. */ optional func audioPlayer(controller: ColiseuPlayer, didReceiveRemoteControlPlayEvent eventSubtype: UIEventSubtype) /* audioPlayer:didReceiveRemoteControlPauseEvent: is called when pause button is clicked from remote control. */ optional func audioPlayer(controller: ColiseuPlayer, didReceiveRemoteControlPauseEvent eventSubtype: UIEventSubtype) /* audioPlayer:didReceiveRemoteControlPreviousTrackEvent: is called when rewind button is clicked from remote control. */ optional func audioPlayer(controller: ColiseuPlayer, didReceiveRemoteControlPreviousTrackEvent eventSubtype: UIEventSubtype) /* audioPlayer:didReceiveRemoteControlNextTrackEvent: is called when fast forward button is clicked from remote control. */ optional func audioPlayer(controller: ColiseuPlayer, didReceiveRemoteControlNextTrackEvent eventSubtype: UIEventSubtype) /* audioPlayer:didReceiveRemoteControlBeginSeekingBackwardEvent: is called when begin seeking backward from remote control. */ optional func audioPlayer(controller: ColiseuPlayer, didReceiveRemoteControlBeginSeekingBackwardEvent eventSubtype: UIEventSubtype) /* audioPlayer:didReceiveRemoteControlEndSeekingBackwardEvent: is called when seeking backward ended from remote control. */ optional func audioPlayer(controller: ColiseuPlayer, didReceiveRemoteControlEndSeekingBackwardEvent eventSubtype: UIEventSubtype) /* audioPlayer:didReceiveRemoteControlBeginSeekingForwardEvent: is called when begin seeking forward from remote control. */ optional func audioPlayer(controller: ColiseuPlayer, didReceiveRemoteControlBeginSeekingForwardEvent eventSubtype: UIEventSubtype) /* audioPlayer:didReceiveRemoteControlEndSeekingForwardEvent: is called when seeking forward ended from remote control. */ optional func audioPlayer(controller: ColiseuPlayer, didReceiveRemoteControlEndSeekingForwardEvent eventSubtype: UIEventSubtype) } /* A protocol for datasource of ColiseuPlayer */ @objc public protocol ColiseuPlayerDataSource: class { // Determine whether audio is not going to repeat, repeat once or always repeat. optional func audioRepeatTypeInAudioPlayer(controller: ColiseuPlayer) -> ColiseuPlayerRepeat.RawValue // Determine whether audio list is shuffled. optional func audioWillShuffleInAudioPlayer(controller: ColiseuPlayer) -> Bool } /* An enum for repeat type of ColiseuPlayer */ public enum ColiseuPlayerRepeat: Int { case None = 0, One, All } public class ColiseuPlayer: NSObject { public typealias function = () -> () internal var audioPlayer: AVAudioPlayer? internal var timer: NSTimer! // Playlist internal var currentSong: AudioFile? internal var songsList: [AudioFile]? // Events public var playerDidStart: function? public var playerDidStop: function? private var playerWillRepeat: Bool? // Delegate public weak var delegate: ColiseuPlayerDelegate? { willSet { if let viewController = newValue as? UIViewController { UIApplication.sharedApplication().beginReceivingRemoteControlEvents() viewController.becomeFirstResponder() } else { UIApplication.sharedApplication().endReceivingRemoteControlEvents() } } didSet { if let viewController = oldValue as? UIViewController { viewController.resignFirstResponder() } } } // DataSource public weak var dataSource: ColiseuPlayerDataSource? public override init() { // Inherited super.init() } public func startSession() { // Session do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) } catch let error as NSError { print("A AVAudioSession setCategory error occurred, here are the details:\n \(error)") } do { try AVAudioSession.sharedInstance().setActive(true) } catch let error as NSError { print("A AVAudioSession setActive error occurred, here are the details:\n \(error)") } } public func stopSession() { do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient) } catch let error as NSError { print("A AVAudioSession setCategory error occurred, here are the details:\n \(error)") } do { try AVAudioSession.sharedInstance().setActive(false) } catch let error as NSError { print("A AVAudioSession setActive error occurred, here are the details:\n \(error)") } } internal func remoteControlInfo(song: AudioFile) { var title: String = "Coliseu" if let bundleName = NSBundle.mainBundle().infoDictionary?["CFBundleName"] as? String { title = bundleName } // ? - Seeking test //let time = self.audioPlayer!.currentTime //self.audioPlayer!.currentTime = time + 30 //Seconds //slider.maximumValue = CMTimeGetSeconds([player duration]) //slider.value = CMTimeGetSeconds(player.currentTime) //player.currentTime = CMTimeMakeWithSeconds((int)slider.value,1) // Remote Control info - ? var songInfo = [MPMediaItemPropertyTitle: song.title, MPMediaItemPropertyArtist: title, //MPNowPlayingInfoPropertyElapsedPlaybackTime: time + 30, MPMediaItemPropertyPlaybackDuration: self.audioPlayer!.duration] as [String : AnyObject] if let artwork = song.artwork { songInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(image: artwork) } MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = songInfo } private func prepareAudio(index: Int) { guard let songs = self.songsList where (index >= 0 && index < songs.count) else { return } prepareAudio(songs[index], index) } private func prepareAudio(song: AudioFile, _ index: Int) { // Keep alive audio at background if let _ = song.path { self.currentSong = song song.index = index } else { self.currentSong = nil return } do { self.audioPlayer = try AVAudioPlayer(contentsOfURL: song.path!) } catch let error as NSError { print("A AVAudioPlayer contentsOfURL error occurred, here are the details:\n \(error)") } self.audioPlayer!.delegate = self self.audioPlayer!.prepareToPlay() remoteControlInfo(song) // ? song.duration = self.audioPlayer!.duration } private func songListIsValid() -> Bool { if self.songsList == nil || self.songsList!.count == 0 { return false } return true } // MARK: Commands public func playSong() { // Verify if has a valid playlist to play if !songListIsValid() { return } // Check the didStart event if let event = self.playerDidStart { event() } self.audioPlayer!.play() } public func playSong(index: Int, songsList: [AudioFile]) { self.songsList = songsList if let dataSource = self.dataSource where dataSource.audioWillShuffleInAudioPlayer?(self) == true { self.songsList?.shuffle() } // Prepare core audio prepareAudio(index) // Play current song playSong() } public func playSong(index: Int) { // Verify if has a valid playlist to play if !songListIsValid() { return } // Prepare core audio prepareAudio(index) // Play current song playSong() } public func pauseSong() { if self.audioPlayer!.playing { self.audioPlayer!.pause() } } public func stopSong() { if self.audioPlayer == nil || !self.audioPlayer!.playing { return } self.audioPlayer!.stop() if let event = self.playerDidStop { event() } if let current = self.currentSong { prepareAudio(current, current.index) } } public func playNextSong(stopIfInvalid stopIfInvalid: Bool = false) { if let songs = self.songsList, song = self.currentSong { var index = song.index // Next song index++ if index > songs.count - 1 { if stopIfInvalid { stopSong() } return } playSong(index) } } public func playPreviousSong() { if let _ = self.songsList, song = self.currentSong { var index = song.index // Previous song index-- if index < 0 { return } playSong(index) } } public func isLastSong() -> Bool { if let currentSong = self.currentSong, songsList = self.songsList where currentSong.index + 1 == songsList.count { return true } return false } public func isFirstSong() -> Bool { if let currentSong = self.currentSong where currentSong.index == 0 { return true } return false } // MARK: ColiseuPlayerDelegate public func remoteControlEvent(event: UIEvent) { if let delegate = self.delegate where event.type == UIEventType.RemoteControl { switch event.subtype { case UIEventSubtype.RemoteControlPlay: delegate.audioPlayer?(self, didReceiveRemoteControlPlayEvent: event.subtype) case UIEventSubtype.RemoteControlPause: delegate.audioPlayer?(self, didReceiveRemoteControlPauseEvent: event.subtype) case UIEventSubtype.RemoteControlPreviousTrack: delegate.audioPlayer?(self, didReceiveRemoteControlPreviousTrackEvent: event.subtype) case UIEventSubtype.RemoteControlNextTrack: delegate.audioPlayer?(self, didReceiveRemoteControlNextTrackEvent: event.subtype) case UIEventSubtype.RemoteControlBeginSeekingBackward: delegate.audioPlayer?(self, didReceiveRemoteControlBeginSeekingBackwardEvent: event.subtype) case UIEventSubtype.RemoteControlEndSeekingBackward: delegate.audioPlayer?(self, didReceiveRemoteControlEndSeekingBackwardEvent: event.subtype) case UIEventSubtype.RemoteControlBeginSeekingForward: delegate.audioPlayer?(self, didReceiveRemoteControlBeginSeekingForwardEvent: event.subtype) case UIEventSubtype.RemoteControlEndSeekingForward: delegate.audioPlayer?(self, didReceiveRemoteControlEndSeekingForwardEvent: event.subtype) default: break } } } } // MARK: AudioPlayerProtocol extension ColiseuPlayer: AudioPlayerProtocol { public func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) { if !flag { return } playNextSong(stopIfInvalid: true) if let repeatType = self.dataSource?.audioRepeatTypeInAudioPlayer?(self) where self.audioPlayer?.playing == false { switch repeatType { case ColiseuPlayerRepeat.None.rawValue: self.playerWillRepeat = false case ColiseuPlayerRepeat.One.rawValue: switch self.playerWillRepeat { case true?: self.playerWillRepeat = false default: self.playerWillRepeat = true playSong(0) } case ColiseuPlayerRepeat.All.rawValue: self.playerWillRepeat = true playSong(0) default: break } } } } // MARK: shuffle Array private extension Array { mutating func shuffle() { if count < 2 { return } for i in 0..<(count - 1) { let j = Int(arc4random_uniform(UInt32(count - i))) + i guard i != j else { continue } swap(&self[i], &self[j]) } } }
1d2f505d2dccd97dfe0d81e485647aab
33.490148
135
0.650218
false
false
false
false
ThumbWorks/i-meditated
refs/heads/master
Pods/RxSwift/RxSwift/Observables/Implementations/Throttle.swift
mit
1
// // Throttle.swift // Rx // // Created by Krunoslav Zaher on 3/22/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class ThrottleSink<O: ObserverType> : Sink<O> , ObserverType , LockOwnerType , SynchronizedOnType { typealias Element = O.E typealias ParentType = Throttle<Element> private let _parent: ParentType let _lock = NSRecursiveLock() // state private var _id = 0 as UInt64 private var _value: Element? = nil let cancellable = SerialDisposable() init(parent: ParentType, observer: O) { _parent = parent super.init(observer: observer) } func run() -> Disposable { let subscription = _parent._source.subscribe(self) return Disposables.create(subscription, cancellable) } func on(_ event: Event<Element>) { synchronizedOn(event) } func _synchronized_on(_ event: Event<Element>) { switch event { case .next(let element): _id = _id &+ 1 let currentId = _id _value = element let scheduler = _parent._scheduler let dueTime = _parent._dueTime let d = SingleAssignmentDisposable() self.cancellable.disposable = d d.disposable = scheduler.scheduleRelative(currentId, dueTime: dueTime, action: self.propagate) case .error: _value = nil forwardOn(event) dispose() case .completed: if let value = _value { _value = nil forwardOn(.next(value)) } forwardOn(.completed) dispose() } } func propagate(_ currentId: UInt64) -> Disposable { _lock.lock(); defer { _lock.unlock() } // { let originalValue = _value if let value = originalValue, _id == currentId { _value = nil forwardOn(.next(value)) } // } return Disposables.create() } } class Throttle<Element> : Producer<Element> { fileprivate let _source: Observable<Element> fileprivate let _dueTime: RxTimeInterval fileprivate let _scheduler: SchedulerType init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) { _source = source _dueTime = dueTime _scheduler = scheduler } override func run<O: ObserverType>(_ observer: O) -> Disposable where O.E == Element { let sink = ThrottleSink(parent: self, observer: observer) sink.disposable = sink.run() return sink } }
2a67100e81755733c05b56c42733e317
25.125
106
0.563121
false
false
false
false
johnlinvc/swiftpy
refs/heads/develop
src/Swiftpy/swiftpy.swift
mit
1
import Python public func initPython(){ Py_Initialize() } public func evalStatement(_ string: String) { PyRun_SimpleStringFlags(string, nil); } public func call(_ code: String, args:CPyObjConvertible...) -> PythonObject { let main = pythonImport(name: "__main__") return main.call(code, args: args) } func wrapEvalString( string : String) -> String { return "def _swiftpy_eval_wrapper_():\n" + " result = \(string)\n" + " return result" } //TODO handle def case public func eval(_ code:String) -> PythonObject { let wrappedCode = wrapEvalString(string:code) evalStatement(wrappedCode) let main = pythonImport(name: "__main__") return main.call("_swiftpy_eval_wrapper_") } public typealias CPyObj = UnsafeMutablePointer<PyObject> public protocol CPyObjConvertible : CustomStringConvertible { var cPyObjPtr:CPyObj? { get } var description:String { get } //TODO test the case of method with self @discardableResult func call(_ funcName:String, args:CPyObjConvertible...) -> PythonObject @discardableResult func call(_ funcName:String, args:[CPyObjConvertible]) -> PythonObject func toPythonString() -> PythonString func attr(_ name:String) -> PythonObject func setAttr(_ name:String, value:CPyObjConvertible) } extension CPyObjConvertible { @discardableResult public func call(_ funcName:String, args:CPyObjConvertible...) -> PythonObject{ return call(funcName, args:args) } @discardableResult public func call(_ funcName:String, args:[CPyObjConvertible]) -> PythonObject { let pFunc = PyObject_GetAttrString(cPyObjPtr!, funcName) guard PyCallable_Check(pFunc) == 1 else { return PythonObject() } let pArgs = PyTuple_New(args.count) for (idx,obj) in args.enumerated() { let i:Int = idx PyTuple_SetItem(pArgs, i, obj.cPyObjPtr!) } let pValue = PyObject_CallObject(pFunc, pArgs) Py_DecRef(pArgs) return PythonObject(ptr: pValue) } public func toPythonString() -> PythonString { let ptr = PyObject_Str(cPyObjPtr!) return PythonString(obj:PythonObject(ptr:ptr)) } public func attr(_ name:String) -> PythonObject { guard PyObject_HasAttrString(cPyObjPtr!, name) == 1 else {return PythonObject()} return PythonObject(ptr:PyObject_GetAttrString(cPyObjPtr!, name)) } public func setAttr(_ name:String, value:CPyObjConvertible) { PyObject_SetAttrString(cPyObjPtr!, name, value.cPyObjPtr!) } public var description: String { let pyString = toPythonString() let cstr:UnsafePointer<CChar> = UnsafePointer(PyString_AsString(pyString.cPyObjPtr!)!) return String(cString : cstr) } } public class PythonInt : CPyObjConvertible, IntegerLiteralConvertible { public let obj:PythonObject public typealias IntegerLiteralType = Int public required init(integerLiteral value: IntegerLiteralType){ obj = PythonObject(ptr:PyInt_FromLong(value)) } public var cPyObjPtr:CPyObj? { return obj.ptr } } public class PythonString : CPyObjConvertible, StringLiteralConvertible{ public let obj:PythonObject public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType public typealias UnicodeScalarLiteralType = StringLiteralType public required init(stringLiteral:String) { obj = PythonObject(ptr: PyString_FromString(stringLiteral)) } public required init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { obj = PythonObject(ptr: PyString_FromString(value)) } public required init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { obj = PythonObject(ptr: PyString_FromString("\(value)")) } init(obj:PythonObject){ self.obj = obj } public var cPyObjPtr:CPyObj? { return obj.ptr } } public func pythonImport(name:String) -> PythonObject{ let module = PyImport_ImportModule(name) return PythonObject(ptr:module) } //TODO public func convertCPyObj(cPyObj ptr:CPyObj) -> CPyObjConvertible { //NOT impl yet return PythonObject(ptr:ptr) } public class PythonObject : CustomDebugStringConvertible, CPyObjConvertible { let ptr:CPyObj? public init() { ptr = nil } init(ptr:CPyObj?) { self.ptr = ptr } public var cPyObjPtr:CPyObj? { return ptr } public var debugDescription: String { get { guard let pptr = ptr else { return "nil" } return pptr.debugDescription } } }
e7f5f134bfdcee9ba4de592cfdf672b5
34.310345
106
0.617188
false
false
false
false
a2/Gulliver
refs/heads/master
Gulliver Tests/Source/InstantMessageAddressSpec.swift
mit
1
import AddressBook import Gulliver import Nimble import Quick class InstantMessageAddressSpec: QuickSpec { override func spec() { describe("multiValueRepresentation") { it("should contain the correct data") { let address = InstantMessageAddress(service: InstantMessageAddress.Services.Facebook, username: "johnny.b.goode") let mvr = address.multiValueRepresentation as! [NSObject : AnyObject] expect((mvr[kABPersonInstantMessageServiceKey as String] as! String)) == kABPersonInstantMessageServiceFacebook as String expect((mvr[kABPersonInstantMessageUsernameKey as String] as! String)) == "johnny.b.goode" } it("is a valid representation") { let address = InstantMessageAddress(service: InstantMessageAddress.Services.Facebook, username: "johnny.b.goode") let multiValue: ABMutableMultiValueRef = ABMultiValueCreateMutable(numericCast(kABDictionaryPropertyType)).takeRetainedValue() if !ABMultiValueAddValueAndLabel(multiValue, address.multiValueRepresentation, "facebook", nil) { fail("Could not add address to multi value") } let record: ABRecordRef = ABPersonCreate().takeRetainedValue() var error: Unmanaged<CFErrorRef>? = nil if !ABRecordSetValue(record, kABPersonInstantMessageProperty, multiValue, &error) { let nsError = (error?.takeUnretainedValue()).map { unsafeBitCast($0, NSError.self) } fail("Could not set value on record: \(nsError?.localizedDescription)") } } } describe("init(multiValueRepresentation:)") { it("creates a valid InstantMessageAddress") { let representation: [NSObject : AnyObject] = [ kABPersonInstantMessageServiceKey as String: kABPersonInstantMessageServiceFacebook as String, kABPersonInstantMessageUsernameKey as String: "johnny.b.goode", ] let address = InstantMessageAddress(multiValueRepresentation: representation) expect(address).notTo(beNil()) expect(address!.service) == InstantMessageAddress.Services.Facebook expect(address!.username) == "johnny.b.goode" } it("works with vCard data") { let fileURL = NSBundle(forClass: AlternateBirthdaySpec.self).URLForResource("Johnny B. Goode", withExtension: "vcf")! let data = NSData(contentsOfURL: fileURL)! let records = ABPersonCreatePeopleInSourceWithVCardRepresentation(nil, data as CFDataRef).takeRetainedValue() as [ABRecordRef] let multiValue: ABMultiValueRef = ABRecordCopyValue(records[0], kABPersonInstantMessageProperty).takeRetainedValue() let values = LabeledValue<InstantMessageAddress>.read(multiValue) expect(values[0].label) == "facebook" expect(values[0].value) == InstantMessageAddress(service: InstantMessageAddress.Services.Facebook, username: "johnny.b.goode") expect(values[1].label) == "skype" expect(values[1].value) == InstantMessageAddress(service: InstantMessageAddress.Services.Skype, username: "jbgoode") } } } }
e3b28aac27c952709610f7234325a07e
55.75
142
0.646109
false
false
false
false
flodolo/firefox-ios
refs/heads/main
Client/Frontend/Login Management/DevicePasscodeRequiredViewController.swift
mpl-2.0
2
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import UIKit import Shared class DevicePasscodeRequiredViewController: SettingsViewController { private var shownFromAppMenu: Bool = false private var warningLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = DynamicFontHelper().DeviceFontExtraLarge label.text = .LoginsDevicePasscodeRequiredMessage label.textAlignment = .center label.numberOfLines = 0 return label }() private lazy var learnMoreButton: UIButton = { let button = UIButton(type: .system) button.translatesAutoresizingMaskIntoConstraints = false button.setTitle(.LoginsDevicePasscodeRequiredLearnMoreButtonTitle, for: .normal) button.addTarget(self, action: #selector(learnMoreButtonTapped), for: .touchUpInside) button.titleLabel?.font = DynamicFontHelper().DeviceFontExtraLarge return button }() init(shownFromAppMenu: Bool = false) { super.init() self.shownFromAppMenu = shownFromAppMenu } required init?(coder aDecoder: NSCoder) { fatalError("not implemented") } override func viewDidLoad() { super.viewDidLoad() if shownFromAppMenu { navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(doneButtonTapped)) } self.title = .Settings.Passwords.Title self.view.addSubviews(warningLabel, learnMoreButton) NSLayoutConstraint.activate([ warningLabel.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: 20), warningLabel.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -20), warningLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), warningLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor), learnMoreButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), learnMoreButton.topAnchor.constraint(equalTo: warningLabel.safeAreaLayoutGuide.bottomAnchor, constant: 20) ]) } @objc func doneButtonTapped(_ sender: UIButton) { dismiss(animated: true) } @objc func learnMoreButtonTapped(_ sender: UIButton) { let viewController = SettingsContentViewController() viewController.url = SupportUtils.URLForTopic("manage-saved-passwords-firefox-ios") navigationController?.pushViewController(viewController, animated: true) } }
b553e079a2b593a91c9d06e733055d7a
38.857143
143
0.711111
false
false
false
false
KasunApplications/susi_iOS
refs/heads/master
Susi/Controllers/ResetPasswordController/ResetPasswordVCMethods.swift
apache-2.0
1
// // ResetPasswordVCMethods.swift // Susi // // Created by Chashmeet Singh on 2017-08-11. // Copyright © 2017 FOSSAsia. All rights reserved. // import UIKit import Material extension ResetPasswordViewController { func dismissView() { self.dismiss(animated: true, completion: nil) } func setupView() { navigationItem.leftViews = [backButton] navigationItem.title = ControllerConstants.resetPassword navigationItem.titleLabel.textColor = .white guard let navBar = navigationController?.navigationBar as? NavigationBar else { return } navBar.backgroundColor = UIColor.hexStringToUIColor(hex: "#4184F3") } func validatePassword() -> [Bool:String] { if let newPassword = newPasswordField.text, let confirmPassword = confirmPasswordField.text { if newPassword.characters.count > 5 { if newPassword == confirmPassword { return [true: ""] } else { return [false: ControllerConstants.passwordDoNotMatch] } } else { return [false: ControllerConstants.passwordLengthShort] } } return [false: Client.ResponseMessages.ServerError] } func setUIActive(active: Bool) { isActive = active if active { indicator.startAnimating() } else { indicator.stopAnimating() } currentPasswordField.isEnabled = !active newPasswordField.isEnabled = !active confirmPasswordField.isEnabled = !active } }
1f84293a079af84f9505e29b993f9956
27.754386
87
0.608298
false
false
false
false
871553223/TestGit
refs/heads/master
CommonMacro/Pods/ReactiveCocoa/ReactiveCocoa/Swift/Event.swift
apache-2.0
51
// // Event.swift // ReactiveCocoa // // Created by Justin Spahr-Summers on 2015-01-16. // Copyright (c) 2015 GitHub. All rights reserved. // /// Represents a signal event. /// /// Signals must conform to the grammar: /// `Next* (Failed | Completed | Interrupted)?` public enum Event<Value, Error: ErrorType> { /// A value provided by the signal. case Next(Value) /// The signal terminated because of an error. No further events will be /// received. case Failed(Error) /// The signal successfully terminated. No further events will be received. case Completed /// Event production on the signal has been interrupted. No further events /// will be received. case Interrupted /// Whether this event indicates signal termination (i.e., that no further /// events will be received). public var isTerminating: Bool { switch self { case .Next: return false case .Failed, .Completed, .Interrupted: return true } } /// Lifts the given function over the event's value. public func map<U>(f: Value -> U) -> Event<U, Error> { switch self { case let .Next(value): return .Next(f(value)) case let .Failed(error): return .Failed(error) case .Completed: return .Completed case .Interrupted: return .Interrupted } } /// Lifts the given function over the event's error. public func mapError<F>(f: Error -> F) -> Event<Value, F> { switch self { case let .Next(value): return .Next(value) case let .Failed(error): return .Failed(f(error)) case .Completed: return .Completed case .Interrupted: return .Interrupted } } /// Unwraps the contained `Next` value. public var value: Value? { if case let .Next(value) = self { return value } else { return nil } } /// Unwraps the contained `Error` value. public var error: Error? { if case let .Failed(error) = self { return error } else { return nil } } } public func == <Value: Equatable, Error: Equatable> (lhs: Event<Value, Error>, rhs: Event<Value, Error>) -> Bool { switch (lhs, rhs) { case let (.Next(left), .Next(right)): return left == right case let (.Failed(left), .Failed(right)): return left == right case (.Completed, .Completed): return true case (.Interrupted, .Interrupted): return true default: return false } } extension Event: CustomStringConvertible { public var description: String { switch self { case let .Next(value): return "NEXT \(value)" case let .Failed(error): return "FAILED \(error)" case .Completed: return "COMPLETED" case .Interrupted: return "INTERRUPTED" } } } /// Event protocol for constraining signal extensions public protocol EventType { // The value type of an event. associatedtype Value /// The error type of an event. If errors aren't possible then `NoError` can be used. associatedtype Error: ErrorType /// Extracts the event from the receiver. var event: Event<Value, Error> { get } } extension Event: EventType { public var event: Event<Value, Error> { return self } }
f4e7b3bc6bf68c6ff1aa7bce0a32a3ac
19.951724
114
0.673469
false
false
false
false
denissimon/prediction-builder-swift
refs/heads/master
Sources/PredictionBuilder.swift
mit
1
// // PredictionBuilder.swift // https://github.com/denissimon/prediction-builder-swift // // Created by Denis Simon on 12/27/2016 // Copyright © 2016 PredictionBuilder. All rights reserved. // import Foundation public enum ArgumentError: Error, Equatable { case general(msg: String) } public struct PredictionResult { public let lnModel: String public let cor, x, y: Double public init(lnModel: String, cor: Double, x: Double, y: Double) { self.lnModel = lnModel self.cor = cor self.x = x self.y = y } } open class PredictionBuilder { public private(set) var x = Double() public private(set) var count = Int() public private(set) var xVector = [Double]() public private(set) var yVector = [Double]() public private(set) var data = [[Double]]() public init() {} public init(x: Double, data: [[Double]]) { set(x: x, data: data) } /** Sets / overrides instance properties */ public func set(x: Double, data: [[Double]]? = nil) { self.x = x if let data = data { self.count = data.count self.xVector = [] self.yVector = [] self.data = data .map ({ if $0.indices.contains(0) && $0.indices.contains(1) { self.xVector.append($0[0]) self.yVector.append($0[1]) } return $0 }) } } private func square(v: Double) -> Double { return v * v } /** Sum of the vector values */ private func sum(vector: [Double]) -> Double { return vector .reduce(0, +) } /** Sum of the vector squared values */ private func sumSquared(vector: [Double]) -> Double { return vector .map({ square(v: $0) }) .reduce(0, +) } /** Sum of the product of x and y */ private func sumXY(data: [[Double]]) -> Double { return data .map({ $0[0] * $0[1] }) .reduce(0, +) } /** The dispersion Dv = (Σv² / N) - (Σv / N)² */ private func dispersion(v: String) -> Double { let sumSquared = [ "x": { self.sumSquared(vector: self.xVector) }, "y": { self.sumSquared(vector: self.yVector) } ] let sum = [ "x": { self.sum(vector: self.xVector) }, "y": { self.sum(vector: self.yVector) } ] return (sumSquared[v]!() / Double(count)) - square(v: sum[v]!() / Double(count)) } /** The intercept a = (ΣY - b(ΣX)) / N */ private func aIntercept(b: Double) -> Double { return (sum(vector: yVector) / Double(count)) - (b * (sum(vector: xVector) / Double(count))) } /** The slope, or the regression coefficient b = ((ΣXY / N) - (ΣX / N)(ΣY / N)) / (Σv² / N) - (Σv / N)² */ private func bSlope() -> Double { return ((sumXY(data: data) / Double(count)) - ((sum(vector: xVector) / Double(count)) * (sum(vector: yVector) / Double(count)))) / dispersion(v: "x") } /** The Pearson's correlation coefficient Rxy = b * (√Dx / √Dy) */ private func corCoefficient(b: Double) -> Double { return b * (sqrt(dispersion(v: "x")) / sqrt(dispersion(v: "y"))) } /** Creats a linear model that fits the data. The resulting equation has the form: h(x) = a + bx */ private func createModel(a: Double, b: Double) -> (_ x: Double)->Double { return { (x: Double)->Double in return a + b*x } } private func round_(number: Double) -> Double { return round(100000 * number) / 100000 } /** Builds a prediction of the expected value of y for a given x, based on a linear regression model. */ public func build() throws -> PredictionResult { // Check the number of observations guard count >= 3 else { throw ArgumentError.general(msg: "The dataset should contain a minimum of 3 observations.") } // Check the number of x and y guard count == xVector.count else { throw ArgumentError.general(msg: "Mismatch in the number of x and y in the dataset.") } let b = round_(number: bSlope()) let a = round_(number: aIntercept(b: b)) let model = createModel(a: a, b: b) let y = round_(number: model(x)) return PredictionResult( lnModel: "\(a)+\(b)x", cor: round_(number: corCoefficient(b: b)), x: x, y: y ) } }
8057faf228f275676fe1b257e55d469d
26.10989
103
0.497163
false
false
false
false
ZekeSnider/Jared
refs/heads/master
JaredFramework/Route.swift
apache-2.0
1
// // Route.swift // JaredFramework // // Created by Zeke Snider on 2/3/19. // Copyright © 2019 Zeke Snider. All rights reserved. // import Foundation public enum Compare: String, Codable { case startsWith case contains case `is` case containsURL case isReaction } public struct Route: Decodable { public var name: String public var comparisons: [Compare: [String]] public var parameterSyntax: String? public var description: String? public var call: (Message) -> Void enum CodingKeys : String, CodingKey { case name case comparisons case parameterSyntax case description } public init(name: String, comparisons:[Compare: [String]], call: @escaping (Message) -> Void) { self.name = name self.comparisons = comparisons self.call = call } public init(name: String, comparisons:[Compare: [String]], call: @escaping (Message) -> Void, description: String) { self.name = name self.comparisons = comparisons self.call = call self.description = description } public init(name: String, comparisons:[Compare: [String]], call: @escaping (Message) -> Void, description: String, parameterSyntax: String) { self.name = name self.comparisons = comparisons self.call = call self.description = description self.parameterSyntax = parameterSyntax } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.name = try container.decode(String.self, forKey: .name) self.comparisons = try container.decode([Compare: [String]].self, forKey: .comparisons) self.description = try container.decode(String.self, forKey: .description) self.parameterSyntax = try container.decode(String.self, forKey: .parameterSyntax) self.call = { _ in } } } public protocol RoutingModule { var routes: [Route] {get} var description: String {get} init(sender: MessageSender) } public extension KeyedDecodingContainer { func decode(_ type: [Compare: [String]].Type, forKey key: Key) throws -> [Compare: [String]] { let stringDictionary = try self.decode([String: [String]].self, forKey: key) var dictionary = [Compare: [String]]() for (key, value) in stringDictionary { guard let anEnum = Compare(rawValue: key) else { let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Could not parse json key to an Compare object") throw DecodingError.dataCorrupted(context) } dictionary[anEnum] = value } return dictionary } }
be601344f090053b0c9e68610d4039be
31.635294
145
0.643115
false
false
false
false
vishalvshekkar/ArchivingSwiftStructures
refs/heads/master
ArchivingSwiftStructures3.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit // MARK: - The structure that is to be archived. struct Movie { let name: String let director: String let releaseYear: Int } // MARK: - The protocol, when implemented by a structure makes the structure archive-able protocol Dictionariable { func dictionaryRepresentation() -> NSDictionary init?(dictionaryRepresentation: NSDictionary?) } // MARK: - Implementation of the Dictionariable protocol by Movie struct extension Movie: Dictionariable { func dictionaryRepresentation() -> NSDictionary { let representation: [String: AnyObject] = [ "name": name, "director": director, "releaseYear": releaseYear ] return representation } init?(dictionaryRepresentation: NSDictionary?) { guard let values = dictionaryRepresentation else {return nil} if let name = values["name"] as? String, director = values["director"] as? String, releaseYear = values["releaseYear"] as? Int { self.name = name self.director = director self.releaseYear = releaseYear } else { return nil } } } // MARK: - Methods aiding in archiving and unarchiving the structures //Single Structure Instances func extractStructureFromArchive<T: Dictionariable>() -> T? { guard let encodedDict = NSKeyedUnarchiver.unarchiveObjectWithFile(path()) as? NSDictionary else {return nil} return T(dictionaryRepresentation: encodedDict) } func archiveStructure<T: Dictionariable>(structure: T) { let encodedValue = structure.dictionaryRepresentation() NSKeyedArchiver.archiveRootObject(encodedValue, toFile: path()) } //Multiple Structure Instances func extractStructuresFromArchive<T: Dictionariable>() -> [T] { guard let encodedArray = NSKeyedUnarchiver.unarchiveObjectWithFile(path()) as? [AnyObject] else {return []} return encodedArray.map{$0 as? NSDictionary}.flatMap{T(dictionaryRepresentation: $0)} } func archiveStructureInstances<T: Dictionariable>(structures: [T]) { let encodedValues = structures.map{$0.dictionaryRepresentation()} NSKeyedArchiver.archiveRootObject(encodedValues, toFile: path()) } //Metjod to get path to encode stuctures to func path() -> String { let documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first let path = documentsPath?.stringByAppendingString("/Movie") return path! } // MARK: - Testing Code //Single Structure Instances let movie = Movie(name: "Avatar", director: "James Cameron", releaseYear: 2009) archiveStructure(movie) let someMovie: Movie? = extractStructureFromArchive() someMovie?.director //Multiple Structure Instances let movies = [ Movie(name: "Avatar", director: "James Cameron", releaseYear: 2009), Movie(name: "The Dark Knight", director: "Christopher Nolan", releaseYear: 2008) ] archiveStructureInstances(movies) let someArray: [Movie] = extractStructuresFromArchive() someArray[0].director //Nested Structures struct Actor { let name: String let firstMovie: Movie } extension Actor: Dictionariable { func dictionaryRepresentation() -> NSDictionary { let representation: [String: AnyObject] = [ "name": name, "firstMovie": firstMovie.dictionaryRepresentation(), ] return representation } init?(dictionaryRepresentation: NSDictionary?) { guard let values = dictionaryRepresentation else {return nil} if let name = values["name"] as? String, let someMovie: Movie = extractStructureFromDictionary() { self.name = name self.firstMovie = someMovie } else { return nil } } }
c70ae1ef3e39cd1ffdbea5be879dfd7f
30.208
151
0.689231
false
false
false
false
movabletype/smartphone-app
refs/heads/master
MT_iOS/MT_iOS/Classes/View/UploaderTableViewCell.swift
mit
1
// // UploaderTableViewCell.swift // MT_iOS // // Created by CHEEBOW on 2016/02/09. // Copyright © 2016年 Six Apart, Ltd. All rights reserved. // import UIKit class UploaderTableViewCell: UITableViewCell { @IBOutlet weak var thumbView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var progressView: UIProgressView! @IBOutlet weak var checkMark: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code progress = 0.0 self.checkMark.alpha = 0.0 } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } var progress: Float { get { return progressView.progress } set { progressView.progress = newValue } } var uploaded: Bool { get { return self.checkMark.alpha == 1.0 } set { self.checkMark.alpha = newValue ? 1.0 : 0.0 } } }
5623366cfa171fc3914bb4c72f91fa8d
22.361702
63
0.598361
false
false
false
false
Arnoymous/MappableObject
refs/heads/develop
MappableObject/Classes/Helpers.swift
mit
1
// // Helpers.swift // Pods // // Created by Arnaud Dorgans on 02/09/2017. // // import UIKit import ObjectMapper import RealmSwift extension Realm { internal func safeWrite(_ block: (() throws -> Void)) throws { if isInWriteTransaction { try block() } else { try write(block) } } } extension ThreadConfined where Self: MappableObject { internal func update(realm: Realm? = nil, block: (Self)->Void) throws { if self.isSync { try ((realm ?? self.realm) ?? Realm()).safeWrite{ block(self) } } else { block(self) } } } extension Dictionary where Key == String { public func nestedValue(at key: String, nested: Bool = true, nestedKeyDelimiter: String) -> Any? { let keyPaths = nested ? key.components(separatedBy: nestedKeyDelimiter) : [key] return keyPaths.reduce(self, { (JSON, keyPath) -> Any? in if let JSON = (JSON as? [String:Any])?[keyPath] { return JSON } return nil }) } } extension BaseMappable where Self: MappableObject { internal static var hasPrimaryKey: Bool { return preferredPrimaryKey != nil } internal static var preferredPrimaryKey: String? { if let primaryKey = self.primaryKey() { return self.jsonPrimaryKey() ?? primaryKey } return nil } internal var isSync: Bool { return self.realm != nil && !self.isInvalidated } internal func validate(map: Map) { if map.mappingType == .fromJSON { if let context = map.context as? RealmMapContext { map.context = RealmMapContext.from(context: context, object: self) if self.isSync, !context.options.contains(.sync) { context.options = context.options.union(.sync) } } else { map.context = RealmMapContext.from(object: self) } } } public func toJSON(shouldIncludeNilValues: Bool = false, realm: Realm? = nil) -> [String:Any] { var JSON = [String:Any]() try? self.update(realm: realm) { JSON = Mapper<Self>(shouldIncludeNilValues: shouldIncludeNilValues).toJSON($0) } return JSON } public func toJSONString(shouldIncludeNilValues: Bool = false, prettyPrint: Bool = false, realm: Realm? = nil) -> String? { var JSONString: String? try? self.update(realm: realm) { JSONString = Mapper<Self>(shouldIncludeNilValues: shouldIncludeNilValues).toJSONString($0, prettyPrint: prettyPrint) } return JSONString } }
eae4725d7620c007d136fa0c1340947b
28.836957
128
0.576685
false
false
false
false
ben-ng/swift
refs/heads/master
validation-test/Sema/type_checker_crashers_fixed/rdar28023899.swift
apache-2.0
1
// RUN: %target-swift-frontend %s -typecheck // REQUIRES: asserts class B : Equatable { static func == (lhs: B, rhs: B) -> Bool { return true } } class C : B { static var v: C { return C() } } let c: C! = nil _ = c == .v
9392d7c4fa3668718068867cfadf6e35
16.538462
57
0.565789
false
false
false
false
prot3ct/Ventio
refs/heads/master
Ventio/Ventio/Controllers/EventsTableViewController.swift
apache-2.0
1
import Foundation import UIKit import RxSwift import Cosmos class EventsTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var eventsTableView: UITableView! internal var eventData: EventDataProtocol! private let disposeBag = DisposeBag() private var events = [EventProtocol]() { didSet { self.eventsTableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() self.eventsTableView.delegate = self self.eventsTableView.dataSource = self self.startLoading() self.eventData .getEventsForCurrentUser() .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .default)) .observeOn(MainScheduler.instance) .subscribe( onNext: { self.events.append($0) }, onError: { error in print(error) }, onCompleted: { self.stopLoading() }) .disposed(by: disposeBag) let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture)) swipeLeft.direction = UISwipeGestureRecognizerDirection.left self.view.addGestureRecognizer(swipeLeft) } func respondToSwipeGesture(gesture: UIGestureRecognizer) { if let swipeGesture = gesture as? UISwipeGestureRecognizer { switch swipeGesture.direction { case UISwipeGestureRecognizerDirection.left: changeInitialViewController(identifier: "myFriendsViewController") default: break } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.events.count } private func changeInitialViewController(identifier: String) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let initialViewController = storyboard .instantiateViewController(withIdentifier: identifier) UIApplication.shared.keyWindow?.rootViewController = initialViewController } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let eventCell = self.eventsTableView .dequeueReusableCell(withIdentifier: "EventTableViewCell", for: indexPath) as! EventTableViewCell let currentEvent = self.events[indexPath.row] eventCell.eventTitle.text = currentEvent.title eventCell.eventDate.text = currentEvent.date eventCell.eventTime.text = currentEvent.time return eventCell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let eventAtIndexPath = self.events[indexPath.row] let eventDetailsViewController = UIStoryboard(name: "Main", bundle: nil) .instantiateViewController(withIdentifier: "eventDetailsViewController") as! EventDetailsViewController eventDetailsViewController.currentEvent = eventAtIndexPath self.eventsTableView.deselectRow(at: indexPath, animated: true) UIApplication.shared.keyWindow?.rootViewController = eventDetailsViewController } func tableView(_ tableView: UITableView,titleForHeaderInSection section: Int) -> String? { return "My Events:" } } class EventTableViewCell: UITableViewCell { @IBOutlet weak var eventTitle: UILabel! @IBOutlet weak var eventDate: UILabel! @IBOutlet weak var eventTime: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
2629b7e39d9d7bf73a01d956ab152f0d
31.88
109
0.646959
false
false
false
false
Jnosh/SwiftBinaryHeapExperiments
refs/heads/master
BinaryHeap/ClassElementHeap.swift
mit
1
// // ClassElementHeap2.swift // BinaryHeap // // Created by Janosch Hildebrand on 14/11/15. // Copyright © 2015 Janosch Hildebrand. All rights reserved. // public typealias AnyComparableObject = protocol<AnyObject, Comparable> private struct Wrapper<Element : AnyComparableObject> : Comparable { let wrapped: Unmanaged<Element> init(_ element: Element) { wrapped = Unmanaged.passRetained(element) } var element: Element { return wrapped.takeUnretainedValue() } func consume() -> Element { return wrapped.takeRetainedValue() } func destroy() { wrapped.release() } } private func ==<Element>(lhs: Wrapper<Element>, rhs: Wrapper<Element>) -> Bool { return lhs.element == rhs.element } private func <<Element>(lhs: Wrapper<Element>, rhs: Wrapper<Element>) -> Bool { return lhs.element < rhs.element } /// A heap specialized for `AnyObject`s. /// /// Uses `Unmanaged` instances internally to avoid any ARC overhead. public struct ClassElementHeap<Element : AnyComparableObject> { /// The buffer object backing this heap private var buffer: ArrayBuffer<Wrapper<Element>> private mutating func reserveCapacity(minimumCapacity: Int) { buffer.reserveCapacity(minimumCapacity) } } // MARK: BinaryHeapType conformance extension ClassElementHeap : BinaryHeapType { public init() { buffer = ArrayBuffer(minimumCapacity: 0, retainElementsOnCopy: true) } public var count: Int { return buffer.count } public var first: Element? { return count > 0 ? buffer.elements.memory.element : nil } public mutating func insert(_value: Element) { // Optimization to prevent uneccessary copy // If we need to resize our element buffer we are guaranteed to have a unique copy afterwards if count == buffer.capacity { buffer.grow(count + 1) } else { buffer.ensureHoldsUniqueReference() } let value = Wrapper(_value) buffer.elements.advancedBy(count).initialize(value) buffer.count = buffer.count + 1 var index = count - 1 while index > 0 && (value < buffer.elements[parentIndex(index)]) { swap(&buffer.elements[index], &buffer.elements[parentIndex(index)]) index = parentIndex(index) } } public mutating func removeFirst() -> Element { precondition(!isEmpty, "Heap may not be empty.") buffer.ensureHoldsUniqueReference() buffer.count = buffer.count - 1 if count > 0 { swap(&buffer.elements[0], &buffer.elements[count]) heapify(buffer.elements, startIndex: 0, endIndex: count) } return buffer.elements.advancedBy(count).move().consume() } public mutating func removeAll(keepCapacity keepCapacity: Bool = false) { buffer.ensureHoldsUniqueReference() // Release unmanaged objects for element in UnsafeBufferPointer(start: buffer.elements, count: count) { element.consume() } buffer.removeAll(keepCapacity: keepCapacity) } } extension ClassElementHeap : CustomDebugStringConvertible, CustomStringConvertible { }
d9999b20b228e60fc724e938ce8a4332
27.928571
101
0.657407
false
false
false
false
Maxim-38RUS-Zabelin/ios-charts
refs/heads/master
Charts/Classes/Data/CandleChartDataSet.swift
apache-2.0
1
// // CandleChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class CandleChartDataSet: BarLineScatterCandleChartDataSet { /// the width of the candle-shadow-line in pixels. /// :default: 3.0 public var shadowWidth = CGFloat(1.5) /// the space between the candle entries /// :default: 0.1 (10%) private var _bodySpace = CGFloat(0.1) /// the color of the shadow line public var shadowColor: UIColor? /// color for open <= close public var decreasingColor: UIColor? /// color for open > close public var increasingColor: UIColor? /// Are decreasing values drawn as filled? public var decreasingFilled = false /// Are increasing values drawn as filled? public var increasingFilled = true public override init(yVals: [ChartDataEntry]?, label: String?) { super.init(yVals: yVals, label: label) } internal override func calcMinMax(#start: Int, end: Int) { if (yVals.count == 0) { return } var entries = yVals as! [CandleChartDataEntry] var endValue : Int if end == 0 { endValue = entries.count - 1 } else { endValue = end } _lastStart = start _lastEnd = end _yMin = entries[start].low _yMax = entries[start].high for (var i = start + 1; i <= endValue; i++) { var e = entries[i] if (e.low < _yMin) { _yMin = e.low } if (e.high > _yMax) { _yMax = e.high } } } /// the space that is left out on the left and right side of each candle, /// :default: 0.1 (10%), max 0.45, min 0.0 public var bodySpace: CGFloat { set { _bodySpace = newValue if (_bodySpace < 0.0) { _bodySpace = 0.0 } if (_bodySpace > 0.45) { _bodySpace = 0.45 } } get { return _bodySpace } } /// Are increasing values drawn as filled? public var isIncreasingFilled: Bool { return increasingFilled; } /// Are decreasing values drawn as filled? public var isDecreasingFilled: Bool { return decreasingFilled; } }
9415fe184c1dfbb2a69222c216083ef2
22.59322
77
0.517068
false
false
false
false
EXXETA/JSONPatchSwift
refs/heads/master
JsonPatchSwift/JPSContants.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the JSONPatchSwift open source project. // // Copyright (c) 2015 EXXETA AG // Licensed under Apache License v2.0 // // //===----------------------------------------------------------------------===// import Foundation // swiftlint:disable nesting struct JPSConstants { struct JsonPatch { struct Parameter { static let Op = "op" static let Path = "path" static let Value = "value" static let From = "from" } struct InitialisationErrorMessages { static let PatchEncoding = "Could not encode patch." static let PatchWithEmptyError = "Patch array does not contain elements." static let InvalidRootElement = "Root element is not an array of dictionaries or a single dictionary." static let OpElementNotFound = "Could not find 'op' element." static let PathElementNotFound = "Could not find 'path' element." static let InvalidOperation = "Operation is invalid." static let FromElementNotFound = "Could not find 'from' element." static let ValueElementNotFound = "Could not find 'value' element." } struct ErrorMessages { static let ValidationError = "Could not validate JSON." } } struct Operation { static let Add = "add" static let Remove = "remove" static let Replace = "replace" static let Move = "move" static let Copy = "copy" static let Test = "test" } struct JsonPointer { static let Delimiter = "/" static let EndOfArrayMarker = "-" static let EmptyString = "" static let EscapeCharater = "~" static let EscapedDelimiter = "~1" static let EscapedEscapeCharacter = "~0" } }
3bbdbc82cc1740fedfc9dcb72066a86b
30.983871
114
0.540091
false
false
false
false
eurofurence/ef-app_ios
refs/heads/release/4.0.0
Packages/EurofurenceApplication/Tests/EurofurenceApplicationTests/Application/Components/News/Widgets/Events/Test Doubles/FakeEventViewModel.swift
mit
1
import EurofurenceApplication import ObservedObject class FakeEventViewModel: EventViewModel { @Observed var name: String @Observed var location: String @Observed var startTime: String @Observed var endTime: String @Observed var isFavourite: Bool @Observed var isSponsorOnly: Bool @Observed var isSuperSponsorOnly: Bool @Observed var isArtShow: Bool @Observed var isKageEvent: Bool @Observed var isDealersDen: Bool @Observed var isMainStage: Bool @Observed var isPhotoshoot: Bool @Observed var isFaceMaskRequired: Bool init( name: String = "Name", location: String = "Location", startTime: String = "Start Time", endTime: String = "End Time", isFavourite: Bool = false, isSponsorOnly: Bool = false, isSuperSponsorOnly: Bool = false, isArtShow: Bool = false, isKageEvent: Bool = false, isDealersDen: Bool = false, isMainStage: Bool = false, isPhotoshoot: Bool = false, isFaceMaskRequired: Bool = false ) { self.name = name self.location = location self.startTime = startTime self.endTime = endTime self.isFavourite = isFavourite self.isSponsorOnly = isSponsorOnly self.isSuperSponsorOnly = isSuperSponsorOnly self.isArtShow = isArtShow self.isKageEvent = isKageEvent self.isDealersDen = isDealersDen self.isMainStage = isMainStage self.isPhotoshoot = isPhotoshoot self.isFaceMaskRequired = isFaceMaskRequired } }
813059e529e9bb7d3534fc9cea232eb8
31
52
0.655625
false
false
false
false
Liujlai/DouYuD
refs/heads/master
DYTV/DYTV/RecommendCycleView.swift
mit
1
// // RecommendCycleView.swift // DYTV // // Created by idea on 2017/8/10. // Copyright © 2017年 idea. All rights reserved. // import UIKit let kCycleCellID = "kCycleCellID" class RecommendCycleView: UIView { //MARK: - 定义属性 var cycleTimer : Timer? var cycleModels : [CycleModel]?{ didSet{ // 1.刷新collectionView collectionView.reloadData() // 2.设置pageControl个数 pageControl.numberOfPages = cycleModels?.count ?? 0 // 3.默认滚动到中间某个位置 // -->刚开始是往前滚时的操作 let indexPath = NSIndexPath(item: (cycleModels?.count ?? 0) * 10, section: 0) collectionView.selectItem(at: indexPath as IndexPath, animated: false, scrollPosition: .left) // 4.添加定时器 removeCycleTimer() addCycleTimer() } } //控件属性 @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ // 系统回调函数 override func awakeFromNib() { super.awakeFromNib() // 注册Cell collectionView.register(UINib(nibName: "CollectionCycleCell", bundle: nil), forCellWithReuseIdentifier: kCycleCellID) // 设置collectionView的layout let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 collectionView.isPagingEnabled = true } override func layoutSubviews() { super.layoutSubviews() // 设置collectionView的layout let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 // 左右进行滚动 layout.scrollDirection = .horizontal collectionView.isPagingEnabled = true } } //MARK: - 提供一个快速创建View的类方法 extension RecommendCycleView{ class func recommendCycleView() -> RecommendCycleView{ return Bundle.main.loadNibNamed("RecommendCycleView", owner: nil, options: nil)?.first as! RecommendCycleView } } //MARK: - 遵守UICollectionView的数据源协议 extension RecommendCycleView:UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //无限轮播 *10000 return (cycleModels?.count ?? 0) * 10000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCellID, for: indexPath) as! CollectionCycleCell //无限轮播 % (cycleModels?.count)! cell.cycleModel = cycleModels![indexPath.item % (cycleModels?.count)!] // cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.red :UIColor.blue return cell } } //MARK: -遵守UICollectonView的代理协议 extension RecommendCycleView : UICollectionViewDelegate{ // 监听滚动 func scrollViewDidScroll(_ scrollView: UIScrollView) { // 1.获取滚动的偏移量 ----->+ scrollView.bounds.width * 0.5 是滑动到一半的时候显示下一张 let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5 // 2.计算pageControl的currentIndex //无限轮播 % (cycleModels?.count ?? 1) --->对到最后page View不动了的修改 pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1) } // 监听用户的拖拽 // 开始拖拽移除定时器 func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { removeCycleTimer() } // 结束拖拽添加定时器 func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { addCycleTimer() } } //MARK: 对定时器的操作方法 extension RecommendCycleView{ func addCycleTimer(){ cycleTimer = Timer(timeInterval: 3.0, target: self , selector: #selector(self.scrollToNext), userInfo: nil, repeats: true) RunLoop.main.add(cycleTimer!, forMode:RunLoopMode.commonModes) } func removeCycleTimer() { cycleTimer?.invalidate()// 从运行循环中移除 cycleTimer = nil } //滚动到下一个 @objc func scrollToNext(){ // 1.获取滚动的偏移量 let currentOffsetX = collectionView.contentOffset.x let offsetX = currentOffsetX + collectionView.bounds.width // 2.滚动到该位置 collectionView.setContentOffset(CGPoint(x: offsetX,y : 0), animated: true) } }
77a310040696772408ec7c842f4c78a7
31.175325
130
0.631887
false
false
false
false
noppoMan/swifty-libuv
refs/heads/master
Sources/Address.swift
mit
1
// // Address.swift // SwiftyLibuv // // Created by Yuki Takei on 6/12/16. // // #if os(Linux) import Glibc #else import Darwin.C #endif import CLibUv /** Wrapper class of sockaddr/sockaddr_in Currently only supported ipv4 */ public class Address { public private(set) var host: String public private(set)var port: Int var _sockAddrinPtr: UnsafeMutablePointer<sockaddr_in>? = nil var address: UnsafePointer<sockaddr> { if _sockAddrinPtr == nil { _sockAddrinPtr = UnsafeMutablePointer<sockaddr_in>.allocate(capacity: 1) uv_ip4_addr(host, Int32(port), _sockAddrinPtr) } return _sockAddrinPtr!.cast(to: UnsafePointer<sockaddr>.self) } /** Convert a string containing an IPv4 addresses to a binary structure. - parameter host: Host to bind - parameter port: Port to bind */ public init(host: String = "0.0.0.0", port: Int = 3000){ self.host = host self.port = port } deinit { if _sockAddrinPtr != nil { dealloc(_sockAddrinPtr!, capacity: 1) } } } extension Address: CustomStringConvertible { public var description: String { return "\(host):\(port)" } }
e4093700b45a52397d105a79039ca4fc
20.15
84
0.606777
false
false
false
false
etiennemartin/jugglez
refs/heads/master
Jugglez/GameCenterManager.swift
mit
1
// // GameCenterManager.swift // Jugglez // // Created by Etienne Martin on 2015-04-12. // Copyright (c) 2015 Etienne Martin. All rights reserved. // import Foundation import GameKit // MARK: Game Center Manager delegate. protocol GameCenterManagerDelegate { func processGameCenterAuth(error: NSError?) func scoreReported(leadershipId: String, error: NSError?) func reloadScoresComplete(leaderBoard: GKLeaderboard, error: NSError?) func achievementSubmitted(achievement: GKAchievement?, error: NSError?) func achievementResetResult(error: NSError?) func mappedPlayerIDToPlayer(player: GKPlayer?, error: NSError?) } // MARK: - Game Center Manager // Game Center Manager takes care of the communication between the app and Apple's // Game Center service. class GameCenterManager: NSObject { private var _earnedAchievementCache: [String:GKAchievement]? = [:] private var _delegate: GameCenterManagerDelegate? = nil override init() { super.init() } // Singleton access static let sharedInstance = GameCenterManager() // Authenticates the local user with the Game Center Service func authenticateLocalUser() { let localPlayer = GKLocalPlayer.localPlayer() localPlayer.authenticateHandler = {(viewController: UIViewController?, error: NSError?) -> Void in if viewController != nil { self.authViewController = viewController NSNotificationCenter.defaultCenter().postNotificationName(GameCenterManager.presentGameCenterNotificationViewController, object: self) } else if GKLocalPlayer.localPlayer().authenticated { self.authViewController = nil // release self.enabled = true print("GameCenter, localPlayer (\(GKLocalPlayer.localPlayer().displayName!)) auth_status: \(GKLocalPlayer.localPlayer().authenticated)") } if self._delegate != nil { self._delegate?.processGameCenterAuth(error) } } } // Reports a score to a leaderboard func reportScore(score: Int64, identifier: String) { if enabled == false { print("Can't submit score, local user isn't authenticated.") if _delegate != nil { let err: NSError = NSError(domain: "GameCenterManager", code: -1, userInfo: nil) _delegate?.scoreReported(identifier, error:err) } return } let scoreReporter: GKScore = GKScore(leaderboardIdentifier: identifier) scoreReporter.value = score GKScore.reportScores([scoreReporter], withCompletionHandler: { (error: NSError?) -> Void in if error != nil { print("Failed to submit score for leaderboard: \(identifier) err: \(error!.localizedDescription)") } else { print("Score submitted for leaderboard: \(identifier)") } if self._delegate != nil { self._delegate?.scoreReported(identifier, error:error) } }) } // Reloads/Refreshes the score for a given leaderboard func reloadHighScoresForIdentity(identifier: String) { let leaderboard = GKLeaderboard() leaderboard.identifier = identifier leaderboard.loadScoresWithCompletionHandler { (scores: [GKScore]?, error: NSError?) -> Void in if error != nil { print("Failed to reload scores: \(error!.localizedDescription)") } else { print("Successfully reloaded scores for leaderboard: \(leaderboard.identifier!)") } if self._delegate != nil { self._delegate?.reloadScoresComplete(leaderboard, error: error) } } } // Submit an Achievement to the Game Center func submitAchievement(identifier: String, percentComplete: Double) { // GameCenter check for duplicate achievements when the achievement is submitted, but if you only want to report // new achievements to the user, then you need to check if it's been earned // // before you submit. Otherwise you'll end up with a race condition between loadAchievementsWithCompletionHandler // and reportAchievementWithCompletionHandler. To avoid this, we fetch the current achievement list once, // then cache it and keep it updated with any new achievements. if _earnedAchievementCache == nil { GKAchievement.loadAchievementsWithCompletionHandler({ (achievements: [GKAchievement]?, error: NSError?) -> Void in guard achievements == nil else { return } if error == nil { var tempCache: [String:GKAchievement] = [:] for a in achievements! { let achievement: GKAchievement = a tempCache[achievement.identifier!] = achievement } self._earnedAchievementCache = tempCache self.submitAchievement(identifier, percentComplete: percentComplete) } else { // Something went wrong if self._delegate != nil { self._delegate?.achievementSubmitted(nil, error: error) } } }) } else { // Search the list for the ID we're using... var achievement: GKAchievement? = self._earnedAchievementCache![identifier] if achievement != nil { if achievement?.percentComplete >= 100.0 || achievement?.percentComplete >= percentComplete { // Achievement was already completed return } achievement?.percentComplete = percentComplete } else { achievement = GKAchievement(identifier: identifier) achievement?.percentComplete = percentComplete // Add achievement to the cache self._earnedAchievementCache![achievement!.identifier!] = achievement } if achievement != nil { // Submit the achievement GKAchievement.reportAchievements([achievement!], withCompletionHandler: { (error: NSError?) -> Void in if error != nil { print("Failed to report Achievement: \(error!.localizedDescription)") } else { print("Successfully reported achievement") } if self._delegate != nil { self._delegate?.achievementSubmitted(achievement, error: error) } }) } } } // Reset all cached achievements func resetAchievements() { _earnedAchievementCache?.removeAll() GKAchievement.resetAchievementsWithCompletionHandler { (error: NSError?) -> Void in if error != nil { print("Failed to reset Achievements: \(error!.localizedDescription)") } else { print("Successfully reset achievements") } if self._delegate != nil { self._delegate?.achievementResetResult(error) } } } // Maps a player's ID to it's user defined ID. func mapPlayerIDtoPlayer(playerId: String) { if _delegate == nil { return } GKPlayer.loadPlayersForIdentifiers([playerId], withCompletionHandler: { (players: [GKPlayer]?, error: NSError?) -> Void in guard players == nil else { return } var player: GKPlayer? = nil for p in players! { let tmpPlayer: GKPlayer = p if tmpPlayer.playerID == playerId { player = tmpPlayer break } } self._delegate?.mappedPlayerIDToPlayer(player!, error: error) }) } // Name of the NSNotification that is sent when the Game Center services requires the user // to authenticate class var presentGameCenterNotificationViewController: String { get { return "present_game_center_notification_view_controller" } } // Determines if the Game Center Manager is ready to be used. (i.e. user is authenticated with the // service var enabled: Bool = false // Holds a reference to the UIViewController passed by the Game Center service during authentication var authViewController: UIViewController? = nil // List of cached achievments var earnedAchievementCache: [String:GKAchievement]? { get { return _earnedAchievementCache } } var delegate: GameCenterManagerDelegate? { get { return _delegate } set (value) { _delegate = value } } }
11d2257f55a3226640d21406ada9f8c0
37.25
152
0.592777
false
false
false
false
marklin2012/iOS_Animation
refs/heads/master
Section3/Chapter15/O2Refresh_completed/O2Refresh/RefreshView.swift
mit
1
// // RefreshView.swift // O2Refresh // // Created by O2.LinYi on 16/3/18. // Copyright © 2016年 jd.com. All rights reserved. // import UIKit import QuartzCore // MARK: - Refresh View Delegate Protocol protocol RefreshViewDelegate { func refreshViewDidRefresh(refreshView: RefreshView) } class RefreshView: UIView { var delegate: RefreshViewDelegate? var scrollView: UIScrollView? var refreshing: Bool = false var progress: CGFloat = 0 var isRefreshing = false let ovalShapeLayer: CAShapeLayer = CAShapeLayer() let airplaneLayer: CALayer = CALayer() init(frame: CGRect, scrollView: UIScrollView) { super.init(frame: frame) self.scrollView = scrollView // add the background image let imageView = UIImageView(image: UIImage(named: "refresh-view-bg")) imageView.frame = bounds imageView.contentMode = .ScaleAspectFill imageView.clipsToBounds = true addSubview(imageView) ovalShapeLayer.strokeColor = UIColor.whiteColor().CGColor ovalShapeLayer.fillColor = UIColor.clearColor().CGColor ovalShapeLayer.lineWidth = 4 ovalShapeLayer.lineDashPattern = [2,3] let refreshRadius = frame.size.height / 2 * 0.8 ovalShapeLayer.path = UIBezierPath(ovalInRect: CGRect(x: frame.size.width/2 - refreshRadius, y: frame.size.height/2 - refreshRadius, width: 2 * refreshRadius, height: 2 * refreshRadius)).CGPath layer.addSublayer(ovalShapeLayer) let airplaneImage = UIImage(named: "icon-plane")! airplaneLayer.contents = airplaneImage.CGImage airplaneLayer.bounds = CGRect(x: 0, y: 0, width: airplaneImage.size.width, height: airplaneImage.size.height) airplaneLayer.position = CGPoint(x: frame.size.width/2 + frame.size.height/2 * 0.8, y: frame.size.height/2) layer.addSublayer(airplaneLayer) airplaneLayer.opacity = 0 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - animate the refresh view func beginRefreshing() { isRefreshing = true UIView.animateWithDuration(0.3, animations: { var newInsets = self.scrollView!.contentInset newInsets.top += self.frame.size.height self.scrollView?.contentInset = newInsets }) let strokeStartAnimation = CABasicAnimation(keyPath: "strokeStart") strokeStartAnimation.fromValue = -0.5 strokeStartAnimation.toValue = 1 let strokeEndAnimation = CABasicAnimation(keyPath: "strokeEnd") strokeEndAnimation.fromValue = 0 strokeEndAnimation.toValue = 1 let strokeAnimationGroup = CAAnimationGroup() strokeAnimationGroup.duration = 1.5 strokeAnimationGroup.repeatCount = 5 strokeAnimationGroup.animations = [strokeStartAnimation, strokeEndAnimation] ovalShapeLayer.addAnimation(strokeAnimationGroup, forKey: nil) // add plane animation let flightAnimation = CAKeyframeAnimation(keyPath: "position") flightAnimation.path = ovalShapeLayer.path flightAnimation.calculationMode = kCAAnimationPaced let airplaneOrientationAnimation = CABasicAnimation(keyPath: "transform.rotation") airplaneOrientationAnimation.fromValue = 0 airplaneOrientationAnimation.toValue = 2 * M_PI let flightAnimationGroup = CAAnimationGroup() flightAnimationGroup.duration = 1.5 flightAnimationGroup.repeatDuration = 5 flightAnimationGroup.animations = [flightAnimation, airplaneOrientationAnimation] airplaneLayer.addAnimation(flightAnimationGroup, forKey: nil) } func endRefreshing() { isRefreshing = false UIView.animateWithDuration(0.3, delay: 0, options: [.CurveEaseOut], animations: { () -> Void in var newInsets = self.scrollView!.contentInset newInsets.top -= self.frame.size.height self.scrollView!.contentInset = newInsets }, completion: { _ in // finished }) } func redrawFromProgress(progress: CGFloat) { ovalShapeLayer.strokeEnd = progress airplaneLayer.opacity = Float(progress) } } extension RefreshView: UIScrollViewDelegate { func scrollViewDidScroll(scrollView: UIScrollView) { let offsetY = CGFloat(max(-(scrollView.contentOffset.y + scrollView.contentInset.top), 0)) progress = min(max(offsetY / frame.size.height, 0.0), 1.0) if !isRefreshing { redrawFromProgress(self.progress) } } func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if !isRefreshing && progress >= 1.0 { delegate?.refreshViewDidRefresh(self) beginRefreshing() } } }
abf480b4a789112fe5a7b32990452e5a
34.479167
201
0.655706
false
false
false
false
brl-x/TaskAPIUsingHeroku
refs/heads/master
Sources/App/Controllers/TaskController.swift
mit
1
// // TaskController.swift // App // // Created by Keith Moon on 18/09/2017. // import Vapor import HTTP import JSON extension Task: Parameterizable { static var uniqueSlug: String { return "task" } // returns the found model for the resolved url parameter static func make(for parameter: String) throws -> Task { guard let task = try Task.find(parameter) else { throw Abort.notFound } return task } } final class TaskController: ResourceRepresentable, EmptyInitializable { typealias Model = Task func index(request: Request) throws -> ResponseRepresentable { let tasks: [Task] = try Task.all() return try tasks.makeJSON() } func create(request: Request) throws -> ResponseRepresentable { guard let json = request.json else { throw Abort.badRequest } let task = try Task(json: json) try task.save() return try task.makeJSON() } func show(request: Request, task: Task) throws -> ResponseRepresentable { return try task.makeJSON() } func update(_ req: Request, task: Task) throws -> ResponseRepresentable { try task.update(for: req) try task.save() return try task.makeJSON() } func delete(request: Request, task: Task) throws -> ResponseRepresentable { try task.delete() let tasks: [Task] = try Task.all() return try tasks.makeJSON() } func makeResource() -> Resource<Task> { return Resource(index: index, store: create, show: show, update: update, destroy: delete) } }
ccfb24731f452c5e749906b362a2e8cf
24.169014
79
0.570229
false
false
false
false
siriuscn/Alamofire-iOS8
refs/heads/master
dist/Source/Request.swift
mit
1
// // Request.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. public protocol RequestAdapter { /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result. /// /// - parameter urlRequest: The URL request to adapt. /// /// - throws: An `Error` if the adaptation encounters an error. /// /// - returns: The adapted `URLRequest`. func adapt(_ urlRequest: URLRequest) throws -> URLRequest } // MARK: - /// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void /// A type that determines whether a request should be retried after being executed by the specified session manager /// and encountering an error. public protocol RequestRetrier { /// Determines whether the `Request` should be retried by calling the `completion` closure. /// /// This operation is fully asychronous. Any amount of time can be taken to determine whether the request needs /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly /// cleaned up after. /// /// - parameter manager: The session manager the request was executed on. /// - parameter request: The request that failed due to the encountered error. /// - parameter error: The error encountered when executing the request. /// - parameter completion: The completion closure to be executed when retry decision has been determined. func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) } // MARK: - protocol TaskConvertible { func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask } /// A dictionary of headers to apply to a `URLRequest`. public typealias HTTPHeaders = [String: String] // MARK: - /// Responsible for sending a request and receiving the response and associated data from the server, as well as /// managing its underlying `URLSessionTask`. open class Request { // MARK: Helper Types /// A closure executed when monitoring upload or download progress of a request. public typealias ProgressHandler = (Progress) -> Void enum RequestTask { case data(TaskConvertible?, URLSessionTask?) case download(TaskConvertible?, URLSessionTask?) case upload(TaskConvertible?, URLSessionTask?) case stream(TaskConvertible?, URLSessionTask?) } // MARK: Properties /// The delegate for the underlying task. open internal(set) var delegate: TaskDelegate { get { taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } return taskDelegate } set { taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } taskDelegate = newValue } } /// The underlying task. open var task: URLSessionTask? { return delegate.task } /// The session belonging to the underlying task. open let session: URLSession /// The request sent or to be sent to the server. open var request: URLRequest? { return task?.originalRequest } /// The response received from the server, if any. open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } let originalTask: TaskConvertible? var startTime: CFAbsoluteTime? var endTime: CFAbsoluteTime? var validations: [() -> Void] = [] private var taskDelegate: TaskDelegate private var taskDelegateLock = NSLock() // MARK: Lifecycle init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { self.session = session switch requestTask { case .data(let originalTask, let task): taskDelegate = DataTaskDelegate(task: task) self.originalTask = originalTask case .download(let originalTask, let task): taskDelegate = DownloadTaskDelegate(task: task) self.originalTask = originalTask case .upload(let originalTask, let task): taskDelegate = UploadTaskDelegate(task: task) self.originalTask = originalTask case .stream(let originalTask, let task): taskDelegate = TaskDelegate(task: task) self.originalTask = originalTask } delegate.error = error delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } } // MARK: Authentication /// Associates an HTTP Basic credential with the request. /// /// - parameter user: The user. /// - parameter password: The password. /// - parameter persistence: The URL credential persistence. `.ForSession` by default. /// /// - returns: The request. @discardableResult open func authenticate( user: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self { let credential = URLCredential(user: user, password: password, persistence: persistence) return authenticate(usingCredential: credential) } /// Associates a specified credential with the request. /// /// - parameter credential: The credential. /// /// - returns: The request. @discardableResult open func authenticate(usingCredential credential: URLCredential) -> Self { delegate.credential = credential return self } /// Returns a base64 encoded basic authentication credential as an authorization header tuple. /// /// - parameter user: The user. /// - parameter password: The password. /// /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } let credential = data.base64EncodedString(options: []) return (key: "Authorization", value: "Basic \(credential)") } // MARK: State /// Resumes the request. open func resume() { guard let task = task else { delegate.queue.isSuspended = false ; return } if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } task.resume() NotificationCenter.default.post( name: Notification.Name.Task.DidResume, object: self, userInfo: [Notification.Key.Task: task] ) } /// Suspends the request. open func suspend() { guard let task = task else { return } task.suspend() NotificationCenter.default.post( name: Notification.Name.Task.DidSuspend, object: self, userInfo: [Notification.Key.Task: task] ) } /// Cancels the request. open func cancel() { guard let task = task else { return } task.cancel() NotificationCenter.default.post( name: Notification.Name.Task.DidCancel, object: self, userInfo: [Notification.Key.Task: task] ) } } // MARK: - CustomStringConvertible extension Request: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as /// well as the response status code if a response has been received. open var description: String { var components: [String] = [] if let HTTPMethod = request?.httpMethod { components.append(HTTPMethod) } if let urlString = request?.url?.absoluteString { components.append(urlString) } if let response = response { components.append("(\(response.statusCode))") } return components.joined(separator: " ") } } // MARK: - CustomDebugStringConvertible extension Request: CustomDebugStringConvertible { /// The textual representation used when written to an output stream, in the form of a cURL command. open var debugDescription: String { return cURLRepresentation() } func cURLRepresentation() -> String { var components = ["$ curl -i"] guard let request = self.request, let url = request.url, let host = url.host else { return "$ curl command could not be created" } if let httpMethod = request.httpMethod, httpMethod != "GET" { components.append("-X \(httpMethod)") } if let credentialStorage = self.session.configuration.urlCredentialStorage { let protectionSpace = URLProtectionSpace( host: host, port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { for credential in credentials { components.append("-u \(credential.user!):\(credential.password!)") } } else { if let credential = delegate.credential { components.append("-u \(credential.user!):\(credential.password!)") } } } if session.configuration.httpShouldSetCookies { if let cookieStorage = session.configuration.httpCookieStorage, let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"") } } var headers: [AnyHashable: Any] = [:] if let additionalHeaders = session.configuration.httpAdditionalHeaders { for (field, value) in additionalHeaders where field != AnyHashable("Cookie") { headers[field] = value } } if let headerFields = request.allHTTPHeaderFields { for (field, value) in headerFields where field != "Cookie" { headers[field] = value } } for (field, value) in headers { components.append("-H \"\(field): \(value)\"") } if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) { var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") components.append("-d \"\(escapedBody)\"") } components.append("\"\(url.absoluteString)\"") return components.joined(separator: " \\\n\t") } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionDataTask`. open class DataRequest: Request { // MARK: Helper Types struct Requestable: TaskConvertible { let urlRequest: URLRequest func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { let urlRequest = try self.urlRequest.adapt(using: adapter) return queue.syncResult { session.dataTask(with: urlRequest) } } } // MARK: Properties /// The progress of fetching the response data from the server for the request. open var progress: Progress { return dataDelegate.progress } var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } // MARK: Stream /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. /// /// This closure returns the bytes most recently received from the server, not including data from previous calls. /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is /// also important to note that the server data in any `Response` object will be `nil`. /// /// - parameter closure: The code to be executed periodically during the lifecycle of the request. /// /// - returns: The request. @discardableResult open func stream(closure: ((Data) -> Void)? = nil) -> Self { dataDelegate.dataStream = closure return self } // MARK: Progress /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is read from the server. /// /// - returns: The request. @discardableResult open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { dataDelegate.progressHandler = (closure, queue) return self } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. open class DownloadRequest: Request { // MARK: Helper Types /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the /// destination URL. public struct DownloadOptions: OptionSet { /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. public let rawValue: UInt /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. /// /// - parameter rawValue: The raw bitmask value for the option. /// /// - returns: A new log level instance. public init(rawValue: UInt) { self.rawValue = rawValue } } /// A closure executed once a download request has successfully completed in order to determine where to move the /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and /// the options defining how the file should be moved. public typealias DownloadFileDestination = ( _ temporaryURL: URL, _ response: HTTPURLResponse) -> (destinationURL: URL, options: DownloadOptions) enum Downloadable: TaskConvertible { case request(URLRequest) case resumeData(Data) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { let task: URLSessionTask switch self { case let .request(urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.syncResult { session.downloadTask(with: urlRequest) } case let .resumeData(resumeData): task = queue.syncResult { session.downloadTask(withResumeData: resumeData) } } return task } } // MARK: Properties /// The resume data of the underlying download task if available after a failure. open var resumeData: Data? { return downloadDelegate.resumeData } /// The progress of downloading the response data from the server for the request. open var progress: Progress { return downloadDelegate.progress } var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } // MARK: State /// Cancels the request. open override func cancel() { downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } NotificationCenter.default.post( name: Notification.Name.Task.DidCancel, object: self, userInfo: [Notification.Key.Task: task as Any] ) } // MARK: Progress /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is read from the server. /// /// - returns: The request. @discardableResult open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { downloadDelegate.progressHandler = (closure, queue) return self } // MARK: Destination /// Creates a download file destination closure which uses the default file manager to move the temporary file to a /// file URL in the first available directory with the specified search path directory and search path domain mask. /// /// - parameter directory: The search path directory. `.DocumentDirectory` by default. /// - parameter domain: The search path domain mask. `.UserDomainMask` by default. /// /// - returns: A download file destination closure. open class func suggestedDownloadDestination( for directory: FileManager.SearchPathDirectory = .documentDirectory, in domain: FileManager.SearchPathDomainMask = .userDomainMask) -> DownloadFileDestination { return { temporaryURL, response in let directoryURLs = FileManager.default.urls(for: directory, in: domain) if !directoryURLs.isEmpty { return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) } return (temporaryURL, []) } } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. open class UploadRequest: DataRequest { // MARK: Helper Types enum Uploadable: TaskConvertible { case data(Data, URLRequest) case file(URL, URLRequest) case stream(InputStream, URLRequest) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { let task: URLSessionTask switch self { case let .data(data, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.syncResult { session.uploadTask(with: urlRequest, from: data) } case let .file(url, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.syncResult { session.uploadTask(with: urlRequest, fromFile: url) } case let .stream(_, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.syncResult { session.uploadTask(withStreamedRequest: urlRequest) } } return task } } // MARK: Properties /// The progress of uploading the payload to the server for the upload request. open var uploadProgress: Progress { return uploadDelegate.uploadProgress } var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } // MARK: Upload Progress /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to /// the server. /// /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress /// of data being read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is sent to the server. /// /// - returns: The request. @discardableResult open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { uploadDelegate.uploadProgressHandler = (closure, queue) return self } } // MARK: - #if !os(watchOS) /// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. @available(iOS 9.0, *) open class StreamRequest: Request { enum Streamable: TaskConvertible { case stream(hostName: String, port: Int) case netService(NetService) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { let task: URLSessionTask switch self { case let .stream(hostName, port): task = queue.syncResult { session.streamTask(withHostName: hostName, port: port) } case let .netService(netService): task = queue.syncResult { session.streamTask(with: netService) } } return task } } } #endif
86923f7f8d53d5ee3918be7006300463
36.347754
131
0.651697
false
false
false
false
AppriaTT/Swift_SelfLearning
refs/heads/master
Swift/swift05 roll view/swift05 roll view/ViewController.swift
mit
1
// // ViewController.swift // swift05 roll view // // Created by Aaron on 16/7/8. // Copyright © 2016年 Aaron. All rights reserved. // import UIKit class ViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate { var interests : [Interest]! override func viewDidLoad() { super.viewDidLoad() //创建模糊层 let bgView = UIImageView(image: UIImage(named: "blue")) bgView.frame = self.view.bounds self.view.addSubview(bgView) let effectView = UIVisualEffectView(frame: self.view.bounds) effectView.effect = UIBlurEffect(style: UIBlurEffectStyle.Light) self.view.addSubview(effectView) //创建collectionView let layout = UICollectionViewFlowLayout() layout.itemSize = CGSizeMake(300, 400) layout.scrollDirection = UICollectionViewScrollDirection.Horizontal let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.delegate = self collectionView.dataSource = self collectionView.backgroundColor = UIColor.clearColor() self.view.addSubview(collectionView) collectionView.registerClass(ZHCollectionViewCell().classForCoder, forCellWithReuseIdentifier: "cell") // 数据源创建 interests = [ Interest(title: "Hello there, i miss u.", featuredImage: UIImage(named: "hello")!), Interest(title: "🐳🐳🐳🐳🐳",featuredImage: UIImage(named: "dudu")!), Interest(title: "Training like this, #bodyline", featuredImage: UIImage(named: "bodyline")!), Interest(title: "I'm hungry, indeed.", featuredImage: UIImage(named: "wave")!), Interest(title: "Dark Varder, #emoji", featuredImage: UIImage(named: "darkvarder")!), Interest(title: "I have no idea, bitch", featuredImage: UIImage(named: "hhhhh")!),] collectionView .reloadData() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int{ return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return interests.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! ZHCollectionViewCell let interest = interests[indexPath.row] print(interest.title) cell.interest = interest return cell } }
28546e168d2615926c2b7b0f85f00709
39.521127
130
0.672923
false
false
false
false
ewhitley/CDAKit
refs/heads/master
CDAKit/health-data-standards/lib/models/insurance_provider.swift
mit
1
// // medication.swift // CDAKit // // Created by Eric Whitley on 12/2/15. // Copyright © 2015 Eric Whitley. All rights reserved. // import Foundation /** Insurance Provider */ public class CDAKInsuranceProvider: CDAKEntry { // MARK: CDA properties ///Payer (insurance provider) public var payer: CDAKOrganization? //, class_name: "CDAKOrganization" ///Insurance guarantor public var guarantors = [CDAKGuarantor]()//, class_name: "CDAKGuarantor" ///Insurance subscriber public var subscriber: CDAKPerson? //, class_name: "CDAKPerson" ///Type public var type: String? ///Member ID public var member_id: String? ///Relationship public var relationship : CDAKCodedEntries = CDAKCodedEntries() //, type: Hash ///Financial responsibility type public var financial_responsibility_type : CDAKCodedEntries = CDAKCodedEntries() //, type: Hash ///Name public var name: String? // MARK: Health-Data-Standards Functions ///Offset all dates by specified double override func shift_dates(date_diff: Double) { super.shift_dates(date_diff) for g in guarantors { g.shift_dates(date_diff) } } // MARK: Standard properties ///Debugging description override public var description: String { return super.description + ", name: \(name), type: \(type), member_id: \(member_id), relationship: \(relationship), financial_responsibility_type: \(financial_responsibility_type), financial_responsibility_type: \(financial_responsibility_type), payer: \(payer), guarantors: \(guarantors), subscriber: \(subscriber)" } } extension CDAKInsuranceProvider { // MARK: - JSON Generation ///Dictionary for JSON data override public var jsonDict: [String: AnyObject] { var dict = super.jsonDict if let payer = payer { dict["payer"] = payer.jsonDict } if guarantors.count > 0 { dict["guarantors"] = guarantors.map({$0.jsonDict}) } if let type = type { dict["type"] = type } if let member_id = member_id { dict["member_id"] = member_id } if relationship.count > 0 { dict["relationship"] = relationship.codes.map({$0.jsonDict}) } if financial_responsibility_type.count > 0 { dict["financial_responsibility_type"] = financial_responsibility_type.codes.map({$0.jsonDict}) } if let name = name { dict["name"] = name } return dict } }
46eee3782ef5f96d22d5eccc887f86e2
27.642857
320
0.671102
false
false
false
false
duliodenis/jukebox
refs/heads/master
jukebox/jukebox/Playlist.swift
mit
1
// // Playlist.swift // jukebox // // Created by Dulio Denis on 3/21/15. // Copyright (c) 2015 Dulio Denis. All rights reserved. // import Foundation import UIKit struct Playlist { var title : String? var description: String? var icon: UIImage? var largeIcon: UIImage? var videos: [String] = [] var urls: [String] = [] var backgroundColor: UIColor = UIColor.clearColor() init(index: Int) { let videoLibrary = VideoLibrary().library let playlistDictionary = videoLibrary[index] title = playlistDictionary["title"] as String! description = playlistDictionary["description"] as String! let iconName = playlistDictionary["icon"] as String! icon = UIImage(named: iconName) let largeIconName = playlistDictionary["largeIcon"] as String! largeIcon = UIImage(named: largeIconName) videos += playlistDictionary["videos"] as [String] urls += playlistDictionary["urls"] as [String] let colorDictionary = playlistDictionary["backgroundColor"] as [String: CGFloat] backgroundColor = rgbColorFromDictionary(colorDictionary) } func rgbColorFromDictionary(colorDictionary: [String: CGFloat]) -> UIColor { let red = colorDictionary["red"]! let green = colorDictionary["green"]! let blue = colorDictionary["blue"]! let alpha = colorDictionary["alpha"]! return UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: alpha) } }
54350eef8a13ece90f98447c95718f00
30.54
90
0.633883
false
false
false
false
zerovagner/iOS-Studies
refs/heads/master
RainyShinyCloudy/RainyShinyCloudy/Weather.swift
gpl-3.0
1
// // Weather.swift // RainyShinyCloudy // // Created by Vagner Oliveira on 5/15/17. // Copyright © 2017 Vagner Oliveira. All rights reserved. // import Foundation import Alamofire import CoreLocation class Weather { private(set) var cityName: String! private(set) var currentWeather: String! private var currentDate: String! private(set) var currentTemperature: String! private(set) var maxTemperature: String! private(set) var minTemperature: String! static let baseUrl = "http://api.openweathermap.org/data/2.5/" static let params = [ "lat":"\(lat)", "lon":"\(lon)", "appid":"42a1771a0b787bf12e734ada0cfc80cb" ] private static var lat = 0.0 private static var lon = 0.0 static let forecastUrl = baseUrl + "forecast/daily" var date: String! { get { if currentDate == "" { let df = DateFormatter() df.dateStyle = .long df.timeStyle = .none currentDate = df.string(from: Date()) } return currentDate } } init() { cityName = "" currentWeather = "" currentDate = "" currentTemperature = "" minTemperature = "" maxTemperature = "" } init(obj: [String:Any]) { if let temp = obj["temp"] as? [String:Any] { if let min = temp["min"] as? Double { minTemperature = "\(round(10 * (min - 273))/10)º" } if let max = temp["max"] as? Double { maxTemperature = "\(round(10 * (max - 273))/10)º" } } if let weather = obj["weather"] as? [[String:Any]] { if let main = weather[0]["main"] as? String { currentWeather = main.capitalized } } if let date = obj["dt"] as? Double { let convertedDate = Date(timeIntervalSince1970: date) let dateFormatter = DateFormatter() dateFormatter.dateStyle = .full dateFormatter.dateFormat = "EEEE" dateFormatter.timeStyle = .none let dateIndex = Calendar.current.component(.weekday, from: convertedDate) currentDate = dateFormatter.weekdaySymbols[dateIndex-1] } } func setUp (fromJSON dict: [String:Any]) { if let name = dict["name"] as? String { cityName = name.capitalized print(cityName) } if let weather = dict["weather"] as? [[String:Any]] { if let curWeather = weather[0]["main"] as? String { currentWeather = curWeather.capitalized print(currentWeather) } } if let main = dict["main"] as? [String:Any] { if let temp = main["temp"] as? Double { currentTemperature = "\(round(10 * (temp - 273))/10)º" print(currentTemperature) } } } func downloadCurrentWeatherData (completed: @escaping DownloadComplete) { let currentWeatherUrl = Weather.baseUrl + "weather" Alamofire.request(currentWeatherUrl, parameters: Weather.params).responseJSON { response in let result = response.result if let dict = result.value as? [String:Any] { self.setUp(fromJSON: dict) } completed() } } static func setCoordinates(fromLocation location: CLLocation) { lat = round(100 * location.coordinate.latitude)/100 lon = round(100 * location.coordinate.longitude)/100 print("lat: \(lat) lon: \(lon)") } }
a12d806b6fb075be16184cf3a6ad456e
25.787611
93
0.665676
false
false
false
false
Cunqi/CQPopupKit
refs/heads/master
CQPopupKit/PopupDialogue.swift
mit
1
// // PopupDialogue.swift // CQPopupKit // // Created by Cunqi.X on 8/13/16. // Copyright © 2016 Cunqi Xiao. All rights reserved. // import UIKit /// Popup dialogue delegate public protocol PopupDialogueDelegate: class { /** When confirm button tapped, call invokePositiveAction to send confirmed data - returns: confirmed data */ func prepareConfirmedData() -> AnyObject? } /// Popup view with navigation bar on the top, contains title, cancel button, confirm button open class PopupDialogue: Popup { // MARK: Public /// Navigation bar view open let navBar = UIView() /// Title label open let dialogueTitle = UILabel(frame: .zero) /// Cancel button open let cancel = UIButton(type: .system) /// Confirm button open let confirm = UIButton(type: .system) /// Dialogue appearance open var dialogueAppearance: PopupDialogueAppearance! /// PopupDialogueDelegate fileprivate weak var delegate: PopupDialogueDelegate? // MARK: Initializer /** Creates a popup dialogue - parameter title: Dialogue title text - parameter contentView: Custom content view - parameter positiveAction: Action when confirm button is tapped - parameter negativeAction: Action when cancel button is tapped - parameter cancelText: Cancel button text - parameter confirmText: Confirm button text - returns: Popup dialogue */ public init(title: String, contentView: UIView?, positiveAction: PopupAction?, negativeAction: PopupAction? = nil, cancelText: String = "Cancel", confirmText: String = "Choose") { dialogueAppearance = CQAppearance.appearance.dialogue super.init(contentView: contentView, positiveAction: positiveAction, negativeAction: negativeAction) if let delegate = self.contentView as? PopupDialogueDelegate { self.delegate = delegate } navBar.backgroundColor = dialogueAppearance.navBarBackgroundColor dialogueTitle.text = title dialogueTitle.font = dialogueAppearance.titleFont dialogueTitle.textColor = dialogueAppearance.titleColor dialogueTitle.textAlignment = .center dialogueTitle.numberOfLines = 1 cancel.setTitle(cancelText, for: UIControlState()) cancel.addTarget(self, action: #selector(tapToDismiss), for: .touchUpInside) confirm.setTitle(confirmText, for: UIControlState()) confirm.addTarget(self, action: #selector(tapToConfirm), for: .touchUpInside) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** Bind constraints to navigation bar and content view */ override func installContentView() { installNavBar() installContent() } /** When confirm button is tapped */ func tapToConfirm() { guard let _ = self.delegate else { self.tapToDismiss() return } let popupInfo = self.delegate!.prepareConfirmedData() invokePositiveAction(popupInfo) } fileprivate func installNavBar() { // Cancel button cancel.translatesAutoresizingMaskIntoConstraints = false navBar.addSubview(cancel) navBar.bindFrom("V:|[cancel]|", views: ["cancel": cancel]) navBar.bindWith(cancel, attribute: .leading) navBar.bindWith(cancel, attribute: .width, multiplier: 0.25) // Confirm button confirm.translatesAutoresizingMaskIntoConstraints = false navBar.addSubview(confirm) navBar.bindFrom("V:|[confirm]|", views: ["confirm": confirm]) navBar.bindWith(confirm, attribute: .trailing) navBar.bindWith(confirm, attribute: .width, multiplier: 0.25) // Title Label dialogueTitle.translatesAutoresizingMaskIntoConstraints = false navBar.addSubview(dialogueTitle) navBar.bindFrom("V:|[title]|", views: ["title": dialogueTitle]) navBar.bind(cancel, attribute: .trailing, to: dialogueTitle, toAttribute: .leading) navBar.bind(confirm, attribute: .leading, to: dialogueTitle, toAttribute: .trailing) // Bottom Separator let bottomSeparator = UIView(frame: .zero) bottomSeparator.backgroundColor = dialogueAppearance.separatorColor bottomSeparator.translatesAutoresizingMaskIntoConstraints = false navBar.addSubview(bottomSeparator) navBar.bindFrom("H:|[separator]|", views: ["separator": bottomSeparator]) navBar.bindWith(bottomSeparator, attribute: .bottom) navBar.bind(bottomSeparator, attribute: .height, to: nil, toAttribute: .notAnAttribute, constant: 1.0) navBar.translatesAutoresizingMaskIntoConstraints = false container.addSubview(navBar) container.bind(navBar, attribute: .height, to: nil, toAttribute: .notAnAttribute, constant: 44) container.bindFrom("H:|[nav]|", views: ["nav": navBar]) container.bindWith(navBar, attribute: .top) } func installContent() { if let content = contentView { content.translatesAutoresizingMaskIntoConstraints = false container.addSubview(content) container.bindFrom("H:|[content]|", views: ["content": content]) container.bindWith(content, attribute: .bottom) container.bind(navBar, attribute: .bottom, to: content, toAttribute: .top) } } }
1c05e2800e2e8dd31068b2cea567d270
32.96732
181
0.712719
false
false
false
false
coreyjv/Emby.ApiClient.Swift
refs/heads/master
Emby.ApiClient/StringHelpers.swift
mit
1
// // StringHelpers.swift // EmbyApiClient // import Foundation internal func splitToArray(stringToSplit: String?, delimiter: Character) -> [String] { if let toBeSplit = stringToSplit { return toBeSplit.characters.split(isSeparator: { $0 == delimiter }).map(String.init).filter({!$0.isEmpty}) } else { return [String]() } } extension String { func sha1() -> String { let data = self.dataUsingEncoding(NSUTF8StringEncoding)! var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0) CC_SHA1(data.bytes, CC_LONG(data.length), &digest) let hexBytes = digest.map { String(format: "%02hhx", $0) } return hexBytes.joinWithSeparator("") } func md5() -> String { let str = self.cStringUsingEncoding(NSUTF8StringEncoding) let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) CC_MD5(str!, strLen, result) let hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.destroy() return String( hash) } }
495653c9bd3997f6d16fda45b160e254
31.717949
114
0.632941
false
false
false
false
abunur/quran-ios
refs/heads/master
VFoundation/AppUpdater.swift
gpl-3.0
2
// // AppUpdater.swift // Quran // // Created by Mohamed Afifi on 5/2/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // extension PersistenceKeyBase { public static let appVersion = PersistenceKey<String?>(key: "appVersion", defaultValue: nil) } public struct AppUpdater { public typealias AppVersion = String public enum VersionUpdate { case sameVersion(version: AppVersion) case firstLaunch(version: AppVersion) case update(from: AppVersion, to: AppVersion) } public let persistence = UserDefaultsSimplePersistence(userDefaults: .standard) public init() { } public func updated() -> VersionUpdate { let current: String = cast(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")) let previous = persistence.valueForKey(.appVersion) // eventually we should update the app version defer { persistence.setValue(current, forKey: PersistenceKeyBase.appVersion) } if let previous = previous { if previous == current { return .sameVersion(version: current) } else { return .update(from: previous, to: current) } } else { return .firstLaunch(version: current) } } }
9b48b3947458ad89dd52ef1449b2bcb2
31.719298
106
0.669169
false
false
false
false
object-kazu/JabberwockProtoType
refs/heads/master
JabberWock/JabberWockTests/HTML_TEST/pTest.swift
mit
1
// // pTest.swift // JabberWock // // Created by 清水 一征 on 2016/12/18. // Copyright © 2016年 momiji-mac. All rights reserved. // import XCTest class pTest: XCTestCase { var dctype = DOCTYPE() var html = HTML() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func test_p() { let p = P() p.content = "test" let ans = p.press() XCTAssertEqual(ans, "<p>test</p>") /* answer <p>test</p> */ } // func test_p_with_css() { // let p = P() // p.content = "test" // // let css = CSS(name: "p") // css.color.value = "red" // p.style = css // XCTAssertEqual(p.styleStr(), "p {" + RET + "color: red;" + RET + "}") // // p.press() // // /* answer // <p>test</p> // */ // // } }
6639c84f5b674f929130613fbe836200
20.357143
111
0.470736
false
true
false
false
bitjammer/swift
refs/heads/master
test/SILGen/nested_types_referencing_nested_functions.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s do { func foo() { bar(2) } func bar<T>(_: T) { foo() } class Foo { // CHECK-LABEL: sil shared @_T0025nested_types_referencing_A10_functions3FooL_CACycfc : $@convention(method) (@owned Foo) -> @owned Foo { init() { foo() } // CHECK-LABEL: sil shared @_T0025nested_types_referencing_A10_functions3FooL_C3zimyyF : $@convention(method) (@guaranteed Foo) -> () func zim() { foo() } // CHECK-LABEL: sil shared @_T0025nested_types_referencing_A10_functions3FooL_C4zangyxlF : $@convention(method) <T> (@in T, @guaranteed Foo) -> () func zang<T>(_ x: T) { bar(x) } // CHECK-LABEL: sil shared @_T0025nested_types_referencing_A10_functions3FooL_CfD : $@convention(method) (@owned Foo) -> () deinit { foo() } } let x = Foo() x.zim() x.zang(1) _ = Foo.zim _ = Foo.zang as (Foo) -> (Int) -> () _ = x.zim _ = x.zang as (Int) -> () }
7f84d9fa33a2ea434f6c14bcf67a2a9b
28.636364
150
0.579755
false
false
false
false
Sadmansamee/quran-ios
refs/heads/master
Quran/NetworkError.swift
mit
1
// // NetworkError.swift // SwinjectMVVMExample // // Created by Yoichi Tagaya on 8/22/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // import Foundation public enum NetworkError: Error, CustomStringConvertible { /// Unknown or not supported error. case unknown /// Not connected to the internet. case notConnectedToInternet /// International data roaming turned off. case internationalRoamingOff /// Connection is lost. case connectionLost /// Cannot reach the server. case serverNotReachable internal init(error: Error) { if let error = error as? URLError { switch error.code { case .timedOut, .cannotFindHost, .cannotConnectToHost: self = .serverNotReachable case .networkConnectionLost: self = .connectionLost case .dnsLookupFailed: self = .serverNotReachable case .notConnectedToInternet: self = .notConnectedToInternet case .internationalRoamingOff: self = .internationalRoamingOff default: self = .unknown } } else { self = .unknown } } public var description: String { let text: String switch self { case .unknown: text = NSLocalizedString("NetworkError_Unknown", comment: "Error description") case .notConnectedToInternet: text = NSLocalizedString("NetworkError_NotConnectedToInternet", comment: "Error description") case .internationalRoamingOff: text = NSLocalizedString("NetworkError_InternationalRoamingOff", comment: "Error description") case .serverNotReachable: text = NSLocalizedString("NetworkError_ServerNotReachable", comment: "Error description") case .connectionLost: text = NSLocalizedString("NetworkError_ConnectionLost", comment: "Error description") } return text } }
32357711db99aae9d05a09bbd415d7b6
30.9375
106
0.627691
false
false
false
false
EdwaRen/Recycle_Can_iOS
refs/heads/final
GooglePlacePicker/GooglePlacePickerDemos/ViewControllers/PickAPlace/PickAPlaceViewController.swift
apache-2.0
9
/* * Copyright 2016 Google Inc. All rights reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import UIKit import GooglePlacePicker /// A view controller which displays a UI for opening the Place Picker. Once a place is selected /// it navigates to the place details screen for the selected location. class PickAPlaceViewController: UIViewController { private var placePicker: GMSPlacePicker? @IBOutlet private weak var pickAPlaceButton: UIButton! @IBOutlet weak var buildNumberLabel: UILabel! var mapViewController: BackgroundMapViewController? init() { super.init(nibName: String(describing: type(of: self)), bundle: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // This is the size we would prefer to be. self.preferredContentSize = CGSize(width: 330, height: 600) // Configure our view. view.backgroundColor = Colors.blue1 view.clipsToBounds = true // Set the build number. buildNumberLabel.text = "Places API Build: \(GMSPlacesClient.sdkVersion())" } @IBAction func buttonTapped() { // Create a place picker. let config = GMSPlacePickerConfig(viewport: nil) let placePicker = GMSPlacePicker(config: config) // Present it fullscreen. placePicker.pickPlace { (place, error) in // Handle the selection if it was successful. if let place = place { // Create the next view controller we are going to display and present it. let nextScreen = PlaceDetailViewController(place: place) self.splitPaneViewController?.push(viewController: nextScreen, animated: false) self.mapViewController?.coordinate = place.coordinate } else if error != nil { // In your own app you should handle this better, but for the demo we are just going to log // a message. NSLog("An error occurred while picking a place: \(error)") } else { NSLog("Looks like the place picker was canceled by the user") } // Release the reference to the place picker, we don't need it anymore and it can be freed. self.placePicker = nil } // Store a reference to the place picker until it's finished picking. As specified in the docs // we have to hold onto it otherwise it will be deallocated before it can return us a result. self.placePicker = placePicker } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
15129e5361bbbfc762d644bc35ca9f26
35.493976
99
0.711456
false
true
false
false
LYM-mg/DemoTest
refs/heads/master
Example/Pods/HandyJSON/HandyJSON/Configuration.swift
apache-2.0
24
/* * Copyright 1999-2101 Alibaba Group. * * 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. */ // // Configuration.swift // HandyJSON // // Created by zhouzhuo on 08/01/2017. // public struct DeserializeOptions: OptionSet { public let rawValue: Int public static let caseInsensitive = DeserializeOptions(rawValue: 1 << 0) public static let defaultOptions: DeserializeOptions = [] public init(rawValue: Int) { self.rawValue = rawValue } } public enum DebugMode: Int { case verbose = 0 case debug = 1 case error = 2 case none = 3 } public struct HandyJSONConfiguration { private static var _mode = DebugMode.error public static var debugMode: DebugMode { get { return _mode } set { _mode = newValue } } public static var deserializeOptions: DeserializeOptions = .defaultOptions }
1add0eca475e1e48a19354649db78e9c
24.267857
78
0.679152
false
false
false
false
iosyaowei/Weibo
refs/heads/master
WeiBo/Classes/Utils(工具)/YWRefreshControl/YWMTRefreshView.swift
mit
1
// // YWMTRefreshView.swift // refreshDemo // // Created by 姚巍 on 16/10/5. // Copyright © 2016年 Guangxi City Network Technology Co.,Ltd. All rights reserved. // import UIKit class YWMTRefreshView: YWRefreshView { @IBOutlet weak var buildIV: UIImageView! @IBOutlet weak var earthIV: UIImageView! @IBOutlet weak var kangarooIV: UIImageView! override var parentViewHeight: CGFloat { didSet { if parentViewHeight < 25 { return } var scale :CGFloat if parentViewHeight > 122 { scale = 1 }else { scale = 1-((122 - parentViewHeight)/(122 - 25)) } kangarooIV.transform = CGAffineTransform(scaleX: scale, y: scale) } } override func awakeFromNib() { //1.房子 let bImg1 = #imageLiteral(resourceName: "icon_building_loading_1") let bImg2 = #imageLiteral(resourceName: "icon_building_loading_2") buildIV.image = UIImage.animatedImage(with: [bImg1,bImg2], duration: 0.5) //2.地球 let anim = CABasicAnimation(keyPath: "transform.rotation") anim.toValue = -2 * M_PI anim.repeatCount = MAXFLOAT anim.duration = 3 anim.isRemovedOnCompletion = false earthIV.layer.add(anim, forKey: nil) //袋鼠 let KImg1 = #imageLiteral(resourceName: "icon_small_kangaroo_loading_1") let Kimg2 = #imageLiteral(resourceName: "icon_small_kangaroo_loading_2") kangarooIV.image = UIImage.animatedImage(with: [KImg1,Kimg2], duration: 0.4) kangarooIV.transform = CGAffineTransform(scaleX: 0.2, y: 0.2) //设置锚点 kangarooIV.layer.anchorPoint = CGPoint(x: 0.5, y: 1) //设置center kangarooIV.center = CGPoint(x: self.bounds.width * 0.5, y: self.bounds.height - 25) } }
54b5590e70e8c180c54817048be1e61a
28.907692
91
0.582305
false
false
false
false
RickiG/dynamicCellHeight
refs/heads/master
AutolayoutCellPoC/RandomNumbers.swift
mit
1
// // RandomNumbers.swift // OfficeBacon // // Created by Ricki Gregersen on 17/11/14. // Copyright (c) 2014 youandthegang.com. All rights reserved. // https://gist.github.com/jstn/f9d5437316879c9c448a import Darwin public func arc4random <T: IntegerLiteralConvertible> (type: T.Type) -> T { var r: T = 0 arc4random_buf(&r, UInt(sizeof(T))) return r } public extension UInt { public static func random(lower: UInt = min, upper: UInt = max) -> UInt { switch (__WORDSIZE) { case 32: return UInt(UInt32.random(lower: UInt32(lower), upper: UInt32(upper))) case 64: return UInt(UInt64.random(lower: UInt64(lower), upper: UInt64(upper))) default: return lower } } } public extension Int { public static func random(lower: Int = min, upper: Int = max) -> Int { switch (__WORDSIZE) { case 32: return Int(Int32.random(lower: Int32(lower), upper: Int32(upper))) case 64: return Int(Int64.random(lower: Int64(lower), upper: Int64(upper))) default: return lower } } } public extension UInt32 { public static func random(lower: UInt32 = min, upper: UInt32 = max) -> UInt32 { return arc4random_uniform(upper - lower) + lower } } public extension Int32 { public static func random(lower: Int32 = min, upper: Int32 = max) -> Int32 { let r = arc4random_uniform(UInt32(Int64(upper) - Int64(lower))) return Int32(Int64(r) + Int64(lower)) } } public extension UInt64 { public static func random(lower: UInt64 = min, upper: UInt64 = max) -> UInt64 { var m: UInt64 let u = upper - lower var r = arc4random(UInt64) if u > UInt64(Int64.max) { m = 1 + ~u } else { m = ((max - (u * 2)) + 1) % u } while r < m { r = arc4random(UInt64) } return (r % u) + lower } } public extension Int64 { public static func random(lower: Int64 = min, upper: Int64 = max) -> Int64 { let (s, overflow) = Int64.subtractWithOverflow(upper, lower) let u = overflow ? UInt64.max - UInt64(~s) : UInt64(s) let r = UInt64.random(upper: u) if r > UInt64(Int64.max) { return Int64(r - (UInt64(~lower) + 1)) } else { return Int64(r) + lower } } } public extension Float { public static func random(lower: Float = 0.0, upper: Float = 1.0) -> Float { let r = Float(arc4random(UInt32)) / Float(UInt32.max) return (r * (upper - lower)) + lower } } public extension Double { public static func random(lower: Double = 0.0, upper: Double = 1.0) -> Double { let r = Double(arc4random(UInt64)) / Double(UInt64.max) return (r * (upper - lower)) + lower } }
5cf39f7aac47d20478aa9a4d8bb64448
28.552083
87
0.58019
false
false
false
false
ReactorKit/ReactorKit
refs/heads/master
Sources/ReactorKit/ActionSubject.swift
mit
1
// // ActionSubject.swift // ReactorKit // // Created by Suyeol Jeon on 14/05/2017. // // import class Foundation.NSLock.NSRecursiveLock import RxSwift /// A special subject for Reactor's Action. It only emits `.next` event. public final class ActionSubject<Element>: ObservableType, ObserverType, SubjectType { typealias Key = UInt var lock = NSRecursiveLock() var nextKey: Key = 0 var observers: [Key: (Event<Element>) -> ()] = [:] #if TRACE_RESOURCES init() { _ = Resources.incrementTotal() } #endif #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() } #endif public func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.Element == Element { self.lock.lock() let key = self.nextKey self.nextKey += 1 self.observers[key] = observer.on self.lock.unlock() return Disposables.create { [weak self] in self?.lock.lock() self?.observers.removeValue(forKey: key) self?.lock.unlock() } } public func on(_ event: Event<Element>) { self.lock.lock() if case .next = event { self.observers.values.forEach { $0(event) } } self.lock.unlock() } }
874f476342702d8018e254c44a36b9e3
20.436364
98
0.644614
false
false
false
false
KrishMunot/swift
refs/heads/master
test/SILGen/builtins.swift
apache-2.0
6
// RUN: %target-swift-frontend -emit-silgen -parse-stdlib %s -disable-objc-attr-requires-foundation-module | FileCheck %s // RUN: %target-swift-frontend -emit-sil -Onone -parse-stdlib %s -disable-objc-attr-requires-foundation-module | FileCheck -check-prefix=CANONICAL %s import Swift protocol ClassProto : class { } struct Pointer { var value: Builtin.RawPointer } // CHECK-LABEL: sil hidden @_TF8builtins3foo func foo(_ x: Builtin.Int1, y: Builtin.Int1) -> Builtin.Int1 { // CHECK: builtin "cmp_eq_Int1" return Builtin.cmp_eq_Int1(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins8load_pod func load_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [[ADDR]] // CHECK: return [[VAL]] return Builtin.load(x) } // CHECK-LABEL: sil hidden @_TF8builtins8load_obj func load_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [[ADDR]] // CHECK: retain [[VAL]] // CHECK: return [[VAL]] return Builtin.load(x) } // CHECK-LABEL: sil hidden @_TF8builtins8load_gen func load_gen<T>(_ x: Builtin.RawPointer) -> T { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*T // CHECK: copy_addr [[ADDR]] to [initialization] {{%.*}} return Builtin.load(x) } // CHECK-LABEL: sil hidden @_TF8builtins8move_pod func move_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [[ADDR]] // CHECK: return [[VAL]] return Builtin.take(x) } // CHECK-LABEL: sil hidden @_TF8builtins8move_obj func move_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [[ADDR]] // CHECK-NOT: retain [[VAL]] // CHECK: return [[VAL]] return Builtin.take(x) } // CHECK-LABEL: sil hidden @_TF8builtins8move_gen func move_gen<T>(_ x: Builtin.RawPointer) -> T { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*T // CHECK: copy_addr [take] [[ADDR]] to [initialization] {{%.*}} return Builtin.take(x) } // CHECK-LABEL: sil hidden @_TF8builtins11destroy_pod func destroy_pod(_ x: Builtin.RawPointer) { var x = x // CHECK: [[XBOX:%[0-9]+]] = alloc_box // CHECK-NOT: pointer_to_address // CHECK-NOT: destroy_addr // CHECK-NOT: release // CHECK: release [[XBOX]] : $@box // CHECK-NOT: release return Builtin.destroy(Builtin.Int64, x) // CHECK: return } // CHECK-LABEL: sil hidden @_TF8builtins11destroy_obj func destroy_obj(_ x: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject // CHECK: destroy_addr [[ADDR]] return Builtin.destroy(Builtin.NativeObject, x) } // CHECK-LABEL: sil hidden @_TF8builtins11destroy_gen func destroy_gen<T>(_ x: Builtin.RawPointer, _: T) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*T // CHECK: destroy_addr [[ADDR]] return Builtin.destroy(T.self, x) } // CHECK-LABEL: sil hidden @_TF8builtins10assign_pod func assign_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) { var x = x var y = y // CHECK: alloc_box // CHECK: alloc_box // CHECK-NOT: alloc_box // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64 // CHECK-NOT: load [[ADDR]] // CHECK: assign {{%.*}} to [[ADDR]] // CHECK: release // CHECK: release // CHECK-NOT: release Builtin.assign(x, y) // CHECK: return } // CHECK-LABEL: sil hidden @_TF8builtins10assign_obj func assign_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject // CHECK: assign {{%.*}} to [[ADDR]] // CHECK: release Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins12assign_tuple func assign_tuple(_ x: (Builtin.Int64, Builtin.NativeObject), y: Builtin.RawPointer) { var x = x var y = y // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*(Builtin.Int64, Builtin.NativeObject) // CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]] // CHECK: assign {{%.*}} to [[T0]] // CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]] // CHECK: assign {{%.*}} to [[T0]] // CHECK: release Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins10assign_gen func assign_gen<T>(_ x: T, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*T // CHECK: copy_addr [take] {{%.*}} to [[ADDR]] : Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins8init_pod func init_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64 // CHECK-NOT: load [[ADDR]] // CHECK: store {{%.*}} to [[ADDR]] // CHECK-NOT: release [[ADDR]] Builtin.initialize(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins8init_obj func init_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject // CHECK-NOT: load [[ADDR]] // CHECK: store [[SRC:%.*]] to [[ADDR]] // CHECK-NOT: release [[SRC]] Builtin.initialize(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins8init_gen func init_gen<T>(_ x: T, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*T // CHECK: copy_addr [take] {{%.*}} to [initialization] [[ADDR]] Builtin.initialize(x, y) } class C {} class D {} // CHECK-LABEL: sil hidden @_TF8builtins22class_to_native_object func class_to_native_object(_ c:C) -> Builtin.NativeObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.NativeObject // CHECK-NOT: release [[C]] // CHECK-NOT: release [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToNativeObject(c) } // CHECK-LABEL: sil hidden @_TF8builtins23class_to_unknown_object func class_to_unknown_object(_ c:C) -> Builtin.UnknownObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.UnknownObject // CHECK-NOT: release [[C]] // CHECK-NOT: release [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToUnknownObject(c) } // CHECK-LABEL: sil hidden @_TF8builtins32class_archetype_to_native_object func class_archetype_to_native_object<T : C>(_ t: T) -> Builtin.NativeObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.NativeObject // CHECK-NOT: release [[C]] // CHECK-NOT: release [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToNativeObject(t) } // CHECK-LABEL: sil hidden @_TF8builtins33class_archetype_to_unknown_object func class_archetype_to_unknown_object<T : C>(_ t: T) -> Builtin.UnknownObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.UnknownObject // CHECK-NOT: release [[C]] // CHECK-NOT: release [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToUnknownObject(t) } // CHECK-LABEL: sil hidden @_TF8builtins34class_existential_to_native_object func class_existential_to_native_object(_ t:ClassProto) -> Builtin.NativeObject { // CHECK: [[REF:%[0-9]+]] = open_existential_ref [[T:%[0-9]+]] : $ClassProto // CHECK: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.NativeObject return Builtin.castToNativeObject(t) } // CHECK-LABEL: sil hidden @_TF8builtins35class_existential_to_unknown_object func class_existential_to_unknown_object(_ t:ClassProto) -> Builtin.UnknownObject { // CHECK: [[REF:%[0-9]+]] = open_existential_ref [[T:%[0-9]+]] : $ClassProto // CHECK: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.UnknownObject return Builtin.castToUnknownObject(t) } // CHECK-LABEL: sil hidden @_TF8builtins24class_from_native_object func class_from_native_object(_ p: Builtin.NativeObject) -> C { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C // CHECK-NOT: release [[C]] // CHECK-NOT: release [[OBJ]] // CHECK: return [[C]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins25class_from_unknown_object func class_from_unknown_object(_ p: Builtin.UnknownObject) -> C { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C // CHECK-NOT: release [[C]] // CHECK-NOT: release [[OBJ]] // CHECK: return [[C]] return Builtin.castFromUnknownObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins34class_archetype_from_native_object func class_archetype_from_native_object<T : C>(_ p: Builtin.NativeObject) -> T { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $T // CHECK-NOT: release [[C]] // CHECK-NOT: release [[OBJ]] // CHECK: return [[C]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins35class_archetype_from_unknown_object func class_archetype_from_unknown_object<T : C>(_ p: Builtin.UnknownObject) -> T { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.UnknownObject to $T // CHECK-NOT: release [[C]] // CHECK-NOT: release [[OBJ]] // CHECK: return [[C]] return Builtin.castFromUnknownObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins41objc_class_existential_from_native_object func objc_class_existential_from_native_object(_ p: Builtin.NativeObject) -> AnyObject { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $AnyObject // CHECK-NOT: release [[C]] // CHECK-NOT: release [[OBJ]] // CHECK: return [[C]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins42objc_class_existential_from_unknown_object func objc_class_existential_from_unknown_object(_ p: Builtin.UnknownObject) -> AnyObject { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.UnknownObject to $AnyObject // CHECK-NOT: release [[C]] // CHECK-NOT: release [[OBJ]] // CHECK: return [[C]] return Builtin.castFromUnknownObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins20class_to_raw_pointer func class_to_raw_pointer(_ c: C) -> Builtin.RawPointer { // CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer // CHECK: return [[RAW]] return Builtin.bridgeToRawPointer(c) } func class_archetype_to_raw_pointer<T : C>(_ t: T) -> Builtin.RawPointer { return Builtin.bridgeToRawPointer(t) } protocol CP: class {} func existential_to_raw_pointer(_ p: CP) -> Builtin.RawPointer { return Builtin.bridgeToRawPointer(p) } // CHECK-LABEL: sil hidden @_TF8builtins18obj_to_raw_pointer func obj_to_raw_pointer(_ c: Builtin.NativeObject) -> Builtin.RawPointer { // CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer // CHECK: return [[RAW]] return Builtin.bridgeToRawPointer(c) } // CHECK-LABEL: sil hidden @_TF8builtins22class_from_raw_pointer func class_from_raw_pointer(_ p: Builtin.RawPointer) -> C { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $C // CHECK: retain [[C]] // CHECK: return [[C]] return Builtin.bridgeFromRawPointer(p) } func class_archetype_from_raw_pointer<T : C>(_ p: Builtin.RawPointer) -> T { return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_TF8builtins20obj_from_raw_pointer func obj_from_raw_pointer(_ p: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.NativeObject // CHECK: retain [[C]] // CHECK: return [[C]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_TF8builtins28unknown_obj_from_raw_pointer func unknown_obj_from_raw_pointer(_ p: Builtin.RawPointer) -> Builtin.UnknownObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.UnknownObject // CHECK: retain [[C]] // CHECK: return [[C]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_TF8builtins28existential_from_raw_pointer func existential_from_raw_pointer(_ p: Builtin.RawPointer) -> AnyObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $AnyObject // CHECK: retain [[C]] // CHECK: return [[C]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_TF8builtins5gep64 func gep64(_ p: Builtin.RawPointer, i: Builtin.Int64) -> Builtin.RawPointer { // CHECK: [[GEP:%.*]] = index_raw_pointer // CHECK: return [[GEP]] return Builtin.gep_Int64(p, i) } // CHECK-LABEL: sil hidden @_TF8builtins5gep32 func gep32(_ p: Builtin.RawPointer, i: Builtin.Int32) -> Builtin.RawPointer { // CHECK: [[GEP:%.*]] = index_raw_pointer // CHECK: return [[GEP]] return Builtin.gep_Int32(p, i) } // CHECK-LABEL: sil hidden @_TF8builtins8condfail func condfail(_ i: Builtin.Int1) { Builtin.condfail(i) // CHECK: cond_fail {{%.*}} : $Builtin.Int1 } struct S {} @objc class O {} @objc protocol OP1 {} @objc protocol OP2 {} protocol P {} // CHECK-LABEL: sil hidden @_TF8builtins10canBeClass func canBeClass<T>(_: T) { // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(O.self) // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(OP1.self) // -- FIXME: protocol<...> doesn't parse as a value typealias ObjCCompo = protocol<OP1, OP2> // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(ObjCCompo.self) // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(S.self) // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(C.self) // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(P.self) typealias MixedCompo = protocol<OP1, P> // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(MixedCompo.self) // CHECK: builtin "canBeClass"<T> Builtin.canBeClass(T.self) } // FIXME: "T.Type.self" does not parse as an expression // CHECK-LABEL: sil hidden @_TF8builtins18canBeClassMetatype func canBeClassMetatype<T>(_: T) { // CHECK: integer_literal $Builtin.Int8, 0 typealias OT = O.Type Builtin.canBeClass(OT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias OP1T = OP1.Type Builtin.canBeClass(OP1T.self) // -- FIXME: protocol<...> doesn't parse as a value typealias ObjCCompoT = protocol<OP1, OP2>.Type // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(ObjCCompoT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias ST = S.Type Builtin.canBeClass(ST.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias CT = C.Type Builtin.canBeClass(CT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias PT = P.Type Builtin.canBeClass(PT.self) typealias MixedCompoT = protocol<OP1, P>.Type // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(MixedCompoT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias TT = T.Type Builtin.canBeClass(TT.self) } // CHECK-LABEL: sil hidden @_TF8builtins11fixLifetime func fixLifetime(_ c: C) { // CHECK: fix_lifetime %0 : $C Builtin.fixLifetime(c) } // CHECK-LABEL: sil hidden @_TF8builtins20assert_configuration func assert_configuration() -> Builtin.Int32 { return Builtin.assert_configuration() // CHECK: [[APPLY:%.*]] = builtin "assert_configuration"() : $Builtin.Int32 // CHECK: return [[APPLY]] : $Builtin.Int32 } // CHECK-LABEL: sil hidden @_TF8builtins17assumeNonNegativeFBwBw func assumeNonNegative(_ x: Builtin.Word) -> Builtin.Word { return Builtin.assumeNonNegative_Word(x) // CHECK: [[APPLY:%.*]] = builtin "assumeNonNegative_Word"(%0 : $Builtin.Word) : $Builtin.Word // CHECK: return [[APPLY]] : $Builtin.Word } // CHECK-LABEL: sil hidden @_TF8builtins11autorelease // CHECK: autorelease_value %0 func autorelease(_ o: O) { Builtin.autorelease(o) } // The 'unreachable' builtin is emitted verbatim by SILGen and eliminated during // diagnostics. // CHECK-LABEL: sil hidden @_TF8builtins11unreachable // CHECK: builtin "unreachable"() // CHECK: return // CANONICAL-LABEL: sil hidden @_TF8builtins11unreachableFT_T_ : $@convention(thin) @noreturn () -> () { // CANONICAL-NOT: builtin "unreachable" // CANONICAL-NOT: return // CANONICAL: unreachable @noreturn func unreachable() { Builtin.unreachable() } // CHECK-LABEL: sil hidden @_TF8builtins15reinterpretCastFTCS_1C1xBw_TBwCS_1DGSqS0__S0__ : $@convention(thin) (@owned C, Builtin.Word) -> (Builtin.Word, @owned D, @owned Optional<C>, @owned C) // CHECK: bb0(%0 : $C, %1 : $Builtin.Word): // CHECK-NEXT: debug_value // CHECK-NEXT: debug_value // CHECK-NEXT: strong_retain %0 : $C // CHECK-NEXT: unchecked_trivial_bit_cast %0 : $C to $Builtin.Word // CHECK-NEXT: unchecked_ref_cast %0 : $C to $D // CHECK-NEXT: unchecked_ref_cast %0 : $C to $Optional<C> // CHECK-NEXT: unchecked_bitwise_cast %1 : $Builtin.Word to $C // CHECK-NEXT: strong_retain %{{.*}} : $C // CHECK-NOT: strong_retain // CHECK-NOT: strong_release // CHECK-NOT: release_value // CHECK: return func reinterpretCast(_ c: C, x: Builtin.Word) -> (Builtin.Word, D, C?, C) { return (Builtin.reinterpretCast(c) as Builtin.Word, Builtin.reinterpretCast(c) as D, Builtin.reinterpretCast(c) as C?, Builtin.reinterpretCast(x) as C) } // CHECK-LABEL: sil hidden @_TF8builtins19reinterpretAddrOnly func reinterpretAddrOnly<T, U>(_ t: T) -> U { // CHECK: unchecked_addr_cast {{%.*}} : $*T to $*U return Builtin.reinterpretCast(t) } // CHECK-LABEL: sil hidden @_TF8builtins28reinterpretAddrOnlyToTrivial func reinterpretAddrOnlyToTrivial<T>(_ t: T) -> Int { // CHECK: [[ADDR:%.*]] = unchecked_addr_cast [[INPUT:%.*]] : $*T to $*Int // CHECK: [[VALUE:%.*]] = load [[ADDR]] // CHECK: destroy_addr [[INPUT]] return Builtin.reinterpretCast(t) } // CHECK-LABEL: sil hidden @_TF8builtins27reinterpretAddrOnlyLoadable func reinterpretAddrOnlyLoadable<T>(_ a: Int, _ b: T) -> (T, Int) { // CHECK: [[BUF:%.*]] = alloc_stack $Int // CHECK: store {{%.*}} to [[BUF]] // CHECK: [[RES1:%.*]] = unchecked_addr_cast [[BUF]] : $*Int to $*T // CHECK: copy_addr [[RES1]] to [initialization] return (Builtin.reinterpretCast(a) as T, // CHECK: [[RES:%.*]] = unchecked_addr_cast {{%.*}} : $*T to $*Int // CHECK: load [[RES]] Builtin.reinterpretCast(b) as Int) } // CHECK-LABEL: sil hidden @_TF8builtins18castToBridgeObject // CHECK: [[BO:%.*]] = ref_to_bridge_object {{%.*}} : $C, {{%.*}} : $Builtin.Word // CHECK: return [[BO]] func castToBridgeObject(_ c: C, _ w: Builtin.Word) -> Builtin.BridgeObject { return Builtin.castToBridgeObject(c, w) } // CHECK-LABEL: sil hidden @_TF8builtins23castRefFromBridgeObject // CHECK: bridge_object_to_ref [[BO:%.*]] : $Builtin.BridgeObject to $C func castRefFromBridgeObject(_ bo: Builtin.BridgeObject) -> C { return Builtin.castReferenceFromBridgeObject(bo) } // CHECK-LABEL: sil hidden @_TF8builtins30castBitPatternFromBridgeObject // CHECK: bridge_object_to_word [[BO:%.*]] : $Builtin.BridgeObject to $Builtin.Word // CHECK: release [[BO]] func castBitPatternFromBridgeObject(_ bo: Builtin.BridgeObject) -> Builtin.Word { return Builtin.castBitPatternFromBridgeObject(bo) } // CHECK-LABEL: sil hidden @_TF8builtins8pinUnpin // CHECK: bb0(%0 : $Builtin.NativeObject): // CHECK-NEXT: debug_value func pinUnpin(_ object : Builtin.NativeObject) { // CHECK-NEXT: strong_retain %0 : $Builtin.NativeObject // CHECK-NEXT: [[HANDLE:%.*]] = strong_pin %0 : $Builtin.NativeObject // CHECK-NEXT: debug_value // CHECK-NEXT: strong_release %0 : $Builtin.NativeObject let handle : Builtin.NativeObject? = Builtin.tryPin(object) // CHECK-NEXT: retain_value [[HANDLE]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: strong_unpin [[HANDLE]] : $Optional<Builtin.NativeObject> Builtin.unpin(handle) // CHECK-NEXT: tuple () // CHECK-NEXT: release_value [[HANDLE]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: strong_release %0 : $Builtin.NativeObject // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return [[T0]] : $() } // ---------------------------------------------------------------------------- // isUnique variants // ---------------------------------------------------------------------------- // NativeObject // CHECK-LABEL: sil hidden @_TF8builtins8isUnique // CHECK: bb0(%0 : $*Optional<Builtin.NativeObject>): // CHECK-NEXT: [[BOX:%.*]] = alloc_box $Optional<Builtin.NativeObject> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: copy_addr %0 to [initialization] [[PB]] : $*Optional<Builtin.NativeObject> // CHECK: [[BUILTIN:%.*]] = is_unique [[PB]] : $*Optional<Builtin.NativeObject> // CHECK: copy_addr [[PB]] to %0 : $*Optional<Builtin.NativeObject> // CHECK-NEXT: strong_release [[BOX]] : $@box Optional<Builtin.NativeObject> // CHECK-NEXT: return func isUnique(_ ref: inout Builtin.NativeObject?) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // NativeObject nonNull // CHECK-LABEL: sil hidden @_TF8builtins8isUnique // CHECK: bb0(%0 : $*Builtin.NativeObject): // CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.NativeObject // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK: copy_addr %0 to [initialization] [[PB]] : $*Builtin.NativeObject // CHECK: [[BUILTIN:%.*]] = is_unique [[PB]] : $*Builtin.NativeObject // CHECK: copy_addr [[PB]] to %0 : $*Builtin.NativeObject // CHECK-NEXT: strong_release [[BOX]] : $@box Builtin.NativeObject // CHECK-NEXT: return func isUnique(_ ref: inout Builtin.NativeObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // NativeObject pinned // CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned // CHECK: bb0(%0 : $*Optional<Builtin.NativeObject>): // CHECK-NEXT: [[BOX:%.*]] = alloc_box $Optional<Builtin.NativeObject> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK: copy_addr %0 to [initialization] [[PB]] : $*Optional<Builtin.NativeObject> // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[PB]] : $*Optional<Builtin.NativeObject> // CHECK: copy_addr [[PB]] to %0 : $*Optional<Builtin.NativeObject> // CHECK-NEXT: strong_release [[BOX]] : $@box Optional<Builtin.NativeObject> // CHECK-NEXT: return func isUniqueOrPinned(_ ref: inout Builtin.NativeObject?) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // NativeObject pinned nonNull // CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned // CHECK: bb0(%0 : $*Builtin.NativeObject): // CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.NativeObject // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK: copy_addr %0 to [initialization] [[PB]] : $*Builtin.NativeObject // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[PB]] : $*Builtin.NativeObject // CHECK: copy_addr [[PB]] to %0 : $*Builtin.NativeObject // CHECK-NEXT: strong_release [[BOX]] : $@box Builtin.NativeObject // CHECK-NEXT: return func isUniqueOrPinned(_ ref: inout Builtin.NativeObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // UnknownObject (ObjC) // CHECK-LABEL: sil hidden @_TF8builtins8isUnique // CHECK: bb0(%0 : $*Optional<Builtin.UnknownObject>): // CHECK-NEXT: [[BOX:%.*]] = alloc_box $Optional<Builtin.UnknownObject> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK: copy_addr %0 to [initialization] [[PB]] : $*Optional<Builtin.UnknownObject> // CHECK: [[BUILTIN:%.*]] = is_unique [[PB]] : $*Optional<Builtin.UnknownObject> // CHECK: copy_addr [[PB]] to %0 : $*Optional<Builtin.UnknownObject> // CHECK-NEXT: strong_release [[BOX]] : $@box Optional<Builtin.UnknownObject> // CHECK-NEXT: return func isUnique(_ ref: inout Builtin.UnknownObject?) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // UnknownObject (ObjC) nonNull // CHECK-LABEL: sil hidden @_TF8builtins8isUnique // CHECK: bb0(%0 : $*Builtin.UnknownObject): // CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.UnknownObject // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK: copy_addr %0 to [initialization] [[PB]] : $*Builtin.UnknownObject // CHECK: [[BUILTIN:%.*]] = is_unique [[PB]] : $*Builtin.UnknownObject // CHECK: copy_addr [[PB]] to %0 : $*Builtin.UnknownObject // CHECK-NEXT: strong_release [[BOX]] : $@box Builtin.UnknownObject // CHECK-NEXT: return func isUnique(_ ref: inout Builtin.UnknownObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // UnknownObject (ObjC) pinned nonNull // CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned // CHECK: bb0(%0 : $*Builtin.UnknownObject): // CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.UnknownObject // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK: copy_addr %0 to [initialization] [[PB]] : $*Builtin.UnknownObject // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[PB]] : $*Builtin.UnknownObject // CHECK: copy_addr [[PB]] to %0 : $*Builtin.UnknownObject // CHECK-NEXT: strong_release [[BOX]] : $@box Builtin.UnknownObject // CHECK-NEXT: return func isUniqueOrPinned(_ ref: inout Builtin.UnknownObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // BridgeObject nonNull // CHECK-LABEL: sil hidden @_TF8builtins8isUnique // CHECK: bb0(%0 : $*Builtin.BridgeObject): // CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.BridgeObject // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK: copy_addr %0 to [initialization] [[PB]] : $*Builtin.BridgeObject // CHECK: [[BUILTIN:%.*]] = is_unique [[PB]] : $*Builtin.BridgeObject // CHECK: copy_addr [[PB]] to %0 : $*Builtin.BridgeObject // CHECK-NEXT: strong_release [[BOX]] : $@box Builtin.BridgeObject // CHECK-NEXT: return func isUnique(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // BridgeObject pinned nonNull // CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned // CHECK: bb0(%0 : $*Builtin.BridgeObject): // CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.BridgeObject // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK: copy_addr %0 to [initialization] [[PB]] : $*Builtin.BridgeObject // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[PB]] : $*Builtin.BridgeObject // CHECK: copy_addr [[PB]] to %0 : $*Builtin.BridgeObject // CHECK-NEXT: strong_release [[BOX]] : $@box Builtin.BridgeObject // CHECK-NEXT: return func isUniqueOrPinned(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // BridgeObject nonNull native // CHECK-LABEL: sil hidden @_TF8builtins15isUnique_native // CHECK: bb0(%0 : $*Builtin.BridgeObject): // CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.BridgeObject // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK: copy_addr %0 to [initialization] [[PB]] : $*Builtin.BridgeObject // CHECK: [[CAST:%.*]] = unchecked_addr_cast [[PB]] : $*Builtin.BridgeObject to $*Builtin.NativeObject // CHECK: [[BUILTIN:%.*]] = is_unique [[CAST]] : $*Builtin.NativeObject // CHECK: copy_addr [[PB]] to %0 : $*Builtin.BridgeObject // CHECK-NEXT: strong_release [[BOX]] : $@box Builtin.BridgeObject // CHECK-NEXT: return func isUnique_native(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUnique_native(&ref)) } // BridgeObject pinned nonNull native // CHECK-LABEL: sil hidden @_TF8builtins23isUniqueOrPinned_native // CHECK: bb0(%0 : $*Builtin.BridgeObject): // CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.BridgeObject // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK: copy_addr %0 to [initialization] [[PB]] : $*Builtin.BridgeObject // CHECK: [[CAST:%.*]] = unchecked_addr_cast [[PB]] : $*Builtin.BridgeObject to $*Builtin.NativeObject // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[CAST]] : $*Builtin.NativeObject // CHECK: copy_addr [[PB]] to %0 : $*Builtin.BridgeObject // CHECK-NEXT: strong_release [[BOX]] : $@box Builtin.BridgeObject // CHECK-NEXT: return func isUniqueOrPinned_native(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned_native(&ref)) } // ---------------------------------------------------------------------------- // Builtin.castReference // ---------------------------------------------------------------------------- class A {} protocol PUnknown {} protocol PClass : class {} // CHECK-LABEL: sil hidden @_TF8builtins19refcast_generic_any // CHECK: unchecked_ref_cast_addr T in %{{.*}} : $*T to AnyObject in %{{.*}} : $*AnyObject func refcast_generic_any<T>(_ o: T) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_TF8builtins17refcast_class_any // CHECK: unchecked_ref_cast %0 : $A to $AnyObject // CHECK-NEXT: return func refcast_class_any(_ o: A) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_TF8builtins20refcast_punknown_any // CHECK: unchecked_ref_cast_addr PUnknown in %{{.*}} : $*PUnknown to AnyObject in %{{.*}} : $*AnyObject func refcast_punknown_any(_ o: PUnknown) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_TF8builtins18refcast_pclass_any // CHECK: unchecked_ref_cast %0 : $PClass to $AnyObject // CHECK-NEXT: return func refcast_pclass_any(_ o: PClass) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_TF8builtins20refcast_any_punknown // CHECK: unchecked_ref_cast_addr AnyObject in %{{.*}} : $*AnyObject to PUnknown in %{{.*}} : $*PUnknown func refcast_any_punknown(_ o: AnyObject) -> PUnknown { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_TF8builtins22unsafeGuaranteed_class // CHECK: bb0([[P:%.*]] : $A): // CHECK: strong_retain [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<A>([[P]] : $A) // CHECK: [[R:%.*]] = tuple_extract [[T]] : $(A, Builtin.Int8), 0 // CHECK: [[K:%.*]] = tuple_extract [[T]] : $(A, Builtin.Int8), 1 // CHECK: strong_release [[R]] : $A // CHECK: return [[P]] : $A // CHECK: } func unsafeGuaranteed_class(_ a: A) -> A { Builtin.unsafeGuaranteed(a) return a } // CHECK-LABEL: _TF8builtins24unsafeGuaranteed_generic // CHECK: bb0([[P:%.*]] : $T): // CHECK: strong_retain [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P]] : $T) // CHECK: [[R:%.*]] = tuple_extract [[T]] : $(T, Builtin.Int8), 0 // CHECK: [[K:%.*]] = tuple_extract [[T]] : $(T, Builtin.Int8), 1 // CHECK: strong_release [[R]] : $T // CHECK: return [[P]] : $T // CHECK: } func unsafeGuaranteed_generic<T: AnyObject> (_ a: T) -> T { Builtin.unsafeGuaranteed(a) return a } // CHECK_LABEL: sil hidden @_TF8builtins31unsafeGuaranteed_generic_return // CHECK: bb0([[P:%.*]] : $T): // CHECK: strong_retain [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P]] : $T) // CHECK: [[R]] = tuple_extract [[T]] : $(T, Builtin.Int8), 0 // CHECK: [[K]] = tuple_extract [[T]] : $(T, Builtin.Int8), 1 // CHECK: strong_release [[P]] // CHECK: [[S:%.*]] = tuple ([[R]] : $T, [[K]] : $Builtin.Int8) // CHECK: return [[S]] : $(T, Builtin.Int8) // CHECK: } func unsafeGuaranteed_generic_return<T: AnyObject> (_ a: T) -> (T, Builtin.Int8) { return Builtin.unsafeGuaranteed(a) } // CHECK-LABEL: sil hidden @_TF8builtins19unsafeGuaranteedEnd // CHECK: bb0([[P:%.*]] : $Builtin.Int8): // CHECK: builtin "unsafeGuaranteedEnd"([[P]] : $Builtin.Int8) // CHECK: [[S:%.*]] = tuple () // CHECK: return [[S]] : $() // CHECK: } func unsafeGuaranteedEnd(_ t: Builtin.Int8) { Builtin.unsafeGuaranteedEnd(t) }
15f952a8f3bef45b5d55b6a70561a5ba
38.128625
192
0.651197
false
false
false
false
Sharelink/Bahamut
refs/heads/master
Bahamut/UIShareContent.swift
mit
1
// // UIShareContent.swift // Bahamut // // Created by AlexChow on 15/7/28. // Copyright (c) 2015年 GStudio. All rights reserved. // import UIKit import AVFoundation import EVReflection protocol UIShareContentDelegate { func initContent(shareCell:UIShareThing,share:ShareThing) func refresh(sender:UIShareContent,share:ShareThing?) func getContentView(sender: UIShareContent, share: ShareThing?) -> UIView func getContentFrame(sender: UIShareThing, share: ShareThing?) -> CGRect } class UIShareContent: UIView { var shareCell:UIShareThing! var delegate:UIShareContentDelegate! var share:ShareThing!{ didSet{ if contentView != nil { contentView.removeFromSuperview() } contentView = delegate.getContentView(self, share: share) self.addSubview(contentView) } } func update() { if delegate != nil && contentView != nil { self.delegate.refresh(self, share: self.share) } } deinit{ if contentView != nil { contentView.removeFromSuperview() contentView = nil } } private(set) var contentView:UIView! }
1d3a8c40c37b0a19e940ca4fccf20e7f
22.566038
77
0.619696
false
false
false
false
JGiola/swift
refs/heads/main
test/Frontend/opt-record-supplemental.swift
apache-2.0
10
// RUN: %empty-directory(%t) // RUN: echo '"%s": { yaml-opt-record: "%t/foo.opt.yaml" }' > %t/filemap.yaml.yaml // RUN: echo '"%s": { bitstream-opt-record: "%t/foo.opt.bitstream" }' > %t/filemap.bitstream.yaml // RUN: %target-swift-frontend -c -O -wmo -save-optimization-record=bitstream %s -module-name foo -o %t/foo.o -supplementary-output-file-map %t/filemap.bitstream.yaml // RUN: llvm-bcanalyzer -dump "%t/foo.opt.bitstream" | %FileCheck -check-prefix=BITSTREAM %s // RUN: %target-swift-frontend -c -O -wmo -save-optimization-record=yaml %s -module-name foo -o %t/foo.o -supplementary-output-file-map %t/filemap.yaml.yaml // RUN: %FileCheck %s -check-prefix=YAML --input-file=%t/foo.opt.yaml // REQUIRES: VENDOR=apple var a: Int = 1 #sourceLocation(file: "custom.swift", line: 2000) func foo() { a = 2 } #sourceLocation() // reset public func bar() { foo() // BITSTREAM: <Remark NumWords=13 BlockCodeSize=4> // BITSTREAM: </Remark> // YAML: sil-assembly-vision-remark-gen }
c1f4cbfca6bfa9a2e1e83c11d1f3d578
35.888889
166
0.678715
false
false
false
false
CodaFi/swift
refs/heads/main
validation-test/compiler_crashers_fixed/00791-swift-type-walk.swift
apache-2.0
65
// 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 var d { typealias F = i<3] { var e(x) { } struct S) -> { } typealias R = compose<T -> U -> { } let c in c == c> { var b(n: T) -> { } var e> { } } protocol d : b = B<d<j : NSObject { map() { } protocol A { } class c { } } } struct B<T> String { } protocol a = e: A { case .h: d { } typealias b { typealias A { } } } var f : Sequence where A, U) -> Bool { print() } class A { struct c in c { enum a") } protocol A : a { func a(T
59126996ac6d4187b1f0a956b0dddad4
15.5
79
0.631515
false
false
false
false
exoplatform/exo-ios
refs/heads/acceptance
eXo/Sources/CheckStoreUpdate.swift
lgpl-3.0
1
// // CheckStoreUpdate.swift // eXo // // Created by Wajih Benabdessalem on 2/2/2022. // Copyright © 2022 eXo. All rights reserved. // import Foundation class CheckStoreUpdate { public static let shared = CheckStoreUpdate() var newVersionAvailable: Bool? var appStoreVersion: String? func checkAppStore(callback: ((_ versionAvailable: Bool, _ version: String?)->Void)? = nil) { var isNew: Bool = false var versionStr: String = "" let request = checkVersionRequest() let dataTask = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if let error = error { print(error) } if let dataa = data { let jsonn = try? JSONSerialization.jsonObject(with: dataa, options: []) if let json = jsonn as? NSDictionary,let results = json["results"] as? NSArray,let entry = results.firstObject as? NSDictionary,let appVersion = entry["version"] as? String,let ourVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String { isNew = ourVersion.compare(appVersion, options: .numeric) == .orderedAscending versionStr = appVersion } self.appStoreVersion = versionStr self.newVersionAvailable = isNew DispatchQueue.main.async { callback?(isNew, versionStr) } } }) dataTask.resume() } /// Create the request . func checkVersionRequest() -> NSMutableURLRequest { let bundleId = Bundle.main.infoDictionary!["CFBundleIdentifier"] as! String let headers = ["Content-Type": "application/x-www-form-urlencoded"] let postData = NSMutableData(data: "undefined=undefined".data(using: String.Encoding.utf8)!) let request = NSMutableURLRequest(url: NSURL(string: "https://itunes.apple.com/lookup?bundleId=\(bundleId)")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) request.httpMethod = "POST" request.allHTTPHeaderFields = headers request.httpBody = postData as Data return request } }
b62c3a25c8f0b5b956dfd060b6ea0e75
41.053571
276
0.600849
false
false
false
false
normand1/SpriteKit-InventorySystem
refs/heads/master
InventoryTestApp/SecondaryInventoryViewController.swift
mit
1
// // InventoryViewController.swift // PestControl // // Created by David Norman on 8/22/15. // Copyright (c) 2015 Razeware LLC. All rights reserved. // import SpriteKit class SecondaryInventoryViewController: UIViewController { var scene: SecondaryInventoryScene? @IBOutlet var inventoryMenuView: SKView! //MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "dismissMenu", name: "com.davidwnorman.dismissMainMenu", object: nil) self.scene = SecondaryInventoryScene(size: self.view.bounds.size) inventoryMenuView.showsFPS = true inventoryMenuView.showsNodeCount = true inventoryMenuView.ignoresSiblingOrder = true self.scene!.scaleMode = .ResizeFill inventoryMenuView.presentScene(scene) self.view.backgroundColor = UIColor.blackColor() } func dismissMenu() { self.dismissViewControllerAnimated(true, completion: { () -> Void in }) } }
e4927265c60d7daf0c6b521cb7b4b358
28.972222
142
0.677479
false
false
false
false
NordicSemiconductor/IOS-nRF-For-HomeKit
refs/heads/master
nRFHomekit/Utilities/Utility.swift
bsd-3-clause
1
/* * Copyright (c) 2015, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import HomeKit public class Utility { //For showing Processing Message with activity indicator private var processingMessageView = UIView() private var processingActivityIndicator = UIActivityIndicatorView() private var processingSuperView:UIView? //For Showing Empty Table Message private var emptyTableMessageView = UIView() private var emptyTableSuperView : UITableView? private var emptyRoomsTableMessageView = UIView() private var emptyRoomsTableMessageSuperView : UITableView? private var emptyAccessoriesTableMessageView = UIView() private var emptyAccessoriesTableMessageSuperView : UITableView? private var isAlertVisible = false public class var sharedInstance : Utility { struct staticUtility { static let instance:Utility = Utility() } return staticUtility.instance } //Messages to show for empty table view public let NO_HOME_FOUND_IN_SELECT_DEVICE = "There is no home. Please add Home from Settings." public let NO_ACCESSORY_IN_PRIMARY_HOME = "There is no accessory in Primary Home. Please add accessory from Settings or change Primay Home from Settings." public let NO_HOME_FOUND_IN_SETTINGS = "There is no home. Please add Home by tapping [+] on navigation bar." public let NO_ROOM_FOUND_IN_HOME_SETTINGS = "Please add Room by tapping on [+]." public let NO_ACCESSORIES_FOUND_IN_HOME_SETTINGS = "Please add Accessory by tapping on [+]." public let NO_ROOM_FOUND_IN_ACCESSORY_CONFIG = "No Room is found in this Home. Please add one from ROOMS in Configure Home page." public let NO_ACCESSORY_FOUND_IN_ROOM_CONFIG = "No Accessory is found in this room. Please add one from ACCESSORIES in Configure Home page." public let NO_ACCESSORY_FOUND_IN_ADD_ACCESSORY = "No Accessory to add. Please makes sure the accessory is in range." public func displayEmptyTableMessage(tableView:UITableView, msg:String) { let viewWidth:CGFloat = 200 let viewHeight:CGFloat = 150 self.emptyTableSuperView = tableView removeEmptyTableMessage() let emptyTableMessageLabel = UILabel(frame: CGRect(x: 10, y: 10, width: viewWidth - 20, height: viewHeight - 20)) emptyTableMessageLabel.text = msg emptyTableMessageLabel.textColor = UIColor.whiteColor() emptyTableMessageLabel.font = UIFont(name: "HelveticaNeue", size: 16.0) emptyTableMessageLabel.lineBreakMode = .ByWordWrapping emptyTableMessageLabel.numberOfLines = 0 emptyTableMessageView = UIView(frame: CGRect(x: tableView.frame.midX - 100, y: tableView.frame.midY - 150 , width: viewWidth, height: viewHeight)) emptyTableMessageView.layer.cornerRadius = 15 //emptyTableMessageView.backgroundColor = UIColor(white: 0, alpha: 0.5) emptyTableMessageView.backgroundColor = UIColor.lightGrayColor() emptyTableMessageView.addSubview(emptyTableMessageLabel) tableView.addSubview(emptyTableMessageView) tableView.separatorStyle = .None tableView.scrollEnabled = false } public func displayEmptyTableMessageAtTop(tableView:UITableView, msg:String) { let viewWidth:CGFloat = 200 let viewHeight:CGFloat = 150 self.emptyTableSuperView = tableView removeEmptyTableMessage() let emptyTableMessageLabel = UILabel(frame: CGRect(x: 10, y: 10, width: viewWidth - 20, height: viewHeight - 20)) emptyTableMessageLabel.text = msg emptyTableMessageLabel.textColor = UIColor.whiteColor() emptyTableMessageLabel.font = UIFont(name: "HelveticaNeue", size: 16.0) emptyTableMessageLabel.lineBreakMode = .ByWordWrapping emptyTableMessageLabel.numberOfLines = 0 emptyTableMessageView = UIView(frame: CGRect(x: tableView.frame.midX - 100, y: 30 , width: viewWidth, height: viewHeight)) emptyTableMessageView.layer.cornerRadius = 15 //emptyTableMessageView.backgroundColor = UIColor(white: 0, alpha: 0.5) emptyTableMessageView.backgroundColor = UIColor.lightGrayColor() emptyTableMessageView.addSubview(emptyTableMessageLabel) tableView.addSubview(emptyTableMessageView) tableView.separatorStyle = .None tableView.scrollEnabled = false } public func removeEmptyTableMessage() { if let emptyTableSuperView = emptyTableSuperView { emptyTableMessageView.removeFromSuperview() emptyTableSuperView.separatorStyle = .SingleLine emptyTableSuperView.scrollEnabled = true } } public func displayEmptyRoomsTableMessage(tableView:UITableView, msg:String, width:Int, height:Int) { let viewWidth:CGFloat = CGFloat(width) let viewHeight:CGFloat = CGFloat(height) self.emptyRoomsTableMessageSuperView = tableView removeEmptyRoomsTableMessage() let emptyTableMessageLabel = UILabel(frame: CGRect(x: 10, y: 10, width: viewWidth - 20, height: viewHeight - 20)) emptyTableMessageLabel.text = msg emptyTableMessageLabel.textColor = UIColor.whiteColor() emptyTableMessageLabel.font = UIFont(name: "HelveticaNeue", size: 14.0) emptyTableMessageLabel.lineBreakMode = .ByWordWrapping emptyTableMessageLabel.numberOfLines = 0 emptyRoomsTableMessageView = UIView(frame: CGRect(x: tableView.frame.midX - 100, y: tableView.frame.midY - 30 , width: viewWidth, height: viewHeight)) emptyRoomsTableMessageView.layer.cornerRadius = 15 //emptyRoomsTableMessageView.backgroundColor = UIColor(white: 0.5, alpha: 0.5) emptyRoomsTableMessageView.backgroundColor = UIColor.lightGrayColor() emptyRoomsTableMessageView.addSubview(emptyTableMessageLabel) tableView.addSubview(emptyRoomsTableMessageView) tableView.separatorStyle = .None tableView.scrollEnabled = false } public func displayEmptyAccessoriesTableMessage(tableView:UITableView, msg:String, width:Int, height:Int) { let viewWidth:CGFloat = CGFloat(width) let viewHeight:CGFloat = CGFloat(height) self.emptyAccessoriesTableMessageSuperView = tableView removeEmptyAccessoriesTableMessage() let emptyTableMessageLabel = UILabel(frame: CGRect(x: 10, y: 10, width: viewWidth - 20, height: viewHeight - 20)) emptyTableMessageLabel.text = msg emptyTableMessageLabel.textColor = UIColor.whiteColor() emptyTableMessageLabel.font = UIFont(name: "HelveticaNeue", size: 14.0) emptyTableMessageLabel.lineBreakMode = .ByWordWrapping emptyTableMessageLabel.numberOfLines = 0 emptyAccessoriesTableMessageView = UIView(frame: CGRect(x: tableView.frame.midX - 100, y: 20 , width: viewWidth, height: viewHeight)) emptyAccessoriesTableMessageView.layer.cornerRadius = 15 //emptyAccessoriesTableMessageView.backgroundColor = UIColor(white: 0.5, alpha: 0.5) emptyAccessoriesTableMessageView.backgroundColor = UIColor.lightGrayColor() emptyAccessoriesTableMessageView.addSubview(emptyTableMessageLabel) tableView.addSubview(emptyAccessoriesTableMessageView) tableView.separatorStyle = .None tableView.scrollEnabled = false } public func removeEmptyRoomsTableMessage() { if let emptyRoomsTableMessageSuperView = emptyRoomsTableMessageSuperView { emptyRoomsTableMessageView.removeFromSuperview() emptyRoomsTableMessageSuperView.separatorStyle = .SingleLine emptyRoomsTableMessageSuperView.scrollEnabled = true } } public func removeEmptyAccessoriesTableMessage() { if let emptyAccessoriesTableMessageSuperView = emptyAccessoriesTableMessageSuperView { emptyAccessoriesTableMessageView.removeFromSuperview() emptyAccessoriesTableMessageSuperView.separatorStyle = .SingleLine emptyAccessoriesTableMessageSuperView.scrollEnabled = true } } public func displayActivityIndicator(view:UIView, msg:String) { self.processingSuperView = view removeActivityIndicator() let processingMessageLabel = UILabel(frame: CGRect(x: 5, y: 50, width: 110, height: 50)) processingMessageLabel.text = msg processingMessageLabel.textColor = UIColor.whiteColor() processingMessageLabel.font = UIFont(name: "HelveticaNeue", size: 16.0) processingMessageLabel.textAlignment = NSTextAlignment.Center processingActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) processingActivityIndicator.frame = CGRect(x: 35, y: 10, width: 50, height: 50) processingActivityIndicator.startAnimating() processingMessageView = UIView(frame: CGRect(x: view.frame.midX - 70, y: view.frame.midY - 150 , width: 120, height: 100)) processingMessageView.layer.cornerRadius = 15 processingMessageView.backgroundColor = UIColor(white: 0, alpha: 0.5) processingMessageView.addSubview(processingActivityIndicator) processingMessageView.addSubview(processingMessageLabel) view.addSubview(processingMessageView) } public func displayActivityIndicator(view:UIView, msg:String, xOffset:Int, yOffset:Int) { self.processingSuperView = view removeActivityIndicator() let processingMessageLabel = UILabel(frame: CGRect(x: 5, y: 50, width: 110, height: 50)) processingMessageLabel.text = msg processingMessageLabel.textColor = UIColor.whiteColor() processingMessageLabel.font = UIFont(name: "HelveticaNeue", size: 16.0) processingMessageLabel.textAlignment = NSTextAlignment.Center processingActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) processingActivityIndicator.frame = CGRect(x: 35, y: 10, width: 50, height: 50) processingActivityIndicator.startAnimating() processingMessageView = UIView(frame: CGRect(x: view.frame.midX + CGFloat(xOffset), y: view.frame.midY + CGFloat(yOffset) , width: 120, height: 100)) processingMessageView.layer.cornerRadius = 15 processingMessageView.backgroundColor = UIColor(white: 0, alpha: 0.5) processingMessageView.addSubview(processingActivityIndicator) processingMessageView.addSubview(processingMessageLabel) view.addSubview(processingMessageView) } public func removeActivityIndicator() { if processingSuperView != nil { processingMessageView.removeFromSuperview() } } public func showAlert(viewController: UIViewController, title: String!, message:String!) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { action -> Void in //Do some stuff print("OK pressed") self.isAlertVisible = false })) if isAlertVisible == false { isAlertVisible = true viewController.presentViewController(alert, animated: true, completion: nil) } } public func getAccessoryCategoryImage(category: String) -> UIImage! { switch (category) { case HMAccessoryCategoryTypeLightbulb: return UIImage(named: "CategoryLightbulb") case HMAccessoryCategoryTypeDoorLock: return UIImage(named: "CategoryLock") case HMAccessoryCategoryTypeGarageDoorOpener: return UIImage(named: "CategoryGarageDoor") case HMAccessoryCategoryTypeSwitch: return UIImage(named: "CategorySwitch") case HMAccessoryCategoryTypeOutlet: return UIImage(named: "CategoryOutlet") case HMAccessoryCategoryTypeFan: return UIImage(named: "CategoryFan") default: return UIImage(named: "CategoryNotSupported") } } }
6f0a30aed648f1a0ef5532f21cf62012
50.043956
158
0.711302
false
false
false
false
TENDIGI/Obsidian-iOS-SDK
refs/heads/master
Obsidian-iOS-SDK/AuthResource.swift
mit
1
// // AuthResource.swift // ObsidianSDK // // Created by Nick Lee on 7/13/15. // Copyright (c) 2015 TENDIGI, LLC. All rights reserved. // import Foundation /// The AuthResource class is an abstract class from which your application's resources (whose server-side declarations implement the `user-authentication` module) should inherit public class AuthResource: Resource { // MARK: Properties /// Whether or not a credential has been stored for the receiving resource public class var authenticated: Bool { return Credential.lookup(name) != nil } /// The user's username, if available public private(set) var username: String? /// The user's email address, if available public private(set) var email: String? private var token: String? = nil // MARK: Initializers required public init(mapper: Mapper) { if let tokenMapping = mapper.headers?.unbox[Constants.Client.Headers.BearerToken] where tokenMapping.value != nil { token <- tokenMapping } username <- mapper[Constants.Resource.Auth.UsernameKey] email <- mapper[Constants.Resource.Auth.EmailKey] super.init(mapper: mapper) } // MARK: CRUD Methods /** Performs a Create request on the recieving resource and stores its credentials for later use - parameter record: A dictionary of attributes to set on the newly created record - parameter completion: An optional closure to execute when the request finishes */ public override class func create<T: AuthResource>(record: [String : AnyObject] = [:], authResource: AuthResource.Type? = nil, completion: ((response: Response<T>) -> Void)?) { // Erryday I'm casting guard ((record[Constants.Resource.Auth.EmailKey] as? String) ?? (record[Constants.Resource.Auth.UsernameKey] as? String)) != nil else { fatalError("No email or username supplied in record to create() method of AuthResource") } guard let password = record[Constants.Resource.Auth.PasswordKey] as? String else { fatalError("No password supplied in record to create() method of AuthResource") } super.create(record, authResource: authResource, completion: { (createResponse: Response<T>) -> Void in switch createResponse { case .Success: T.authenticate( record[Constants.Resource.Auth.EmailKey] as? String, username: record[Constants.Resource.Auth.UsernameKey] as? String, password: password, completion: { (authResponse: Response<T>) -> Void in completion?(response: authResponse) }) default: completion?(response: createResponse) } }) } // MARK: Authentication /** Performs an authenticate request on the recieving resource - parameter email: The email to authenticate against - parameter password: The password to authenticate against - parameter completion: An optional closure to execute when the request finishes */ public class func authenticate<T: AuthResource>(email email: String, password: String, completion: ((response: Response<T>) -> Void)?) { return authenticate(email, username: nil, password: password, completion: completion) } /** Performs an authenticate request on the recieving resource - parameter username: The username to authenticate against - parameter password: The password to authenticate against - parameter completion: An optional closure to execute when the request finishes */ public class func authenticate<T: AuthResource>(username username: String, password: String, completion: ((response: Response<T>) -> Void)?) { return authenticate(nil, username: username, password: password, completion: completion) } private class func authenticate<T: AuthResource>(email: String? = nil, username: String? = nil, password: String, completion: ((response: Response<T>) -> Void)?) { var criteria = Criteria() if let authEmail = email { criteria = criteria.equals(Constants.Resource.Auth.EmailKey, value: authEmail) } else if let authUsername = username { criteria = criteria.equals(Constants.Resource.Auth.UsernameKey, value: authUsername) } criteria = criteria.equals(Constants.Resource.Auth.PasswordKey, value: password) let params = [ Constants.Request.ResourceRequest.CriteriaKey : criteria.serialized.obsidianRepresentation ] let request = ResourceRequest(method: .POST, resource: self.name, name: Constants.Resource.Auth.MethodName, params: params) Client.sharedInstance.perform(request, completion: { (response: Response<T>) -> Void in switch response { case .Success(let response): if let token = response.firstResult?.token { Credential.store(T.name, token: token) } default: break } completion?(response: response) }) } /** Deletes any credentials stored for the receiving resource */ public class func logout() { Credential.clear(name) } }
b36f7c8bb20fd6f549a5da0aa6dd93c1
36.959184
180
0.628136
false
false
false
false
kyouko-taiga/anzen
refs/heads/master
Sources/AST/ASTVisitor+Traversal.swift
apache-2.0
1
public extension ASTVisitor { // swiftlint:disable cyclomatic_complexity func visit(_ node: Node) throws { switch node { case let n as ModuleDecl: try visit(n) case let n as Block: try visit(n) case let n as PropDecl: try visit(n) case let n as FunDecl: try visit(n) case let n as ParamDecl: try visit(n) case let n as StructDecl: try visit(n) case let n as InterfaceDecl: try visit(n) case let n as QualTypeSign: try visit(n) case let n as TypeIdent: try visit(n) case let n as FunSign: try visit(n) case let n as ParamSign: try visit(n) case let n as Directive: try visit(n) case let n as WhileLoop: try visit(n) case let n as BindingStmt: try visit(n) case let n as ReturnStmt: try visit(n) case let n as NullRef: try visit(n) case let n as IfExpr: try visit(n) case let n as LambdaExpr: try visit(n) case let n as CastExpr: try visit(n) case let n as BinExpr: try visit(n) case let n as UnExpr: try visit(n) case let n as CallExpr: try visit(n) case let n as CallArg: try visit(n) case let n as SubscriptExpr: try visit(n) case let n as SelectExpr: try visit(n) case let n as Ident: try visit(n) case let n as ArrayLiteral: try visit(n) case let n as SetLiteral: try visit(n) case let n as MapLiteral: try visit(n) case let n as Literal<Bool>: try visit(n) case let n as Literal<Int>: try visit(n) case let n as Literal<Double>: try visit(n) case let n as Literal<String>: try visit(n) default: assertionFailure("unexpected node during generic visit") } } // swiftlint:enable cyclomatic_complexity func visit(_ nodes: [Node]) throws { for node in nodes { try visit(node) } } func visit(_ node: ModuleDecl) throws { try traverse(node) } func traverse(_ node: ModuleDecl) throws { try visit(node.statements) } func visit(_ node: Block) throws { try traverse(node) } func traverse(_ node: Block) throws { try visit(node.statements) } // MARK: Declarations func visit(_ node: PropDecl) throws { try traverse(node) } func traverse(_ node: PropDecl) throws { if let typeAnnotation = node.typeAnnotation { try visit(typeAnnotation) } if let (_, value) = node.initialBinding { try visit(value) } } func visit(_ node: FunDecl) throws { try traverse(node) } func traverse(_ node: FunDecl) throws { try visit(node.parameters) if let codomain = node.codomain { try visit(codomain) } if let body = node.body { try visit(body) } } func visit(_ node: ParamDecl) throws { try traverse(node) } func traverse(_ node: ParamDecl) throws { if let annotation = node.typeAnnotation { try visit(annotation) } } func visit(_ node: StructDecl) throws { try traverse(node) } func traverse(_ node: StructDecl) throws { try visit(node.body) } func visit(_ node: InterfaceDecl) throws { try traverse(node) } func traverse(_ node: InterfaceDecl) throws { try visit(node.body) } // MARK: Type signatures func visit(_ node: QualTypeSign) throws { try traverse(node) } func traverse(_ node: QualTypeSign) throws { if let signature = node.signature { try visit(signature) } } func visit(_ node: TypeIdent) throws { try traverse(node) } func traverse(_ node: TypeIdent) throws { try visit(Array(node.specializations.values)) } func visit(_ node: FunSign) throws { try traverse(node) } func traverse(_ node: FunSign) throws { try visit(node.parameters) try visit(node.codomain) } func visit(_ node: ParamSign) throws { try traverse(node) } func traverse(_ node: ParamSign) throws { try visit(node.typeAnnotation) } // MARK: Statements func visit(_ node: Directive) throws { } func visit(_ node: WhileLoop) throws { try traverse(node) } func traverse(_ node: WhileLoop) throws { try visit(node.condition) try visit(node.body) } func visit(_ node: BindingStmt) throws { try traverse(node) } func traverse(_ node: BindingStmt) throws { try visit(node.lvalue) try visit(node.rvalue) } func visit(_ node: ReturnStmt) throws { try traverse(node) } func traverse(_ node: ReturnStmt) throws { if let (_, value) = node.binding { try visit(value) } } // MARK: Expressions func visit(_ node: NullRef) throws { } func visit(_ node: IfExpr) throws { try traverse(node) } func traverse(_ node: IfExpr) throws { try visit(node.condition) try visit(node.thenBlock) if let elseBlock = node.elseBlock { try visit(elseBlock) } } func visit(_ node: LambdaExpr) throws { try traverse(node) } func traverse(_ node: LambdaExpr) throws { try visit(node.parameters) if let codomain = node.codomain { try visit(codomain) } try visit(node.body) } func visit(_ node: CastExpr) throws { try traverse(node) } func traverse(_ node: CastExpr) throws { try visit(node.operand) try visit(node.castType) } func visit(_ node: BinExpr) throws { try traverse(node) } func traverse(_ node: BinExpr) throws { try visit(node.left) try visit(node.right) } func visit(_ node: UnExpr) throws { try traverse(node) } func traverse(_ node: UnExpr) throws { try visit(node.operand) } func visit(_ node: CallExpr) throws { try traverse(node) } func traverse(_ node: CallExpr) throws { try visit(node.callee) try visit(node.arguments) } func visit(_ node: CallArg) throws { try traverse(node) } func traverse(_ node: CallArg) throws { try visit(node.value) } func visit(_ node: SubscriptExpr) throws { try traverse(node) } func traverse(_ node: SubscriptExpr) throws { try visit(node.callee) try visit(node.arguments) } func visit(_ node: SelectExpr) throws { try traverse(node) } func traverse(_ node: SelectExpr) throws { if let owner = node.owner { try visit(owner) } try visit(node.ownee) } func visit(_ node: Ident) throws { try traverse(node) } func traverse(_ node: Ident) throws { try visit(Array(node.specializations.values)) } func visit(_ node: ArrayLiteral) throws { try traverse(node) } func traverse(_ node: ArrayLiteral) throws { try visit(node.elements) } func visit(_ node: SetLiteral) throws { try traverse(node) } func traverse(_ node: SetLiteral) throws { try visit(node.elements) } func visit(_ node: MapLiteral) throws { try traverse(node) } func traverse(_ node: MapLiteral) throws { try visit(Array(node.elements.values)) } func visit(_ node: Literal<Bool>) throws { } func visit(_ node: Literal<Int>) throws { } func visit(_ node: Literal<Double>) throws { } func visit(_ node: Literal<String>) throws { } }
1191708223809399c5705d42bdcb3654
20.95122
62
0.622778
false
false
false
false
baottran/nSURE
refs/heads/master
nSURE/Customer.swift
mit
1
// // Customer.swift // nSURE // // Created by Bao Tran on 6/9/15. // Copyright (c) 2015 Bao Tran. All rights reserved. // import Foundation class Customer: PFObject, PFSubclassing { @NSManaged var firstName: String? @NSManaged var lastName: String? var phones = [Phone]() @NSManaged var defaultPhone: Phone var addresses = [Address]() @NSManaged var defaultAddress: Address var vehicles = [Vehicle]() @NSManaged var defaultVehicle: Vehicle var signees = [Signee]() @NSManaged var defaultSignee: Signee class func parseClassName() -> String { return "Customer" } //2 override class func initialize() { var onceToken: dispatch_once_t = 0 dispatch_once(&onceToken) { self.registerSubclass() } } override class func query() -> PFQuery? { let searc = PFQuery(className: Customer.parseClassName()) return searc } required init(firstName: String?, lastName: String?){ super.init() self.firstName = firstName self.lastName = lastName // // self.defaultPhone = defaultPhone // self.defaultVehicle = defaultVehicle // self.defaultAddress = defaultAddress // self.defaultSignee = defaultSignee // // self.phones.append(defaultPhone) // self.addresses.append(defaultAddress) // self.vehicles.append(defaultVehicle) // self.signees.append(defaultSignee) } override init(){ super.init() } }
ff17136fc8d8a4abb585aac0cc9c164b
22.558824
65
0.596754
false
false
false
false
jpush/jchat-swift
refs/heads/master
JChat/Src/Utilites/3rdParty/InputBar/SAIInputItemView.swift
mit
1
// // SAIInputItemView.swift // SAIInputBar // // Created by SAGESSE on 8/3/16. // Copyright © 2016-2017 SAGESSE. All rights reserved. // import UIKit internal class SAIInputItemView: UICollectionViewCell { var item: SAIInputItem? { willSet { UIView.performWithoutAnimation { self._updateItem(newValue) } } } weak var delegate: SAIInputItemViewDelegate? { set { return _button.delegate = newValue } get { return _button.delegate } } func setSelected(_ selected: Bool, animated: Bool) { _button.setSelected(selected: selected, animated: animated) } func _init() { clipsToBounds = true backgroundColor = .clear //backgroundColor = UIColor.greenColor().colorWithAlphaComponent(0.2) } func _updateItem(_ newValue: SAIInputItem?) { guard let newValue = newValue else { // clear on nil _contentView?.removeFromSuperview() _contentView = nil return } if let customView = newValue.customView { // 需要显示自定义视图 _contentView?.removeFromSuperview() _contentView = customView } else { // 显示普通按钮 if _contentView !== _button { _contentView?.removeFromSuperview() _contentView = _button } // 更新按钮属性 _button.barItem = newValue } // 更新视图 if let view = _contentView, view.superview != contentView { view.frame = contentView.bounds view.autoresizingMask = [.flexibleWidth, .flexibleHeight] contentView.addSubview(view) } } private var _contentView: UIView? private lazy var _button: SAIInputItemButton = { let view = SAIInputItemButton(type: .custom) //let view = SAIInputItemButton(type: .System) view.isMultipleTouchEnabled = false view.isExclusiveTouch = true return view }() override init(frame: CGRect) { super.init(frame: frame) _init() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) _init() } } internal class SAIInputItemButton: UIButton { override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { guard let barItem = self.barItem else { return super.beginTracking(touch, with: event) } if delegate?.barItem(shouldHighlightFor: barItem) ?? true { allowsHighlight = true delegate?.barItem(didHighlightFor: barItem) } else { allowsHighlight = false } return super.beginTracking(touch, with: event) } var barItem: SAIInputItem? { willSet { guard barItem !== newValue else { return } UIView.performWithoutAnimation { guard let item = newValue else { return } self._updateBarItem(item) } } } weak var delegate: SAIInputItemViewDelegate? var allowsHighlight = true var _selected: Bool = false override var isHighlighted: Bool { set { guard allowsHighlight else { return } super.isHighlighted = newValue _setHighlighted(newValue, animated: true) } get { return super.isHighlighted } } override var state: UIControl.State { // 永远禁止系统的选中 return super.state.subtracting(.selected) } func setSelected(selected: Bool, animated: Bool) { //logger.trace(selected) let op1: UIControl.State = [(selected ? .selected : .normal), .normal] let op2: UIControl.State = [(selected ? .selected : .normal), .highlighted] let n = barItem?.image(for: op1) ?? barItem?.image(for: .normal) let h = barItem?.image(for: op2) setImage(n, for: .normal) setImage(h, for: .highlighted) if animated { _addAnimation("selected") } _selected = selected } private func _init() { addTarget(self, action: #selector(_touchHandler), for: .touchUpInside) } private func _addAnimation(_ key: String) { let ani = CATransition() ani.duration = 0.35 ani.fillMode = CAMediaTimingFillMode.backwards ani.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear) ani.type = CATransitionType.fade ani.subtype = CATransitionSubtype.fromTop layer.add(ani, forKey: key) } private func _setHighlighted(_ highlighted: Bool, animated: Bool) { //logger.trace(highlighted) // 检查高亮的时候有没有设置图片, 如果有关闭系统的变透明效果 if barItem?.image(for: [(isSelected ? .selected : .normal), .highlighted]) != nil { imageView?.alpha = 1 } if animated { _addAnimation("highlighted") } } func _updateBarItem(_ item: SAIInputItem) { let states: [UIControl.State] = [ [.normal], [.highlighted], [.disabled], [.selected, .normal], [.selected, .highlighted], [.selected, .disabled] ] tag = item.tag isEnabled = item.enabled imageEdgeInsets = item.imageInsets tintColor = item.tintColor backgroundColor = item.backgroundColor if let font = item.font { titleLabel?.font = font } states.forEach { setTitle(item.title(for: $0), for: $0) setTitleColor(item.titleColor(for: $0), for: $0) setTitleShadowColor(item.titleShadowColor(for: $0), for: $0) setAttributedTitle(item.attributedTitle(for: $0), for: $0) setImage(item.image(for: $0), for: $0) setBackgroundImage(item.backgroundImage(for: $0), for: $0) } setTitle(item.title, for: .normal) setImage(item.image, for: .normal) } @objc private func _touchHandler() { guard let barItem = barItem else { return } // delegate before the callback barItem.handler?(barItem) if !_selected { // select guard delegate?.barItem(shouldSelectFor: barItem) ?? true else { return } setSelected(selected: true, animated: true) delegate?.barItem(didSelectFor: barItem) } else { // Deselect guard delegate?.barItem(shouldDeselectFor: barItem) ?? true else { return } setSelected(selected: false, animated: true) delegate?.barItem(didDeselectFor: barItem) } } override init(frame: CGRect) { super.init(frame: frame) _init() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) _init() } } internal protocol SAIInputItemViewDelegate: class { func barItem(shouldHighlightFor barItem: SAIInputItem) -> Bool func barItem(shouldDeselectFor barItem: SAIInputItem) -> Bool func barItem(shouldSelectFor barItem: SAIInputItem) -> Bool func barItem(didHighlightFor barItem: SAIInputItem) func barItem(didDeselectFor barItem: SAIInputItem) func barItem(didSelectFor barItem: SAIInputItem) }
a36b6d668633632cce964c60e0a867ef
28.667954
91
0.557913
false
false
false
false
LYM-mg/DemoTest
refs/heads/master
其他功能/MGImagePickerControllerTest/MGImagePickerControllerTest/ImagePickerController/Manager/MGPhotoHandleManager.swift
mit
1
// // MGPhotoHandleManager.swift // MGImagePickerControllerDemo // // Created by newunion on 2019/7/8. // Copyright © 2019 MG. All rights reserved. // import UIKit import Photos import ObjectiveC extension PHCachingImageManager { static let defalut = PHCachingImageManager() } /// 进行数据类型转换的Manager class MGPhotoHandleManager: NSObject { /// 用以描述runtime关联属性 struct MGPhotoAssociate { static let mg_assetCollectionAssociate = UnsafeRawPointer(bitPattern: "mg_assetCollection".hashValue) static let mg_cacheAssociate = UnsafeRawPointer(bitPattern: "mg_CacheAssociate".hashValue) static let mg_assetCacheSizeAssociate = UnsafeRawPointer(bitPattern: "mg_assetCacheSizeAssociate".hashValue) } /// PHFetchResult对象转成数组的方法 /// /// - Parameters: /// - result: 转型的fetchResult对象 /// - complete: 完成的闭包 public static func resultToArray(_ result: PHFetchResult<AnyObject>, complete: @escaping ([AnyObject], PHFetchResult<AnyObject>) -> Void) { guard result.count != 0 else { complete([], result); return } var array = [AnyObject]() //开始遍历 result.enumerateObjects({ (object, index, _) in // 过滤自定义空数组 if object.isKind(of: PHAssetCollection.self) && object.estimatedAssetCount > 0 { let assetResult = PHAsset.fetchAssets(in: object as! PHAssetCollection, options: PHFetchOptions()) debugPrint(object.localizedTitle ?? "没有名字") // 过滤空数组 if assetResult.count != 0 { array.append(object) }else { } if index == result.count - 1 { complete(array, result) } }else { if index == result.count - 1 { complete(array, result) } } }) } /// PHFetchResult对象转成PHAsset数组的方法 /// /// - Parameters: /// - result: 转型的fetchResult对象 PHAsset /// - complete: 完成的闭包 public static func resultToPHAssetArray(_ result: PHFetchResult<AnyObject>, complete: @escaping ([AnyObject], PHFetchResult<AnyObject>) -> Void) { guard result.count != 0 else { complete([], result); return } var array = [AnyObject]() //开始遍历 result.enumerateObjects({ (object, index, _) in if object.isKind(of: PHAsset.self) { array.append(object) } complete(array, result) }) } /// 获得选择的图片数组 /// /// - Parameters: /// - allAssets: 所有的资源数组 /// - status: 选中状态 /// - Returns: public static func assets(_ allAssets: [PHAsset], status: [Bool]) -> [PHAsset] { var assethandle = [PHAsset]() for i in 0 ..< allAssets.count { let status = status[i] if status { assethandle.append(allAssets[i]) } } return assethandle } /// 获取PHAssetCollection的详细信息 /// /// - Parameters: /// - size: 获得封面图片的大小 /// - completion: 取组的标题、照片资源的预估个数以及封面照片,默认为最新的一张 public static func assetCollection(detailInformationFor collection: PHAssetCollection, size: CGSize, completion: @escaping ((String?, UInt, UIImage?) -> Void)) { let assetResult = PHAsset.fetchAssets(in: collection, options: PHFetchOptions()) if assetResult.count == 0 { completion(collection.localizedTitle, 0, UIImage()) return } let image: UIImage? = ((objc_getAssociatedObject(collection, MGPhotoHandleManager.MGPhotoAssociate.mg_assetCollectionAssociate!)) as? UIImage) if image != nil { completion(collection.localizedTitle, UInt(assetResult.count), image) return } //开始重新获取图片 let scale = UIScreen.main.scale let newSize = CGSize(width: size.width * scale, height: size.height * scale) PHCachingImageManager.default().requestImage(for: assetResult.lastObject!, targetSize: newSize, contentMode: PHImageContentMode.aspectFill, options: nil, resultHandler: { (realImage, _) in completion(collection.localizedTitle, UInt(assetResult.count), realImage) }) } /// 获取PHAsset的照片资源 /// - Parameters: /// - asset: 获取资源的对象 /// - size: 截取图片的大小 /// - completion: 获取的图片,以及当前的资源对象 public static func asset(representionIn asset: PHAsset, size: CGSize, completion: @escaping ((UIImage, PHAsset) -> Void)) { if let cacheAssociate = MGPhotoHandleManager.MGPhotoAssociate.mg_cacheAssociate, objc_getAssociatedObject(asset, cacheAssociate) == nil { objc_setAssociatedObject(asset, MGPhotoHandleManager.MGPhotoAssociate.mg_cacheAssociate!, [CGSize](), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } var caches: [CGSize] = objc_getAssociatedObject(asset, MGPhotoHandleManager.MGPhotoAssociate.mg_cacheAssociate!) as! [CGSize] let scale = UIScreen.main.scale let newSize = CGSize(width: size.width * scale, height: size.height * scale) //开始请求 let option = PHImageRequestOptions() option.resizeMode = .fast // 同步获得图片, 只会返回1张图片 option.isSynchronous = true option.isNetworkAccessAllowed = true//默认关闭 let fileName: String? = asset.value(forKeyPath: "filename") as? String if let fileName = fileName, fileName.hasSuffix("GIF") { option.version = .original } PHCachingImageManager.default().requestImage(for: asset, targetSize: newSize, contentMode: PHImageContentMode.aspectFill, options: option) { (image, info) in if !((info![PHImageResultIsDegradedKey] as? NSNumber)?.boolValue ?? false) { //这样只会走一次获取到高清图时 DispatchQueue.main.async(execute: { completion(image ?? UIImage(), asset) }) } } //进行缓存 if !caches.contains(newSize) { (PHCachingImageManager.default() as! PHCachingImageManager).startCachingImages(for: [asset], targetSize: newSize, contentMode: PHImageContentMode.aspectFill, options: PHImageRequestOptions()) caches.append(newSize) //重新赋值 objc_setAssociatedObject(asset, MGPhotoHandleManager.MGPhotoAssociate.mg_cacheAssociate!, caches, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC) } } /// 获取PHAsset的高清图片资源 /// /// - Parameters: /// - asset: 获取资源的对象 /// - size: 获取图片的大小 /// - completion: 完成 public static func asset(hightQuarityFor asset: PHAsset, Size size: CGSize, completion: @escaping ((String) -> Void)) { let newSize = size if let assetCache = MGPhotoAssociate.mg_assetCacheSizeAssociate, objc_getAssociatedObject(asset, assetCache) == nil { let associateData = [String: Any]()//Dictionary<String, Any> objc_setAssociatedObject(asset, assetCache, associateData, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC) } /// 获得当前所有的存储 var assicciateData = objc_getAssociatedObject(asset, MGPhotoAssociate.mg_assetCacheSizeAssociate!) as! [String: Any] guard assicciateData.index(forKey: NSCoder.string(for: newSize)) == nil else { let index = assicciateData.index(forKey: NSCoder.string(for: newSize))//获得索引 let size = assicciateData[index!].value as! String//获得数据 completion(size); return } let options = PHImageRequestOptions() // options.deliveryMode = .highQualityFormat options.isSynchronous = true options.resizeMode = .fast options.isNetworkAccessAllowed = true let fileName: String? = asset.value(forKeyPath: "filename") as? String if let fileName = fileName, fileName.hasSuffix("GIF") { options.version = .original } //请求数据 PHCachingImageManager.default().requestImageData(for: asset, options: options) { (data, _, _, _) in guard let data = data else { //回调 completion("0B") return } //进行数据转换 // let size = mg_dataSize((data?.count)!) let size = (data.count).mg_dataSize //新增值 assicciateData.updateValue(size, forKey: NSCoder.string(for: newSize)) //缓存 objc_setAssociatedObject(asset, MGPhotoAssociate.mg_assetCacheSizeAssociate!, assicciateData, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC) //回调 completion(size) } } /// 获取PHFetchResult符合媒体类型的PHAsset对象 /// /// - Parameters: /// - result: 获取数据的对象 /// - type: 媒体类型 /// - enumerateObject: 每次获得符合媒体类型的对象调用一次 /// - matchedObject: 每次都会调用一次 /// - completion: 完成之后返回存放符合媒体类型的PHAsset数组 public static func fetchResult(in result: PHFetchResult<PHAsset>, type: PHAssetMediaType, enumerateObject: ((PHAsset) -> Void)?, matchedObject: ((PHAsset) -> Void)?, completion: (([PHAsset]) -> Void)?) { var assets = [PHAsset]() // 如果当前没有数据 guard result.count >= 0 else { completion?(assets);return } //开始遍历 result.enumerateObjects({ (obj, idx, _) in // 每次回调 enumerateObject?(obj) // 如果是类型相符合 if obj.mediaType == type { matchedObject?(obj) assets.append(obj) } if idx == result.count - 1 { // 说明完成 completion?(assets) } }) } /// 获取PHFetchResult符合媒体类型的PHAsset对象 /// /// - Parameters: /// - result: 获取资源的对象 /// - type: 媒体类型 /// - completion: 完成之后返回存放符合媒体类型的PHAsset数组 public static func fetchResult(in result: PHFetchResult<PHAsset>, type: PHAssetMediaType, completion: (([PHAsset]) -> Void)?) { fetchResult(in: result, type: type, enumerateObject: nil, matchedObject: nil, completion: completion) } /// 获得选择的资源数组 /// /// - Parameters: /// - assets: 存放资源的数组 /// - status: 对应资源的选中状态数组 /// - Returns: 筛选完毕的数组 public static func filter(assetsIn assets: [PHAsset], status: [Bool]) -> [PHAsset] { var assetHandle = [PHAsset]() for asset in assets { //如果状态为选中 if status[assets.firstIndex(of: asset)!] { assetHandle.append(asset) } } return assetHandle } } extension MGPhotoHandleManager { /// 获取资源中的图片对象 /// /// - Parameters: /// - assets: 需要请求的asset数组 /// - isHight: 图片是否需要高清图 /// - size: 当前图片的截取size /// - ignoreSize: 是否无视size属性,按照图片原本大小获取 /// - completion: 返回存放images的数组 static func startRequestImage(imagesIn assets: [PHAsset], isHight: Bool, size: CGSize, ignoreSize: Bool, completion: @escaping (([UIImage]) -> Void)) { var images = [UIImage]() var newSize = size for i in 0 ..< assets.count { //获取资源 let asset = assets[i] //重置大小 if ignoreSize { newSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight) } //图片类型 let mode = isHight ? PHImageRequestOptionsDeliveryMode.highQualityFormat : PHImageRequestOptionsDeliveryMode.fastFormat //初始化option let option = PHImageRequestOptions() option.deliveryMode = mode option.isSynchronous = true option.isNetworkAccessAllowed = true let fileName: String? = asset.value(forKeyPath: "filename") as? String if let fileName = fileName, fileName.hasSuffix("GIF") { option.version = .original } //开始请求 PHImageManager.default().requestImage(for: asset, targetSize: newSize, contentMode: PHImageContentMode.aspectFill, options: option, resultHandler: { (image, _) in //添加 images.append(image!) if images.count == assets.count { completion(images) } }) } } /// 获取资源中图片的数据对象 /// /// - Parameters: /// - assets: 需要请求的asset数组 /// - isHight: 图片是否需要高清图 /// - completion: 返回存放images的数组 static func startRequestData(imagesIn assets: [PHAsset], isHight: Bool, completion: @escaping (([Data]) -> Void)) { var datas = [Data]() for i in 0 ..< assets.count { let asset = assets[i] let mode = isHight ? PHImageRequestOptionsDeliveryMode.highQualityFormat : PHImageRequestOptionsDeliveryMode.fastFormat //初始化option let option = PHImageRequestOptions() option.deliveryMode = mode option.isSynchronous = true option.isNetworkAccessAllowed = true let fileName: String? = asset.value(forKeyPath: "filename") as? String if let fileName = fileName, fileName.hasSuffix("GIF") { option.version = .original } //请求数据 PHImageManager.default().requestImageData(for: asset, options: option, resultHandler: { (data, _, _, _) in if let data = data { datas.append(data) } if datas.count == assets.count { completion(datas) } }) } } }
2e8277c93417fb9e337768361c7eb27a
34.740741
207
0.591562
false
false
false
false
witekbobrowski/Stanford-CS193p-Winter-2017
refs/heads/master
Cassini/Cassini/DemoURL.swift
mit
1
// // DemoURL.swift // // Created by CS193p Instructor. // Copyright (c) 2017 Stanford University. All rights reserved. // import Foundation struct DemoURL{ static let stanford = URL(string: "http://stanford.edu/about/images/intro_about.jpg") static var NASA: Dictionary<String,URL> = { let NASAURLStrings = [ "Cassini" : "http://www.jpl.nasa.gov/images/cassini/20090202/pia03883-full.jpg", "Earth" : "http://www.nasa.gov/sites/default/files/wave_earth_mosaic_3.jpg", "Saturn" : "http://www.nasa.gov/sites/default/files/saturn_collage.jpg" ] var urls = Dictionary<String,URL>() for (key, value) in NASAURLStrings { urls[key] = URL(string: value) } return urls }() }
c66d0494961a0ca6a90653db3f20a0f4
29.346154
92
0.609632
false
false
false
false