repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
gcharita/XMLMapper
XMLMapper/Classes/Requests/XMLEncoding.swift
1
3048
// // XMLEncoding.swift // XMLMapper // // Created by Giorgos Charitakis on 30/09/2017. // import Foundation import Alamofire /// Uses `XMLSerialization` to create a XML representation of the parameters object, which is set as the body of the /// request. The `Content-Type` HTTP header field of an encoded request is set to `text/xml`. public struct XMLEncoding: ParameterEncoding { // MARK: Properties /// Returns a `XMLEncoding` instance for a simple XML request body public static var `default`: XMLEncoding { return XMLEncoding() } private var soapAction: String? private var soapVersion: SOAPVersion? // MARK: Initialization /// Creates a `XMLEncoding` instance public init(withAction soapAction: String? = nil, soapVersion: SOAPVersion? = nil) { self.soapAction = soapAction self.soapVersion = soapVersion } /// Returns a `XMLEncoding` instance for a SOAP request body public static func soap(withAction soapAction: String?, soapVersion: SOAPVersion = .version1point1) -> XMLEncoding { return XMLEncoding(withAction: soapAction, soapVersion: soapVersion) } // MARK: Encoding /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } let data = try XMLSerialization.data(withXMLObject: parameters, addXMLDeclaration: true) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { switch soapVersion { case .none: urlRequest.setValue("text/xml; charset=\"utf-8\"", forHTTPHeaderField: "Content-Type") case .some(let soapVersion): var contentType = soapVersion.contentType if let soapAction = soapAction, soapVersion == .version1point2 { contentType += ";action=\"\(soapAction)\"" } urlRequest.setValue(contentType, forHTTPHeaderField: "Content-Type") } } if let soapAction = soapAction, urlRequest.value(forHTTPHeaderField: "SOAPAction") == nil, soapVersion == .version1point1 { urlRequest.setValue(soapAction, forHTTPHeaderField: "SOAPAction") } if urlRequest.value(forHTTPHeaderField: "Content-Length") == nil, soapVersion != nil { urlRequest.setValue("\(data.count)", forHTTPHeaderField: "Content-Length") } urlRequest.httpBody = data return urlRequest } }
mit
9a6c0cd9292f34c6ea85631cfb4d8d64
38.076923
131
0.644357
4.940032
false
false
false
false
gp09/Beefit
BeefitMsc/BeefitMsc/BeeLearnToFitViewController.swift
1
1610
// // BeeLearnToFitViewController.swift // BeefitMsc // // Created by Priyank on 01/08/2017. // Copyright © 2017 priyank. All rights reserved. // import UIKit class BeeLearnToFitViewController: UIViewController { var gridCollectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() // gridCollectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 100, width: self.view.frame.size.width, height: self.view.frame.size.height), collectionViewLayout:nil) gridCollectionView.backgroundColor = nil gridCollectionView.showsVerticalScrollIndicator = false gridCollectionView.showsHorizontalScrollIndicator = false gridCollectionView.dataSource = self as! UICollectionViewDataSource gridCollectionView.delegate = self as! UICollectionViewDelegate // gridCollectionView!.register(ImageCell.self, forCellWithReuseIdentifier: "cell") self.view.addSubview(gridCollectionView) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
89bd14eb1154491a5488f2cb06e303f1
34.755556
184
0.7023
5.107937
false
false
false
false
SuperAwesomeLTD/sa-kws-app-demo-ios
KWSDemo/KWSShadowView.swift
1
544
// // UIView+KWSStyle.swift // KWSDemo // // Created by Gabriel Coman on 22/06/2016. // Copyright © 2016 Gabriel Coman. All rights reserved. // import UIKit import SAUtils class KWSShadowView: UIView { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundColor = UIColor.white layer.masksToBounds = false layer.shadowColor = UIColorFromHex(0x898989).cgColor layer.shadowOffset = CGSize(width: 0, height: 2.5) layer.shadowOpacity = 0.5 } }
gpl-3.0
8680efc44e82735d952ecff023e2b335
21.625
60
0.650092
3.906475
false
false
false
false
goyuanfang/SXSwiftWeibo
103 - swiftWeibo/103 - swiftWeibo/Classes/Tools/SXSwiftJ2M.swift
1
7525
// // SXSwiftJ2M.swift // 105 - SXSwiftJ2M // // Created by 董 尚先 on 15/3/4. // Copyright (c) 2015年 shangxianDante. All rights reserved. // import Foundation @objc protocol J2MProtocol{ /** 自定义的类型映射表 :returns: 返回[属性名:自定义对象名称] */ static func customeClassMapping()->[String:String]? } public class SXSwiftJ2M { /// 创建单例 public static let sharedManager = SXSwiftJ2M() /// MARK:- 使用字典转模型 /** 使用字典转模型 :param: dict 数据字典 :param: cls 模型的类 :returns: 实例化类的对象 */ public func swiftObjWithDict(dict:NSDictionary,cls:AnyClass) ->AnyObject?{ /// 取出模型类字典 let dictInfo = GetAllModelInfo(cls) /// 实例化对象 var obj:AnyObject = cls.alloc() autoreleasepool{ for(k,v) in dictInfo{ if let value:AnyObject = dict[k]{ // println("要设置数值的 \(value) + key \(k)") /// 如果是基本数据类型直接kvc if v.isEmpty && !(value === NSNull()){ // $$$$$ obj.setValue(value, forKey: k) }else { let type = "\(value.classForCoder)" // $$$$$ 取出某一个对象所属的类 // println("自定义对象 \(value) \(k) \(v) 类型是 \(type) ") if type == "NSDictionary" { // value 是字典-> 将 value 的字典转换成 Info 的对象 if let subObj:AnyObject? = swiftObjWithDict(value as!NSDictionary, cls: NSClassFromString(v)){ obj.setValue(subObj, forKey: k) } } else if type == "NSArray" { // value 是数组 // 如果是数组如何处理? 遍历数组,继续处理数组中的字典 if let subObj:AnyObject? = swiftObjWithArray(value as!NSArray, cls: NSClassFromString(v)){ obj.setValue(subObj, forKey: k) } } } } } } // println(dictInfo) return obj } /// MARK:- 将数组转化成模型数组 /** 将数组转化成模型数组 :param: array 数组 :param: cls 模型类 :returns: 模型数组 */ public func swiftObjWithArray(array:NSArray,cls:AnyClass) ->AnyObject?{ var result = [AnyObject]() for value in array{ let type = "\(value.classForCoder)" // $$$$$ if type == "NSDictionary"{ if let subObj:AnyObject = swiftObjWithDict(value as! NSDictionary, cls: cls){ result.append(subObj) // $$$$$ } } else if type == "NSArray"{ if let subObj:AnyObject = swiftObjWithArray(value as! NSArray, cls: cls){ result.append(subObj) } } } return result } /// 缓存字典 var modleCache = [String:[String:String]]() // $$$$$ /// MARK:- 获取模型类的所有信息 /** 获取模型类的所有信息 :param: cls 模型类 :returns: 完整信息字典 */ func GetAllModelInfo(cls:AnyClass)->[String:String]{ /// 先判断是否已经被缓存 if let cache = modleCache["\(cls)"]{ // println("\(cls)类已经被缓存") return cache } /// 循环查找父类,但是不会处理NSObject var currentcls:AnyClass = cls /// 定义模型字典 var dictInfo = [String:String]() /// 循环遍历直到NSObject while let parent:AnyClass = currentcls.superclass(){ // $$$$$ dictInfo.merge(GetModelInfo(currentcls)) currentcls = parent } /// 写入缓存 modleCache["\(cls)"] = dictInfo return dictInfo } /// MARK:- 获取给定类的信息 func GetModelInfo(cls:AnyClass) ->[String:String]{ /// 判断是否遵循了协议,一旦遵循协议就是有自定义对象 var mapping:[String : String]? if (cls.respondsToSelector("customeClassMapping")){ // $$$$$ /// 得到属性字典 mapping = cls.customeClassMapping() // println(mapping!) } /// 必须用UInt32否则不能调用 var count:UInt32 = 0 let ivars = class_copyIvarList(cls, &count) println("有 \(count) 个属性") var dictInfo = [String:String]() for i in 0..<count{ /// 必须再强转成Int否则不能用来做下标 let ivar = ivars[Int(i)] let cname = ivar_getName(ivar) let name = String.fromCString(cname)! /// 去属性字典中取,如果没有就使用后面的变量 let type = mapping?[name] ?? "" // $$$$$ dictInfo[name] = type } /// 释放 free(ivars) return dictInfo } /// MARK:- 加载属性列表 func loadProperties(cls:AnyClass){ /// 必须用UInt32否则不能调用 var count:UInt32 = 0 let properties = class_copyPropertyList(cls, &count) println("有 \(count) 个属性") for i in 0..<count{ /// 必须再强转成Int否则不能用来做下标 let property = properties[Int(i)] let cname = property_getName(property) let name = String.fromCString(cname)! let ctype = property_getAttributes(property) let type = String.fromCString(ctype)! println(name + "--------" + type) } /// 释放 free(properties) /// 基本数据类型不对,swift数组和字符串不对 } /// MARK:- 加载成员变量 func loadIVars(cls:AnyClass){ /// 必须用UInt32否则不能调用 var count:UInt32 = 0 let ivars = class_copyIvarList(cls, &count) println("有 \(count) 个属性") for i in 0..<count{ /// 必须再强转成Int否则不能用来做下标 let ivar = ivars[Int(i)] let cname = ivar_getName(ivar) let name = String.fromCString(cname)! let ctype = ivar_getTypeEncoding(ivar) let type = String.fromCString(ctype)! println(name + "--------" + type) } /// 释放 free(ivars) /// 能够检测通过 } } /// 相当于添加分类,泛型,拼接字典 extension Dictionary{ mutating func merge<K,V>(dict:[K:V]){ for (k,v) in dict{ self.updateValue(v as! Value, forKey: k as! Key) } } }
mit
200bf5731e87ea21cca21e078b6838a3
24.747082
118
0.448844
4.423128
false
false
false
false
HassanEskandari/Eureka
Source/Rows/SuggestionRow/SuggestionTableCell.swift
1
3360
// // SuggestionTableCell.swift // // Adapted from Mathias Claassen 4/14/16 by Hélène Martin 8/11/16 // // import Foundation import UIKit open class SuggestionTableCell<T: SuggestionValue, TableViewCell: UITableViewCell>: SuggestionCell<T>, UITableViewDelegate, UITableViewDataSource where TableViewCell: EurekaSuggestionTableViewCell, TableViewCell.S == T { /// callback that can be used to customize the table cell. public var customizeTableViewCell: ((TableViewCell) -> Void)? public var tableView: UITableView? required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func setup() { super.setup() tableView = UITableView(frame: CGRect.zero, style: .plain) tableView?.autoresizingMask = .flexibleHeight tableView?.isHidden = true tableView?.delegate = self tableView?.dataSource = self tableView?.backgroundColor = UIColor.white tableView?.register(TableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier) } open func showTableView() { if let controller = formViewController() { if tableView?.superview == nil { controller.view.addSubview(tableView!) } let frame = controller.tableView?.convert(self.frame, to: controller.view) ?? self.frame tableView?.frame = CGRect(x: 0, y: frame.origin.y + frame.height, width: contentView.frame.width, height: 44*5) tableView?.isHidden = false } } open func hideTableView() { tableView?.isHidden = true } override func reload() { tableView?.reloadData() } override func setSuggestions(_ string: String) { suggestions = (row as? _SuggestionRow<SuggestionTableCell>)?.filterFunction(string) reload() } open override func textFieldDidChange(_ textField: UITextField) { super.textFieldDidChange(textField) if textField.text?.isEmpty == false { showTableView() } } open override func textFieldDidEndEditing(_ textField: UITextField) { super.textFieldDidEndEditing(textField) hideTableView() } //MARK: UITableViewDelegate and Datasource open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return suggestions?.count ?? 0 } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! TableViewCell if let prediction = suggestions?[(indexPath as NSIndexPath).row] { cell.setupForValue(prediction) } customizeTableViewCell?(cell) return cell } open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let prediction = suggestions?[(indexPath as NSIndexPath).row] { row.value = prediction _ = cellResignFirstResponder() } } open func numberOfSections(in tableView: UITableView) -> Int { return 1 } }
mit
975e137a5d2498e6a16df67a650dc54d
33.618557
220
0.657236
5.288189
false
false
false
false
jkusnier/WorkoutMerge
WorkoutMerge/SubmitWorkoutTableViewCell.swift
1
1889
// // SubmitWorkoutTableViewCell.swift // WorkoutMerge // // Created by Jason Kusnier on 5/30/15. // Copyright (c) 2015 Jason Kusnier. All rights reserved. // import UIKit class SubmitWorkoutTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subtitleLabel: UILabel! @IBOutlet weak var sendDataSwitch: UISwitch! @IBOutlet weak var textField: UITextField! var switchChangedCallback: ((Bool) -> ())? var isDisabled = false override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } @IBAction func switchChanged(sender: AnyObject) { if let switchChangedCallback = self.switchChangedCallback { if let uiSwitch = sender as? UISwitch { self.titleLabel.enabled = uiSwitch.on self.subtitleLabel.enabled = uiSwitch.on switchChangedCallback(uiSwitch.on) } } } func setSwitchState(switchState: Bool) { if let sendDataSwitch = self.sendDataSwitch { sendDataSwitch.on = switchState } if let titleLabel = self.titleLabel { titleLabel.enabled = switchState } if let subtitleLabel = self.subtitleLabel { subtitleLabel.enabled = switchState } } func setDisabled(disabledState: Bool) { self.isDisabled = disabledState if let sendDataSwitch = self.sendDataSwitch { sendDataSwitch.enabled = !disabledState } if let titleLabel = self.titleLabel { titleLabel.enabled = !disabledState } if let subtitleLabel = self.subtitleLabel { subtitleLabel.enabled = !disabledState } } }
mit
3d9e40af60d3afcc6932c73da4d996a3
28.061538
79
0.623081
5.023936
false
false
false
false
isnine/HutHelper-Open
HutHelper/SwiftApp/Extension + Const/Util + Math.swift
1
3704
// // Util + Math.swift // HutHelperSwift // // Created by 张驰 on 2020/1/13. // Copyright © 2020 张驰. All rights reserved. // import Foundation /** 开学 年 月 日*/ let startYear = 2020 let startMonth = 2 let startDay = 24 /** 今天是第今年第几天 */ func getNumDay(year: Int, mouth: Int, day: Int) -> Int { let mouths = [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] var sum = 0 for i in 0..<mouth-1 { sum += mouths[i] } if mouth > 2 { if ( year % 4 == 0 && year % 100 != 0) || year % 400 == 0 { sum += 29 } else { sum += 28 } } return sum + day } /** 返回当前是本学期第几周 */ func getNumWeek(nowYear: Int, nowMouth: Int, nowDay: Int) -> Int { var ans = 0 if nowYear != startYear { ans = getNumDay(year: nowYear, mouth: nowMouth, day: nowDay) - getNumDay(year: nowYear, mouth: 1, day: 1) + 1 ans += getNumDay(year: nowYear-1, mouth: 12, day: 31) - getNumDay(year: startYear, mouth: startMonth, day: startDay) + 1 } else { ans = getNumDay(year: nowYear, mouth: nowMouth, day: nowDay) - getNumDay(year: startYear, mouth: startMonth, day: startDay) + 1 } if (ans + 6) / 7 <= 0 { return 1 } return (ans + 6) / 7 } // MARK: - 获取日期各种值 extension Date { // MARK: 年 func years() -> Int { let calendar = NSCalendar.current let com = calendar.dateComponents([.year, .month, .day], from: self) return com.year! } // MARK: 月 func months() -> Int { let calendar = NSCalendar.current let com = calendar.dateComponents([.year, .month, .day], from: self) return com.month! } // MARK: 日 func days() -> Int { let calendar = NSCalendar.current let com = calendar.dateComponents([.year, .month, .day], from: self) return com.day! } /** 获取当前星期几 */ func getWeekDay() -> String { let interval = Int(self.timeIntervalSince1970) let days = Int(interval/86400) // 24*60*60 let weekday = ((days + 4)%7+7)%7 let weekDays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"] return weekDays[weekday] } // MARK: 当月天数 func countOfDaysInMonth() -> Int { let calendar = Calendar(identifier: Calendar.Identifier.gregorian) let range = (calendar as NSCalendar?)?.range(of: NSCalendar.Unit.day, in: NSCalendar.Unit.month, for: self) return (range?.length)! } // MARK: 当月第一天是星期几 func firstWeekDay() -> Int { //1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat. let calendar = Calendar(identifier: Calendar.Identifier.gregorian) let firstWeekDay = (calendar as NSCalendar?)?.ordinality(of: NSCalendar.Unit.weekday, in: NSCalendar.Unit.weekOfMonth, for: self) return firstWeekDay! - 1 } // MARK: - 日期的一些比较 //是否是今天 func isToday() -> Bool { let calendar = NSCalendar.current let com = calendar.dateComponents([.year, .month, .day], from: self) let comNow = calendar.dateComponents([.year, .month, .day], from: Date()) return com.year == comNow.year && com.month == comNow.month && com.day == comNow.day } //是否是这个月 func isThisMonth() -> Bool { let calendar = NSCalendar.current let com = calendar.dateComponents([.year, .month, .day], from: self) let comNow = calendar.dateComponents([.year, .month, .day], from: Date()) return com.year == comNow.year && com.month == comNow.month } }
lgpl-2.1
5228824ce3d68ff8ce8989b101231fd8
30.594595
137
0.575706
3.391683
false
false
false
false
MrMYHuang/taa
iOS/Shared/WebViewController.swift
1
5281
// // ViewController.swift // cbetar2 // // Created by Roger Huang on 2020/12/24. // import SwiftUI import UIKit import WebKit import SnapKit struct WebViewControllerWrap: UIViewControllerRepresentable { func makeUIViewController(context: Context) -> some UIViewController { return WebViewController() } func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) { } } class WebViewController: UIViewController { let jsonUriPrefix = "data:text/json;charset=utf-8," #if DEBUG let baseURL = URL(string: "http://localhost:3000/taa")! #else let baseURL = URL(string: "https://myhpwa.github.io/taa")! #endif let contentController = WKUserContentController(); let swiftCallbackHandler = "swiftCallbackHandler" lazy var webView: WKWebView = { let preferences = WKPreferences() preferences.setValue(true, forKey: "allowFileAccessFromFileURLs") let configuration = WKWebViewConfiguration() configuration.preferences = preferences configuration.defaultWebpagePreferences.allowsContentJavaScript = true configuration.limitsNavigationsToAppBoundDomains = true configuration.userContentController = contentController let webView = WKWebView(frame: .zero, configuration: configuration) webView.navigationDelegate = self webView.scrollView.contentInsetAdjustmentBehavior = .never let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache]) let date = NSDate(timeIntervalSince1970: 0) WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set<String>, modifiedSince: date as Date, completionHandler:{ }) return webView }() override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidLoad() { super.viewDidLoad() contentController.add(self, name: swiftCallbackHandler) view.addSubview(webView) webView.snp.makeConstraints { //$0.edges.equalToSuperview() $0.top.equalTo(self.view.safeAreaLayoutGuide.snp.topMargin) $0.leading.trailing.bottom.equalToSuperview() } webView.load(URLRequest(url: baseURL)) } var fileURL: URL? private func saveText(text: String, file: String) { if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { fileURL = dir.appendingPathComponent(file) do { try text.write(to: fileURL!, atomically: false, encoding: .utf8) let controller = UIDocumentPickerViewController(forExporting: [fileURL!]) controller.delegate = self present(controller, animated: true) } catch {/* error handling here */} } } } extension WebViewController: UIDocumentPickerDelegate { func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { try? FileManager.default.removeItem(at: fileURL! ) } } extension WebViewController: WKScriptMessageHandler { func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { guard let dict = message.body as? Dictionary<String, Any> else { return } guard let event = dict["event"] as? String else { return } if(event == "copy") { let text = dict["text"] as? String ?? "" UIPasteboard.general.string = text } } } extension WebViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { if navigationAction.navigationType == .linkActivated { if let url = navigationAction.request.url { if url.absoluteString.contains(jsonUriPrefix) { if let dataStr = url.absoluteString.replacingOccurrences(of: jsonUriPrefix, with: "").removingPercentEncoding { saveText(text: dataStr, file: "Settings.json") decisionHandler(.cancel) return } } else if let host = url.host, !host.hasPrefix(baseURL.host!), UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url) decisionHandler(.cancel) return } } } decisionHandler(.allow) } func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard let serverTrust = challenge.protectionSpace.serverTrust else { completionHandler(.cancelAuthenticationChallenge, nil) return } let exceptions = SecTrustCopyExceptions(serverTrust) SecTrustSetExceptions(serverTrust, exceptions) completionHandler(.useCredential, URLCredential(trust: serverTrust)); } }
mit
cbb7cd2d171fdeba8428dc54a32c6c32
37.830882
182
0.655368
5.46122
false
true
false
false
chicio/Exploring-SceneKit
ExploringSceneKit/Model/Scenes/PhysicallyBasedRendering/PhysicallyBasedLight.swift
1
833
// // PhysicallyBasedLight.swift // ExploringSceneKit // // Created by Fabrizio Duroni on 25.08.17. // import SceneKit class PhysicallyBasedLight: Light { init(lightFeatures: LightFeatures, physicallyBasedLightFeatures: PhysicallyBasedLightFeatures) { super.init(lightFeatures: lightFeatures) set(physicallyBasedLightFeatures: physicallyBasedLightFeatures) activateShadow() } private func set(physicallyBasedLightFeatures: PhysicallyBasedLightFeatures) { node.light?.type = .directional node.light?.intensity = physicallyBasedLightFeatures.lumen node.light?.temperature = physicallyBasedLightFeatures.temperature } private func activateShadow() { node.light?.castsShadow = true node.light?.orthographicScale = 10 } }
mit
b4e4242daf70bf4f2bb4dad944f11c1c
28.75
100
0.710684
4.293814
false
false
false
false
digices-llc/paqure-ios-framework
Paqure/Device/Device.swift
1
4259
// // Device.swift // Paqure // // Created by Linguri Technology on 7/21/16. // Copyright © 2016 Digices. All rights reserved. // import UIKit class Device: NSObject { var id : Int var label: NSString var identifier: NSString var locale : NSString var token : NSString var created : Int var modified : Int var status : Int override init() { self.id = 2 self.label = " " self.identifier = UIDevice.currentDevice().identifierForVendor!.UUIDString self.locale = NSLocale.currentLocale().localeIdentifier self.token = "4c9184f37cff01bcdc32dc486ec36961" self.created = Int(NSTimeInterval(NSTimeIntervalSince1970)) self.modified = Int(NSTimeInterval(NSTimeIntervalSince1970)) self.status = 2 } required init?(coder aDecoder: NSCoder) { self.id = aDecoder.decodeIntegerForKey("id") self.label = aDecoder.decodeObjectForKey("label") as! NSString self.identifier = aDecoder.decodeObjectForKey("identifier") as! NSString self.locale = aDecoder.decodeObjectForKey("locale") as! NSString self.token = aDecoder.decodeObjectForKey("token") as! NSString self.created = aDecoder.decodeIntegerForKey("created") self.modified = aDecoder.decodeIntegerForKey("modified") self.status = aDecoder.decodeIntegerForKey("status") } init(dict: NSDictionary) { // JSON Dictionary returns strings, which will prevent casting to device, so we must convert if let id = dict["id"] as? String { if let idInt = Int(id) { self.id = idInt } else { self.id = 0 } } else { self.id = 0 } if let label = dict["label"] as? String { self.label = label } else { self.label = "" } if let identifier = dict["identifier"] as? String { self.identifier = identifier } else { self.identifier = UIDevice.currentDevice().identifierForVendor!.UUIDString } if let locale = dict["locale"] as? String { self.locale = locale } else { self.locale = NSLocale.currentLocale().localeIdentifier } if let token = dict["token"] as? String { self.token = token } else { self.token = "" } if let created = dict["created"] as? String { if let createdInt = Int(created) { self.created = createdInt } else { self.created = 0 } } else { self.created = 0 } if let modified = dict["modified"] as? String { if let modifiedInt = Int(modified) { self.modified = modifiedInt } else { self.modified = 0 } } else { self.modified = 0 } if let status = dict["status"] as? String { if let statusInt = Int(status) { self.status = statusInt } else { self.status = 2 } } else { self.status = 2 } } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeInteger(self.id, forKey: "id") aCoder.encodeObject(self.label, forKey: "label") aCoder.encodeObject(self.identifier, forKey: "identifier") aCoder.encodeObject(self.locale, forKey: "locale") aCoder.encodeObject(self.token, forKey: "token") aCoder.encodeInteger(self.created, forKey: "created") aCoder.encodeInteger(self.modified, forKey: "modified") aCoder.encodeInteger(self.status, forKey: "status") } func encodedPostBody() -> NSData { let body = self.getSuffix() return body.dataUsingEncoding(NSUTF8StringEncoding)! as NSData } func getSuffix() -> String { return "id=\(self.id)&label=\(self.label)&identifier=\(self.identifier)&locale=\(self.locale)&token=\(self.token)&created=\(self.created)&modified=\(self.modified)&status=\(self.status)" } }
bsd-3-clause
2bead2a6f4b30390104c24529b43941f
31.015038
194
0.558478
4.689427
false
false
false
false
jonnguy/HSTracker
HSTracker/UIs/StatsManager/StatsTab.swift
1
6694
// // StatsTab.swift // HSTracker // // Created by Matthew Welborn on 6/25/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Cocoa class StatsTab: NSViewController { @IBOutlet weak var modePicker: NSPopUpButton! @IBOutlet weak var statsTable: NSTableView! @IBOutlet weak var seasonPicker: NSPopUpButton! var deck: Deck? var statsTableItems = [StatsTableRow]() let modePickerItems: [GameMode] = [.all, .ranked, .casual, .brawl, .arena, .friendly, .practice] var observer: NSObjectProtocol? override func viewDidLoad() { super.viewDidLoad() for mode in modePickerItems { modePicker.addItem(withTitle: mode.userFacingName) } modePicker.selectItem(at: modePickerItems.index(of: .ranked)!) seasonPicker.addItem(withTitle: NSLocalizedString("all_seasons", comment: "")) if let deck = self.deck { let seasons = Array(deck.gameStats).compactMap({ $0.season }) .sorted().reversed() for season in seasons { seasonPicker.addItem( withTitle: String(format: NSLocalizedString("season", comment: ""), NSNumber(value: season as Int))) seasonPicker.lastItem?.tag = season } } seasonPicker.selectItem(at: 0) update() statsTable.delegate = self statsTable.dataSource = self let descClass = NSSortDescriptor(key: "opponentClassName", ascending: true) let descRecord = NSSortDescriptor(key: "totalGames", ascending: false) let descWinrate = NSSortDescriptor(key: "winRateNumber", ascending: false) let descCI = NSSortDescriptor(key: "confidenceWindow", ascending: true) statsTable.tableColumns[0].sortDescriptorPrototype = descClass statsTable.tableColumns[1].sortDescriptorPrototype = descRecord statsTable.tableColumns[2].sortDescriptorPrototype = descWinrate statsTable.tableColumns[3].sortDescriptorPrototype = descCI // swiftlint:disable line_length statsTable.tableColumns[3].headerToolTip = NSLocalizedString("It is 90% certain that the true winrate falls between these values.", comment: "") // swiftlint:enable line_length // We need to update the display when the // stats change self.observer = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: Events.reload_decks), object: nil, queue: OperationQueue.main) { _ in self.update() } } deinit { if let observer = self.observer { NotificationCenter.default.removeObserver(observer) } } func sortStatsTable() { let sorted = (statsTableItems as NSArray) .sortedArray(using: statsTable.sortDescriptors) if let _statsTableItems = sorted as? [StatsTableRow] { statsTableItems = _statsTableItems } } func update() { if let deck = self.deck { var index = modePicker.indexOfSelectedItem if index == -1 { // In case somehow nothing is selected modePicker.selectItem(at: modePickerItems.index(of: .ranked)!) index = modePicker.indexOfSelectedItem } var season = seasonPicker.indexOfSelectedItem if season == -1 { season = 0 seasonPicker.selectItem(at: 0) } if season > 0 { season = seasonPicker.selectedTag() } DispatchQueue.main.async { self.statsTableItems = StatsHelper.getStatsUITableData(deck: deck, mode: self.modePickerItems[index], season: season) self.sortStatsTable() self.statsTable.reloadData() } } else { DispatchQueue.main.async { self.statsTableItems = [] self.statsTable.reloadData() } } } @IBAction func modeSelected(_ sender: AnyObject) { update() } @IBAction func changeSeason(_ sender: AnyObject) { update() } } extension StatsTab: NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { if tableView == statsTable { return statsTableItems.count } else { return 0 } } } extension StatsTab: NSTableViewDelegate { func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { if tableView != statsTable { return nil } var image: NSImage? var text: String = "" var cellIdentifier: String = "" var alignment: NSTextAlignment = NSTextAlignment.left let item = statsTableItems[row] if tableColumn == tableView.tableColumns[0] { image = NSImage(named: NSImage.Name(rawValue: item.classIcon)) text = item.opponentClassName alignment = NSTextAlignment.left cellIdentifier = "StatsClassCellID" } else if tableColumn == tableView.tableColumns[1] { text = item.record alignment = NSTextAlignment.right cellIdentifier = "StatsRecordCellID" } else if tableColumn == tableView.tableColumns[2] { text = item.winRate alignment = NSTextAlignment.right cellIdentifier = "StatsWinRateCellID" } else if tableColumn == tableView.tableColumns[3] { text = item.confidenceInterval alignment = NSTextAlignment.right cellIdentifier = "StatsCICellID" } if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier), owner: nil) as? NSTableCellView { cell.textField?.stringValue = text cell.imageView?.image = image ?? nil cell.textField?.alignment = alignment return cell } return nil } func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) { if tableView == statsTable { DispatchQueue.main.async { self.sortStatsTable() self.statsTable.reloadData() } } } }
mit
b45f9a68064422c859d1d8e1b85180da
34.041885
171
0.579561
5.249412
false
false
false
false
cpascoli/WeatherHype
WeatherHype/Classes/Utils/Utils.swift
1
1120
// // Utils.swift // WeatherHype // // Created by Carlo Pascoli on 28/09/2016. // Copyright © 2016 Carlo Pascoli. All rights reserved. // import UIKit extension Date { func dayOfWeek() -> String { let weekdays = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Satudrday" ] let comp:DateComponents = Calendar.current.dateComponents([.weekday], from: self) return weekdays[comp.weekday!-1] } } extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(hex:Int) { self.init(red:(hex >> 16) & 0xff, green:(hex >> 8) & 0xff, blue:hex & 0xff) } }
apache-2.0
efb19ab5c32b33cd830b817d4c0ee10d
24.431818
116
0.529937
3.780405
false
false
false
false
DanielFulton/ImageLibraryTests
Pods/MapleBacon/Library/MapleBacon/MapleBacon/ImageManager.swift
3
3077
// // Copyright (c) 2015 Zalando SE. All rights reserved. // import UIKit public class ImageManager { public static let sharedManager = ImageManager() private let downloadQueue = NSOperationQueue() private var downloadsInProgress = [NSURL: ImageDownloadOperation]() deinit { downloadQueue.cancelAllOperations() } public func downloadImageAtURL(url: NSURL, cacheScaled: Bool, imageView: UIImageView?, storage: Storage = MapleBaconStorage.sharedStorage, completion: ImageDownloaderCompletion?) -> ImageDownloadOperation? { if let cachedImage = storage.image(forKey: url.absoluteString) { completion?(ImageInstance(image: cachedImage, state: .Cached, url: url), nil) } else { if downloadsInProgress[url] == nil { let downloadOperation = ImageDownloadOperation(imageURL: url) downloadOperation.qualityOfService = .UserInitiated downloadOperation.completionHandler = downloadHandlerWithStorage(url, cacheScaled: cacheScaled, imageView: imageView, storage: storage, completion: completion) downloadsInProgress[url] = downloadOperation downloadQueue.addOperation(downloadOperation) return downloadOperation } else { completion?(ImageInstance(image: nil, state: .Downloading, url: nil), nil) delay(0.1) { self.downloadImageAtURL(url, cacheScaled: cacheScaled, imageView: imageView, storage: storage, completion: completion) } } } return nil } private func downloadHandlerWithStorage(url: NSURL, cacheScaled: Bool, imageView: UIImageView?, storage: Storage, completion: ImageDownloaderCompletion?) -> ImageDownloaderCompletion { return { [weak self] (imageInstance, _) in self?.downloadsInProgress[url] = nil if let newImage = imageInstance?.image { if cacheScaled && imageView != nil && newImage.images == nil { self?.resizeAndStoreImage(newImage, imageView: imageView!, storage: storage, key: url.absoluteString) } else if let imageData = imageInstance?.data { storage.storeImage(newImage, data: imageData, forKey: url.absoluteString) } completion?(ImageInstance(image: newImage, state: .New, url: imageInstance?.url), nil) } } } private func resizeAndStoreImage(image: UIImage, imageView: UIImageView, storage: Storage, key: String) { Resizer.resizeImage(image, contentMode: imageView.contentMode, toSize: imageView.bounds.size, interpolationQuality: .Default) { resizedImage in storage.storeImage(resizedImage, data: nil, forKey: key) } } public func hasDownloadsInProgress() -> Bool { return !downloadsInProgress.isEmpty } }
mit
bf3961a6f927157eae23d3f97bf570a1
43.594203
188
0.624959
5.426808
false
false
false
false
LeonClover/DouYu
DouYuZB/DouYuZB/Classes/Home/Controller/FunnyViewController.swift
1
953
// // FunnyViewController.swift // DouYuZB // // Created by Leon on 2017/8/28. // Copyright © 2017年 pingan. All rights reserved. // import UIKit private let kTopMargin: CGFloat = 8.0 class FunnyViewController: BaseAnchorViewController { //MARK: 懒加载viewModel对象 fileprivate lazy var funnyVM: FunnyViewModel = FunnyViewModel() } extension FunnyViewController{ override func setupUI() { super.setupUI() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.headerReferenceSize = CGSize.zero collectionView.contentInset = UIEdgeInsetsMake(kTopMargin, 0.0, 0.0, 0.0) } } extension FunnyViewController { override func loadData() { baseVM = funnyVM funnyVM.loadFunnyData { self.collectionView.reloadData() //MARK: 数据请求完成 self.loadDataFinished() } } }
mit
c4d371b9146d4aa031122b32bcc6cb1b
22.794872
87
0.658405
4.884211
false
false
false
false
johnno1962/Dynamo
Sources/Proxies.swift
1
11732
// // Proxies.swift // Dynamo // // Created by John Holdsworth on 20/06/2015. // Copyright (c) 2015 John Holdsworth. All rights reserved. // // $Id: //depot/Dynamo/Sources/Proxies.swift#16 $ // // Repo: https://github.com/johnno1962/Dynamo // import Foundation #if os(Linux) import Dispatch import Glibc #endif // MARK: Proxy Swiftlets /** Swiftlet to allow a DynamoWebServer to act as a http: protocol proxy on the same port. */ open class ProxySwiftlet: _NSObject_, DynamoSwiftlet { var logger: ((String) -> ())? /** default initialiser with optional "tracer" for all traffic */ @objc public init( logger: ((String) -> ())? = nil ) { self.logger = logger } /** process as proxy request if request path has "host" */ open func present( httpClient: DynamoHTTPConnection ) -> DynamoProcessed { if httpClient.url.host == dummyBase.host { return .notProcessed } if let host = httpClient.url.host { if let remoteConnection = DynamoHTTPConnection( url: httpClient.url ) { var remotePath = httpClient.url.path == "" ? "/" : httpClient.url.path if !remotePath.hasSuffix( "/" ) && (httpClient.path.hasSuffix( "/" ) || httpClient.path.range( of: "/?" ) != nil) { remotePath += "/" } if let query = httpClient.url.query { remotePath += "?"+query } remoteConnection.rawPrint( "\(httpClient.method) \(remotePath) \(httpClient.version)\r\n" ) for (name, value) in httpClient.requestHeaders { remoteConnection.rawPrint( "\(name): \(value)\r\n" ) } remoteConnection.rawPrint( "\r\n" ) if httpClient.readBuffer.count != 0 { httpClient.readBuffer.withUnsafeBytes({ (bytes: UnsafePointer<Int8>) -> Void in remoteConnection.write( buffer: bytes, count: httpClient.readBuffer.count ) }) httpClient.readBuffer.replaceSubrange( 0..<httpClient.readBuffer.count, with: Data() ) } remoteConnection.flush() DynamoSelector.relay( host, from: httpClient, to: remoteConnection, logger ) } else { httpClient.sendResponse( resp: .ok( html: "Unable to resolve host \(host)" ) ) } } return .processed } } /** Swiftlet to allow a DynamoWebServer to act as a https: SSL connection protocol proxy on the same port. This must be come before the DynamoProxySwiftlet in the list of swiftlets for the server for both to work. */ open class SSLProxySwiftlet: ProxySwiftlet { /** connect socket through to destination SSL server for method "CONNECT" */ open override func present( httpClient: DynamoHTTPConnection ) -> DynamoProcessed { if httpClient.method == "CONNECT" { if let urlForDestination = URL( string: "https://\(httpClient.path)" ), let remoteConnection = DynamoHTTPConnection( url: urlForDestination ) { httpClient.rawPrint( "HTTP/1.0 200 Connection established\r\nProxy-agent: Dynamo/1.0\r\n\r\n" ) httpClient.flush() DynamoSelector.relay( httpClient.path, from: httpClient, to: remoteConnection, logger ) } return .processed } return .notProcessed } } // MARK: "select()" based fd switching var dynamoSelector: DynamoSelector? private let selectBitsPerFlag: Int32 = 32 private let selectShift: Int32 = 5 private let selectBitMask: Int32 = (1<<selectShift)-1 private var dynamoQueueLock = NSLock() private let dynamoProxyQueue = DispatchQueue( label: "DynamoProxyThread", attributes: DispatchQueue.Attributes.concurrent ) /** polling interval for proxy relay */ public var dynamoPollingUsec: Int32 = 100*1000 private var maxReadAhead = 10*1024*1024 private var maxPacket = 2*1024 func FD_ZERO( _ flags: UnsafeMutablePointer<Int32> ) { memset( flags, 0, MemoryLayout<fd_set>.size ) } func FD_CLR( _ fd: Int32, _ flags: UnsafeMutablePointer<Int32> ) { let set = flags + Int( fd>>selectShift ) set.pointee &= ~(1<<(fd&selectBitMask)) } func FD_SET( _ fd: Int32, _ flags: UnsafeMutablePointer<Int32> ) { let set = flags + Int( fd>>selectShift ) set.pointee |= 1<<(fd&selectBitMask) } func FD_ISSET( _ fd: Int32, _ flags: UnsafeMutablePointer<Int32> ) -> Bool { let set = flags + Int( fd>>selectShift ) return (set.pointee & (1<<(fd&selectBitMask))) != 0 } //#if !os(Linux) //@asmname("fcntl") //func fcntl( filedesc: Int32, _ command: Int32, _ arg: Int32 ) -> Int32 //#endif /** More efficient than relying on operating system to handle many reads on different threads when proxying */ final class DynamoSelector { var readMap = [Int32:DynamoHTTPConnection]() var writeMap = [Int32:DynamoHTTPConnection]() var queue = [(String,DynamoHTTPConnection,DynamoHTTPConnection)]() class func relay( _ label: String, from: DynamoHTTPConnection, to: DynamoHTTPConnection, _ logger: ((String) -> ())? ) { dynamoQueueLock.lock() if dynamoSelector == nil { dynamoSelector = DynamoSelector() dynamoProxyQueue.async(execute: { dynamoSelector!.selectLoop( logger ) } ) } dynamoSelector!.queue.append( (label,from,to) ) dynamoQueueLock.unlock() } func selectLoop( _ logger: ((String) -> Void)? = nil ) { let readFlags = malloc( MemoryLayout<fd_set>.size ).assumingMemoryBound(to: Int32.self) let writeFlags = malloc( MemoryLayout<fd_set>.size ).assumingMemoryBound(to: Int32.self) let errorFlags = malloc( MemoryLayout<fd_set>.size ).assumingMemoryBound(to: Int32.self) var buffer = [UInt8](repeating: 0, count: maxPacket) var timeout = timeval() while true { dynamoQueueLock.lock() while queue.count != 0 { let (label,from,to) = queue.remove(at: 0) to.label = "-> \(label)" from.label = "<- \(label)" // #if !os(Linux) // if label == "surrogate" { // var flags = fcntl( to.clientSocket, F_GETFL, 0 ) // flags |= O_NONBLOCK // fcntl( to.clientSocket, F_SETFL, flags ) // } // #endif readMap[from.clientSocket] = to readMap[to.clientSocket] = from } dynamoQueueLock.unlock() FD_ZERO( readFlags ) FD_ZERO( writeFlags ) FD_ZERO( errorFlags ) var maxfd: Int32 = -1, fdcount = 0 for (fd,writer) in readMap { if writer.readBuffer.count < maxReadAhead { FD_SET( fd, readFlags ) } FD_SET( fd, errorFlags ) if maxfd < fd { maxfd = fd } fdcount += 1 } var hasWrite = false for (fd,_) in writeMap { FD_SET( fd, writeFlags ) FD_SET( fd, errorFlags ) if maxfd < fd { maxfd = fd } hasWrite = true } timeout.tv_sec = 0 #if os(Linux) timeout.tv_usec = Int(dynamoPollingUsec) #else timeout.tv_usec = dynamoPollingUsec #endif func fd_set_ptr( _ p: UnsafeMutablePointer<Int32> ) -> UnsafeMutablePointer<fd_set> { return p.withMemoryRebound(to: fd_set.self, capacity: 1) { $0 } } if select( maxfd+1, fd_set_ptr( readFlags ), hasWrite ? fd_set_ptr( writeFlags ) : nil, fd_set_ptr( errorFlags ), &timeout ) < 0 { timeout.tv_sec = 0 timeout.tv_usec = 0 dynamoStrerror( "Select error \(readMap) \(writeMap)" ) for (fd,_) in readMap { FD_ZERO( readFlags ) FD_SET( fd, readFlags ) if select( fd+1, fd_set_ptr( readFlags ), nil, nil, &timeout ) < 0 { dynamoLog( "Closing reader: \(fd)" ) close( fd ) } } for (fd,writer) in writeMap { FD_ZERO( readFlags ) FD_SET( fd, readFlags ) if select( fd+1, fd_set_ptr( readFlags ), nil, nil, &timeout ) < 0 { writeMap.removeValue( forKey: writer.clientSocket ) dynamoLog( "Closing writer: \(fd)" ) close( fd ) } } continue } if maxfd < 0 { continue } for readFD in 0...maxfd { if let writer = readMap[readFD], let reader = readMap[writer.clientSocket], FD_ISSET( readFD, readFlags ) || writer.readTotal != 0 && reader.hasBytesAvailable { if let bytesRead = reader.receive( buffer: &buffer, count: buffer.count ) { logger?( "\(writer.label) \(writer.readTotal)+\(writer.readBuffer.count)+\(bytesRead) bytes (\(readFD)/\(readMap.count)/\(fdcount))" ) if bytesRead <= 0 { close( readFD ) readMap[readFD] = nil } else { writer.readBuffer.append( buffer, count: bytesRead ) writer.readTotal += bytesRead } if writer.readBuffer.count != 0 { writeMap[writer.clientSocket] = writer } } } } for (writeFD,writer) in writeMap { if FD_ISSET( writeFD, writeFlags ) { writer.readBuffer.withUnsafeBytes({ (bytes: UnsafePointer<Int8>) in if let bytesWritten = writer.forward( buffer: bytes, count: writer.readBuffer.count ) { if bytesWritten <= 0 { writeMap.removeValue( forKey: writer.clientSocket ) dynamoLog( "Short write on relay \(writer.label)" ) close( writeFD ) } else { writer.readBuffer.replaceSubrange( 0..<bytesWritten, with: Data() ) } if writer.readBuffer.count == 0 { writeMap.removeValue( forKey: writer.clientSocket ) } } }) } } for errorFD in 0..<maxfd { if FD_ISSET( errorFD, errorFlags ) { writeMap.removeValue( forKey: errorFD ) dynamoLog( "ERROR from select on relay" ) close( errorFD ) } } } } fileprivate func close( _ fd: Int32 ) { if let writer = readMap[fd] { readMap.removeValue( forKey: writer.clientSocket ) } readMap.removeValue( forKey: fd ) } }
mit
489a9a70934cfc055cabca2f8e414b8e
34.231231
158
0.514661
4.452372
false
false
false
false
mathewsheets/SwiftLearningAssignments
Todo_Assignment_4/TodoApi/TodoApi/TodoModel.swift
2
1774
import Foundation public class TodoModel: CustomStringConvertible { public var id: String? public var title: String? public var body: String? public var priority: Int? public var done: Bool? public init() { } public init(dictionary: [String:AnyObject]) { id = dictionary["id"] as? String title = dictionary["title"] as? String body = dictionary["body"] as? String priority = dictionary["priority"] as? Int done = dictionary["done"] as? Bool } public var description: String { return "[id: \(id ?? ""), title: \(title ?? ""), body: \(body ?? ""), priority: \(priority ?? -1), done: \(done ?? false)]" } public var asDictionary: [String:AnyObject] { var dictionary = [String:AnyObject]() dictionary["id"] = id as AnyObject? dictionary["title"] = title as AnyObject? dictionary["body"] = body as AnyObject? dictionary["priority"] = priority as AnyObject? dictionary["done"] = done as AnyObject? return dictionary } } extension TodoModel: Equatable { public static func ==(lhs: TodoModel, rhs: TodoModel) -> Bool { return lhs.description == rhs.description } } extension TodoModel: Hashable { public var hashValue: Int { return description.hashValue } } extension Array where Element: TodoModel { public var asDictionary: [[String:AnyObject]] { var dictionaries = [[String:AnyObject]]() for element in self { dictionaries.append(element.asDictionary) } return dictionaries } }
mit
49780a06d63ab608b048062a28dd2764
23.30137
131
0.559752
4.955307
false
false
false
false
hulinSun/Better
better/Pods/ObjectMapper/Sources/ImmutableMappable.swift
12
11312
// // ImmutableMappble.swift // ObjectMapper // // Created by Suyeol Jeon on 23/09/2016. // // The MIT License (MIT) // // Copyright (c) 2014-2016 Hearst // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. public protocol ImmutableMappable: BaseMappable { init(map: Map) throws } public extension ImmutableMappable { /// Implement this method to support object -> JSON transform. public func mapping(map: Map) {} /// Initializes object from a JSON String public init(JSONString: String, context: MapContext? = nil) throws { self = try Mapper(context: context).map(JSONString: JSONString) } /// Initializes object from a JSON Dictionary public init(JSON: [String: Any], context: MapContext? = nil) throws { self = try Mapper(context: context).map(JSON: JSON) } /// Initializes object from a JSONObject public init(JSONObject: Any, context: MapContext? = nil) throws { self = try Mapper(context: context).map(JSONObject: JSONObject) } } public extension Map { fileprivate func currentValue(for key: String, nested: Bool? = nil, delimiter: String = ".") -> Any? { let isNested = nested ?? key.contains(delimiter) return self[key, nested: isNested, delimiter: delimiter].currentValue } // MARK: Basic /// Returns a value or throws an error. public func value<T>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let value = currentValue as? T else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '\(T.self)'", file: file, function: function, line: line) } return value } /// Returns a transformed value or throws an error. public func value<Transform: TransformType>(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> Transform.Object { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let value = transform.transformFromJSON(currentValue) else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) } return value } // MARK: BaseMappable /// Returns a `BaseMappable` object or throws an error. public func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let JSONObject = currentValue else { throw MapError(key: key, currentValue: currentValue, reason: "Found unexpected nil value", file: file, function: function, line: line) } return try Mapper<T>().mapOrFail(JSONObject: JSONObject) } // MARK: [BaseMappable] /// Returns a `[BaseMappable]` or throws an error. public func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [T] { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let jsonArray = currentValue as? [Any] else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line) } return try jsonArray.enumerated().map { i, JSONObject -> T in return try Mapper<T>().mapOrFail(JSONObject: JSONObject) } } /// Returns a `[BaseMappable]` using transform or throws an error. public func value<Transform: TransformType>(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [Transform.Object] { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let jsonArray = currentValue as? [Any] else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line) } return try jsonArray.enumerated().map { i, json -> Transform.Object in guard let object = transform.transformFromJSON(json) else { throw MapError(key: "\(key)[\(i)]", currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) } return object } } // MARK: [String: BaseMappable] /// Returns a `[String: BaseMappable]` or throws an error. public func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [String: T] { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let jsonDictionary = currentValue as? [String: Any] else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[String: Any]'", file: file, function: function, line: line) } var value: [String: T] = [:] for (key, json) in jsonDictionary { value[key] = try Mapper<T>().mapOrFail(JSONObject: json) } return value } /// Returns a `[String: BaseMappable]` using transform or throws an error. public func value<Transform: TransformType>(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [String: Transform.Object] { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let jsonDictionary = currentValue as? [String: Any] else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[String: Any]'", file: file, function: function, line: line) } var value: [String: Transform.Object] = [:] for (key, json) in jsonDictionary { guard let object = transform.transformFromJSON(json) else { throw MapError(key: key, currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) } value[key] = object } return value } } public extension Mapper where N: ImmutableMappable { public func map(JSON: [String: Any]) throws -> N { return try self.mapOrFail(JSON: JSON) } public func map(JSONString: String) throws -> N { return try mapOrFail(JSONString: JSONString) } public func map(JSONObject: Any) throws -> N { return try mapOrFail(JSONObject: JSONObject) } // MARK: Array mapping functions public func mapArray(JSONArray: [[String: Any]]) throws -> [N] { return try JSONArray.flatMap(mapOrFail) } public func mapArray(JSONString: String) throws -> [N] { guard let JSONObject = Mapper.parseJSONString(JSONString: JSONString) else { throw MapError(key: nil, currentValue: JSONString, reason: "Cannot convert string into Any'") } return try mapArray(JSONObject: JSONObject) } public func mapArray(JSONObject: Any) throws -> [N] { guard let JSONArray = JSONObject as? [[String: Any]] else { throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[[String: Any]]'") } return try mapArray(JSONArray: JSONArray) } // MARK: Dictionary mapping functions public func mapDictionary(JSONString: String) throws -> [String: N] { guard let JSONObject = Mapper.parseJSONString(JSONString: JSONString) else { throw MapError(key: nil, currentValue: JSONString, reason: "Cannot convert string into Any'") } return try mapDictionary(JSONObject: JSONObject) } public func mapDictionary(JSONObject: Any?) throws -> [String: N] { guard let JSON = JSONObject as? [String: [String: Any]] else { throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: [String: Any]]''") } return try mapDictionary(JSON: JSON) } public func mapDictionary(JSON: [String: [String: Any]]) throws -> [String: N] { return try JSON.filterMap(mapOrFail) } // MARK: Dictinoary of arrays mapping functions public func mapDictionaryOfArrays(JSONObject: Any?) throws -> [String: [N]] { guard let JSON = JSONObject as? [String: [[String: Any]]] else { throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: [String: Any]]''") } return try mapDictionaryOfArrays(JSON: JSON) } public func mapDictionaryOfArrays(JSON: [String: [[String: Any]]]) throws -> [String: [N]] { return try JSON.filterMap { array -> [N] in try mapArray(JSONArray: array) } } // MARK: 2 dimentional array mapping functions public func mapArrayOfArrays(JSONObject: Any?) throws -> [[N]] { guard let JSONArray = JSONObject as? [[[String: Any]]] else { throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[[[String: Any]]]''") } return try JSONArray.map(mapArray) } } internal extension Mapper where N: BaseMappable { internal func mapOrFail(JSON: [String: Any]) throws -> N { let map = Map(mappingType: .fromJSON, JSON: JSON, context: context) // Check if object is ImmutableMappable, if so use ImmutableMappable protocol for mapping if let klass = N.self as? ImmutableMappable.Type, var object = try klass.init(map: map) as? N { object.mapping(map: map) return object } // If not, map the object the standard way guard let value = self.map(JSON: JSON) else { throw MapError(key: nil, currentValue: JSON, reason: "Cannot map to '\(N.self)'") } return value } internal func mapOrFail(JSONString: String) throws -> N { guard let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) else { throw MapError(key: nil, currentValue: JSONString, reason: "Cannot parse into '[String: Any]'") } return try mapOrFail(JSON: JSON) } internal func mapOrFail(JSONObject: Any) throws -> N { guard let JSON = JSONObject as? [String: Any] else { throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: Any]'") } return try mapOrFail(JSON: JSON) } }
mit
567dd882a77f13a9c663858bbed4d1ae
40.896296
256
0.707744
3.799798
false
false
false
false
AnirudhDas/AniruddhaDas.github.io
RedBus/RedBus/Controller/BusesListViewController.swift
1
4846
// // BusesListViewController.swift // RedBus // // Created by Anirudh Das on 8/22/18. // Copyright © 2018 Aniruddha Das. All rights reserved. // import UIKit class BusesListViewController: BaseViewController { @IBOutlet weak var busListTblView: UITableView! @IBOutlet weak var spinner: UIActivityIndicatorView! @IBOutlet weak var errorView: UIView! @IBOutlet weak var retryBtn: UIButton! @IBOutlet weak var errorLabel: UILabel! var dataController = appDelegate.dataController var fetchBusesService: FetchBusesProtocol = FetchBusesService(apiURL: ServerConfiguration.Request.apiFetchBusUrl) var busesDataSource: BusesList = BusesList() { didSet { busListTblView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() setupNavBarWithFilterButton() busListTblView.delegate = self busListTblView.dataSource = self fetchBuses() } func setupNavBarWithFilterButton() { let filterBarButton = UIBarButtonItem(image: Constants.filter, style: .done, target: self, action: #selector(self.showFilterVC)) self.navigationItem.rightBarButtonItem = filterBarButton } @objc func showFilterVC() { guard let filterVC = storyboard?.instantiateViewController(withIdentifier: Constants.filterVCStoryboardId) as? FilterViewController, let busesArr = busesDataSource.allBuses, !busesArr.isEmpty else { return } filterVC.modalPresentationStyle = .overFullScreen filterVC.sortBy = busesDataSource.sortBy if let busType = busesDataSource.busType { filterVC.busFilterType = busType } filterVC.applyCompletionHandler = { (sortBy, busFilterType) in self.busesDataSource.sortBy = sortBy self.busesDataSource.busType = busFilterType self.busListTblView.reloadData() if self.busesDataSource.filteredBuses.isEmpty { self.view.makeToast(Constants.useDifferentFilter, duration: 3.0, position: .bottom) } else { self.view.makeToast(Constants.filterSuccess, duration: 3.0, position: .bottom) } } self.present(filterVC, animated: true, completion: nil) } @IBAction func retryBtnClicked(_ sender: Any) { self.errorView.isHidden = true self.busListTblView.isHidden = false fetchBuses() } func fetchBuses() { spinner.startAnimating() performOperationInBackground { _ = self.fetchBusesService.fetchAllBuses { [weak self] (busesResponse) in guard let weakSelf = self else { return } performUIUpdatesOnMain { weakSelf.spinner.stopAnimating() guard let busesResponse = busesResponse, !busesResponse.isEmpty else { weakSelf.errorView.isHidden = false weakSelf.busListTblView.isHidden = true return } weakSelf.busesDataSource.allBuses = busesResponse weakSelf.busListTblView.reloadData() weakSelf.view.makeToast(Constants.fetchBusesSuccess, duration: 3.0, position: .bottom) } } } } } extension BusesListViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return busesDataSource.filteredBuses.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let busCell = tableView.dequeueReusableCell(withIdentifier: Constants.busCell, for: indexPath) as? BusTableViewCell else { return UITableViewCell() } busCell.selectionStyle = .none busCell.configureCell(busDetail: busesDataSource.filteredBuses[indexPath.row]) return busCell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let busCell = tableView.cellForRow(at: indexPath) as? BusTableViewCell, let busDetail = busCell.busDetail else { return } _ = Utility.showAlertMessage(title: Constants.bookingAlertTitle, message: Constants.bookingAlertMessage + " with \(busCell.busDetail.operatorName)?", viewController: self, okButtonTitle: Constants.bookingAlertOK, okHandler: { [weak self] _ in guard let weakSelf = self else { return } weakSelf.dataController.addBooking(bus: busDetail) weakSelf.view.makeToast(Constants.bookingSuccessful, duration: 3.0, position: .bottom) }, cancelButtonTitle: Constants.bookingAlertCancel, cancelHandler: nil) } }
apache-2.0
e2315e0aa13c5dab39927aaedc717354
41.130435
250
0.660062
4.859579
false
false
false
false
jianwoo/WordPress-iOS
WordPress/WordPressTodayWidget/TodayViewController.swift
1
4973
import UIKit import NotificationCenter class TodayViewController: UIViewController, NCWidgetProviding { @IBOutlet var siteNameLabel: UILabel! @IBOutlet var visitorsCountLabel: UILabel! @IBOutlet var visitorsLabel: UILabel! @IBOutlet var viewsCountLabel: UILabel! @IBOutlet var viewsLabel: UILabel! var siteName: String = "" var visitorCount: String = "" var viewCount: String = "" var siteId: NSNumber? override func viewDidLoad() { super.viewDidLoad() let sharedDefaults = NSUserDefaults(suiteName: WPAppGroupName)! self.siteId = sharedDefaults.objectForKey(WPStatsTodayWidgetUserDefaultsSiteIdKey) as NSNumber? visitorsLabel?.text = NSLocalizedString("Visitors", comment: "Stats Visitors Label") viewsLabel?.text = NSLocalizedString("Views", comment: "Stats Views Label") } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // Manual state restoration var userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setObject(self.siteName, forKey: WPStatsTodayWidgetUserDefaultsSiteNameKey) userDefaults.setObject(self.visitorCount, forKey: WPStatsTodayWidgetUserDefaultsVisitorCountKey) userDefaults.setObject(self.viewCount, forKey: WPStatsTodayWidgetUserDefaultsViewCountKey) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Manual state restoration let sharedDefaults = NSUserDefaults(suiteName: WPAppGroupName)! self.siteName = sharedDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsSiteNameKey) ?? "" let userDefaults = NSUserDefaults.standardUserDefaults() self.visitorCount = userDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsVisitorCountKey) ?? "0" self.viewCount = userDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsViewCountKey) ?? "0" self.siteNameLabel?.text = self.siteName self.visitorsCountLabel?.text = self.visitorCount self.viewsCountLabel?.text = self.viewCount } @IBAction func launchContainingApp() { self.extensionContext!.openURL(NSURL(string: "\(WPCOM_SCHEME)://viewstats?siteId=\(siteId!)")!, completionHandler: nil) } func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) { // Perform any setup necessary in order to update the view. // If an error is encoutered, use NCUpdateResult.Failed // If there's no update required, use NCUpdateResult.NoData // If there's an update, use NCUpdateResult.NewData let sharedDefaults = NSUserDefaults(suiteName: WPAppGroupName)! let siteId = sharedDefaults.objectForKey(WPStatsTodayWidgetUserDefaultsSiteIdKey) as NSNumber? self.siteName = sharedDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsSiteNameKey) ?? "" let timeZoneName = sharedDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsSiteTimeZoneKey) let oauth2Token = self.getOAuth2Token() if siteId == nil || timeZoneName == nil || oauth2Token == nil { WPDDLogWrapper.logError("Missing site ID, timeZone or oauth2Token") let bundle = NSBundle(forClass: TodayViewController.classForCoder()) NCWidgetController.widgetController().setHasContent(false, forWidgetWithBundleIdentifier: bundle.bundleIdentifier) completionHandler(NCUpdateResult.Failed) return } let timeZone = NSTimeZone(name: timeZoneName!) var statsService: WPStatsService = WPStatsService(siteId: siteId, siteTimeZone: timeZone, oauth2Token: oauth2Token, andCacheExpirationInterval:0) statsService.retrieveTodayStatsWithCompletionHandler({ (wpStatsSummary: StatsSummary!) -> Void in WPDDLogWrapper.logInfo("Downloaded data in the Today widget") self.visitorCount = wpStatsSummary.visitors self.viewCount = wpStatsSummary.views self.siteNameLabel?.text = self.siteName self.visitorsCountLabel?.text = self.visitorCount self.viewsCountLabel?.text = self.viewCount completionHandler(NCUpdateResult.NewData) }, failureHandler: { (error) -> Void in WPDDLogWrapper.logError("\(error)") completionHandler(NCUpdateResult.Failed) }) } func getOAuth2Token() -> String? { var error:NSError? var oauth2Token:NSString? = SFHFKeychainUtils.getPasswordForUsername(WPStatsTodayWidgetOAuth2TokenKeychainUsername, andServiceName: WPStatsTodayWidgetOAuth2TokenKeychainServiceName, accessGroup: WPStatsTodayWidgetOAuth2TokenKeychainAccessGroup, error: &error) return oauth2Token } }
gpl-2.0
502bded46987883ec1ca4fd765860000
45.485981
267
0.69817
5.683429
false
false
false
false
hermantai/samples
ios/SwiftUI-Cookbook-2nd-Edition/Chapter12-Handling-authentication-and-Firebase-with-SwiftUI/04-Implementing-a-distributed-Notes-app-with-Firebase-and-SwiftUI/FirebaseNotes/FirebaseNotes/NotesRepository.swift
1
901
// // NotesRepository.swift // NotesRepository // // Created by Giordano Scalzo on 26/08/2021. // import Foundation import Firebase import FirebaseFirestoreSwift struct NotesRepository { private let dbCollection = Firestore.firestore().collection("notes") func newNote(title: String, date: Date, body: String) async -> [Note] { let note = Note(id: UUID().uuidString, title: title, date: date, body: body) _ = try? dbCollection.addDocument(from: note) return await fetchNotes() } func fetchNotes() async -> [Note] { guard let snapshot = try? await dbCollection.getDocuments() else { return [] } let notes: [Note] = snapshot.documents.compactMap { document in try? document.data(as: Note.self) } return notes.sorted { $0.date < $1.date } } }
apache-2.0
2fca3805952ba168fdfce39fda5e4472
25.5
84
0.600444
4.133028
false
false
false
false
B-Lach/BLOAuth
Example/OAuthExample/Bridge.swift
1
11947
// // Bridge.swift // OAuthExample // // Created by Benny Lach on 27.12.14. // Copyright (c) 2014 Benny Lach. All rights reserved. // //import Foundation import UIKit class Bridge: NSObject, UIWebViewDelegate { let discogsKey = "JyPZaEQUnsoMDYyBXcOB" let discogsSecrect = "xZrVXRKBqnyivHWvdiOQfUDeBIDPcdTb" let discogsHost = "api.discogs.com" let discogsScheme = "http" let twitterKey = "YXFQrNNJ8yRUtIJ4o8a1bK4Ep" let twitterSecret = "Iz5CYGoLBi2AvEEkULS9JeFY3Z0jcQAnSmt5lFTyqPax2JCGqo" let twitterHost = "api.twitter.com" let twitterScheme = "https" let dropboxKey = "rrvxrvdbntq26gl" let dropboxSecret = "xre9ib91vybx094" let dropboxHost = "api.dropbox.com" let dropboxScheme = "https" var oauthClass:BLOAuth? var rootController:UINavigationController? var service:Int? var urlResponse:[String:String]! func beginDiscogsOAuth() { self.service = 0 self.oauthClass = BLOAuth(consumerKey: self.discogsKey, consumerSecret: self.discogsSecrect, oauthToken: nil, oauthSecret: nil, userAgent: nil) self.oauthClass?.params["oauth_callback"] = "oauthCallback://oauthResponse".customPercentEncoding() self.oauthClass?.getRequestToken("/oauth/request_token", scheme: self.discogsScheme, host: self.discogsHost, method: "GET", completion: { (sucess, error) -> () in if sucess == false { println("request-token error: \(error?.description)") } else { dispatch_async(dispatch_get_main_queue(), { () -> Void in let url = self.oauthClass?.getAuthorizeURL("/oauth/authorize", getParameters: nil, scheme: self.discogsScheme, host: "discogs.com") self.openWebView(url!) }) } }) } func beginTwitterOAuth() { self.service = 1 self.oauthClass = BLOAuth(consumerKey: twitterKey, consumerSecret: twitterSecret, oauthToken: nil, oauthSecret: nil, userAgent: nil) self.oauthClass?.params["oauth_callback"] = "oauthCallback://oauthResponse".customPercentEncoding() self.oauthClass?.getRequestToken("/oauth/request_token", scheme: self.twitterScheme, host: self.twitterHost, method: "POST", completion: { (sucess, error) -> () in if sucess == false { println("request-token error: \(error?.description)") } else { dispatch_async(dispatch_get_main_queue(), { () -> Void in let url = self.oauthClass?.getAuthorizeURL("/oauth/authorize", getParameters: nil, scheme: self.twitterScheme, host: self.twitterHost) self.openWebView(url!) }) } }) } func beginDropboxOAuth() { self.service = 2 self.oauthClass = BLOAuth(consumerKey: self.dropboxKey, consumerSecret: self.dropboxSecret, oauthToken: nil, oauthSecret: nil, userAgent: nil) //self.oauthClass?.params["oauth_callback"] = "oauthCallback://oauthResponse".customPercentEncoding() self.oauthClass?.getRequestToken("/1/oauth/request_token", scheme: self.dropboxScheme, host: self.dropboxHost, method: "POST", completion: { (sucess, error) -> () in if sucess == false { println("request-token error: \(error?.description)") } else { dispatch_async(dispatch_get_main_queue(), { () -> Void in let url = self.oauthClass?.getAuthorizeURL("/1/oauth/authorize", getParameters: ["oauth_callback":"oauthCallback://oauthResponse"], scheme: self.dropboxScheme, host: "dropbox.com") self.openWebView(url!) }) } }) } func openWebView(url:NSURL) { // removing all stored cookies let cookieArray = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies as [NSHTTPCookie] for cookie in cookieArray { NSHTTPCookieStorage.sharedHTTPCookieStorage().deleteCookie(cookie) } // add observer for oauth_callback NSNotificationCenter.defaultCenter().addObserver(self, selector: "notifier:", name: "oauthResponse", object: nil) // showing webview let webView = UIWebView(frame: UIScreen.mainScreen().bounds) webView.delegate = self let webController = UIViewController(nibName: nil, bundle: nil) webController.view.addSubview(webView) let navController = UINavigationController(rootViewController: webController) let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate self.rootController = appDelegate.window!.rootViewController as? UINavigationController self.rootController!.presentViewController(navController, animated: true, completion: nil) webView.loadRequest(NSURLRequest(URL: url)) } func notifier(notification: NSNotification) { NSNotificationCenter.defaultCenter().removeObserver(self, name: "oauthResponse", object: nil) let dict:Dictionary = notification.userInfo! let query = dict["query"] as String self.urlResponse = self.dictFromQuery(query) self.rootController?.dismissViewControllerAnimated(true, completion: nil) if !(query as NSString).containsString("denied") { switch self.service! { case 0: self.continueDiscogsOAuth() case 1: self.continueTwitterOAuth() case 2: self.continueDropboxOAuth() default: break } } } func continueDiscogsOAuth() { self.oauthClass?.getAccessToken("/oauth/access_token", scheme: self.discogsScheme, host: self.discogsHost, method: "POST", oauthVerifier: self.urlResponse["oauth_verifier"]!, completion: { (responseData, response, error) -> () in if error != nil { println("Discogs access_token error: \(error.localizedDescription)") } else { var responseString = NSString(data: responseData, encoding: NSUTF8StringEncoding) as String let tokenDict = self.dictFromQuery(responseString) self.oauthClass?.oauthToken = tokenDict["oauth_token"] self.oauthClass?.oauthSecret = tokenDict["oauth_token_secret"] self.oauthClass?.authenticatedReques("/oauth/identity", getParameters: nil, bodyData: nil, scheme: self.discogsScheme, host: self.discogsHost, method: "GET", completion: { (responseData, response, error) -> () in if error != nil { println("Discogs identity error: \(error.localizedDescription)") } else { responseString = NSString(data: responseData, encoding: NSUTF8StringEncoding) as String let alertView = UIAlertView(title: "Success", message: responseString, delegate: nil, cancelButtonTitle: "OK") dispatch_async(dispatch_get_main_queue(), { () -> Void in alertView.show() }) } }) } }) } func continueTwitterOAuth() { self.oauthClass?.getAccessToken("/oauth/access_token", scheme: self.twitterScheme, host: self.twitterHost, method: "POST", oauthVerifier: self.urlResponse["oauth_verifier"]!, completion: { (responseData, response, error) -> () in if error != nil { println("Discogs access_token error: \(error.localizedDescription)") } else { var responseString = NSString(data: responseData, encoding: NSUTF8StringEncoding) as String let tokenDict = self.dictFromQuery(responseString) self.oauthClass?.oauthToken = tokenDict["oauth_token"] self.oauthClass?.oauthSecret = tokenDict["oauth_token_secret"] let screen_name:String = tokenDict["screen_name"]! self.oauthClass?.authenticatedReques("/1.1/users/show.json", getParameters: ["screen_name":"\(screen_name)"], bodyData: nil, scheme: self.twitterScheme, host: self.twitterHost, method: "GET", completion: { (responseData, response, error) -> () in if error != nil { println("Discogs identity error: \(error.localizedDescription)") } else { responseString = NSString(data: responseData, encoding: NSUTF8StringEncoding) as String let alertView = UIAlertView(title: "Success", message: responseString, delegate: nil, cancelButtonTitle: "OK") dispatch_async(dispatch_get_main_queue(), { () -> Void in alertView.show() }) } }) } }) } func continueDropboxOAuth() { self.oauthClass?.getAccessToken("/1/oauth/access_token", scheme: self.dropboxScheme, host: self.dropboxHost, method: "POST", oauthVerifier: self.urlResponse["uid"]!, completion: { (responseData, response, error) -> () in if error != nil { println("Dropbox access_token error: \(error.localizedDescription)") } else { var responseString = NSString(data: responseData, encoding: NSUTF8StringEncoding) as String let tokenDict = self.dictFromQuery(responseString) self.oauthClass?.oauthToken = tokenDict["oauth_token"] self.oauthClass?.oauthSecret = tokenDict["oauth_token_secret"] self.oauthClass?.authenticatedReques("/1/account/info", getParameters: nil, bodyData: nil, scheme: self.dropboxScheme, host: self.dropboxHost, method: "GET", completion: { (responseData, response, error) -> () in if error != nil { println("Discogs identity error: \(error.localizedDescription)") } else { responseString = NSString(data: responseData, encoding: NSUTF8StringEncoding) as String let alertView = UIAlertView(title: "Success", message: responseString, delegate: nil, cancelButtonTitle: "OK") dispatch_async(dispatch_get_main_queue(), { () -> Void in alertView.show() }) } }) } }) } func dictFromQuery(query: String)->[String:String] { var dict = [String:String]() let splitArray = query.componentsSeparatedByString("&") for string in splitArray { let splitArray2 = string.componentsSeparatedByString("=") dict[splitArray2[0]] = splitArray2[1] } return dict } //MARK: - WebViewDelegate func webViewDidStartLoad(webView: UIWebView) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true } func webViewDidFinishLoad(webView: UIWebView) { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } func webView(webView: UIWebView, didFailLoadWithError error: NSError) { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } }
mit
748bfec5bd4a74d3e0544e9a81983789
45.131274
262
0.584498
4.982068
false
false
false
false
chenchangqing/mapboxdemo
googleMap/googleMap/ViewController.swift
1
1236
// // ViewController.swift // googleMap // // Created by  green on 15/10/29. // Copyright © 2015年 com.fgl. All rights reserved. // import Mapbox class ViewController: UIViewController, MGLMapViewDelegate { override func viewDidLoad() { super.viewDidLoad() let mapView = MGLMapView(frame: view.bounds) mapView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] mapView.delegate = self // set the map's center coordinate mapView.setCenterCoordinate(CLLocationCoordinate2D(latitude: 38.894368, longitude: -77.036487), zoomLevel: 15, animated: false) view.addSubview(mapView) // Declare the annotation `point` and set its coordinates, title, and subtitle let point = MGLPointAnnotation() point.coordinate = CLLocationCoordinate2D(latitude: 38.894368, longitude: -77.036487) point.title = "Hello world!" point.subtitle = "Welcome to The Ellipse." // Add annotation `point` to the map mapView.addAnnotation(point) } func mapView(mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool { return true } }
apache-2.0
b8bca4b98bed7bf029d1a9cab4fae0c0
30.589744
99
0.646104
4.649057
false
false
false
false
sergiosilvajr/ToDoList-Assignment-iOS
ToDoList/ToDoList/ToDoListViewController.swift
1
4790
// // ToDoListViewController.swift // ToDoList // // Created by Luis Sergio da Silva Junior on 11/27/15. // Copyright © 2015 Luis Sergio. All rights reserved. // import UIKit class ToDoListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{ var selectedDate: NSDate? var currentDayTodoList : [[String : AnyObject]]? @IBOutlet weak var myTableView: UITableView! var selectedCellIndex : Int = -1 override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) updateViewWithUserDefaultInfo() } private func updateViewWithUserDefaultInfo(){ if let todoList = UserDefaultUtil.getToDoItensFromADate(selectedDate!) { currentDayTodoList = todoList print("ToDoListViewController") print(currentDayTodoList) } self.myTableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { selectedCellIndex = indexPath.item } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "fromToDoToDefailViewController"{ let theDestination = (segue.destinationViewController as! DetailViewController) theDestination.currentDate = selectedDate } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if currentDayTodoList != nil { if currentDayTodoList!.count > 0{ print(currentDayTodoList!.count) return currentDayTodoList!.count } else{ return 0 } } return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("custom", forIndexPath: indexPath) as! ToDoTableViewCell print ("cellForRowAtIndexPath") for value in currentDayTodoList![indexPath.item].values{ if let name = value.valueForKey(UserDefaultUtil.nameKey) as? String{ cell.nameItem.text = "title:" + name }else{ cell.nameItem.text = "title: -" } if let content = value.valueForKey(UserDefaultUtil.contentKey) as? String{ cell.descriptionItem.text = "content: "+content }else{ cell.descriptionItem.text = "content: -" } if let cellDate = value.valueForKey(UserDefaultUtil.hourKey) as? String{ cell.dateLabelInfo.text = "date: "+cellDate }else{ cell.dateLabelInfo.text = "date: -" } if let isImportant = value.valueForKey(UserDefaultUtil.priorityKey) as? String{ cell.isImportantLabel.text = "important : " + isImportant }else{ cell.isImportantLabel.text = "important : -" } } return cell } static func enableTouch(isEnabled: Bool, inout cell: UITableViewCell){ if isEnabled { cell.selectionStyle = UITableViewCellSelectionStyle.Default }else{ cell.selectionStyle = UITableViewCellSelectionStyle.None cell.accessoryType = UITableViewCellAccessoryType.None } cell.userInteractionEnabled = isEnabled } func addNewCell(){ self.performSegueWithIdentifier("fromToDoToDefailViewController", sender: self) } func removeCell(){ if selectedCellIndex < 0 { let actionSheetController: UIAlertController = UIAlertController(title: "Error!", message: "You need at least one item to use the Remove action", preferredStyle: .Alert) let cancelAction: UIAlertAction = UIAlertAction(title: "Dismiss", style: .Cancel) { action -> Void in } actionSheetController.addAction(cancelAction) presentViewController(actionSheetController, animated: true, completion: nil) }else{ let dict = currentDayTodoList![selectedCellIndex] var stringDate = "" for value in dict.values where value.valueForKey(UserDefaultUtil.hourKey) != nil { stringDate = (value.valueForKey(UserDefaultUtil.hourKey) as? String)! } UserDefaultUtil.removeItem(NSDate.getCurrentDateFromString(stringDate)!) updateViewWithUserDefaultInfo() } } }
apache-2.0
9fcde4d2401a46358062bd2ae91f278c
35.838462
181
0.623095
5.542824
false
false
false
false
Jranco/SwiftyGraph
SwiftyGraph/SwiftyGraph/Algorithms/Shortest Path/Dijkstra/Dijkstra.swift
1
3092
// // Dijkstra.swift // SwiftyGraph // // Created by Thomas Segkoulis on 02/01/17. // Copyright © 2017 Thomas Segkoulis. All rights reserved. // extension GraphWeighted { public func dijkstra(source: VerticeType, destination: VerticeType, completion: (_ distance: Int, _ path: [VerticeType]) -> Void) { /** Unvisited Vertex set */ var unvisitedVertex = Set<VerticeType>() /** Distances from source to Vertex */ var distance: [VerticeType: Int] = [:] // Previous vertex var prev: [VerticeType: VerticeType] = [:] /// Add all vertices to the unvisitedVertex Set for v in verticeDictionary { unvisitedVertex.insert(v.value) } /// Init source distance to zero distance[source] = 0 while unvisitedVertex.isEmpty == false { let minDistVertex = vertexWithMinDist(vertexDist: distance, unvisitedVertex: unvisitedVertex) unvisitedVertex.remove(minDistVertex) guard adjacency[minDistVertex] != nil else { continue } for (v, edge) in adjacency[minDistVertex]! { if(distance[v] == nil) { let alt = distance[minDistVertex]! + (edge.weight?.value)! distance[v] = alt prev[v] = verticeDictionary[minDistVertex] } else { let alt = distance[minDistVertex]! + (edge.weight?.value)! if(alt < distance[v]!) { distance[v] = alt prev[v] = verticeDictionary[minDistVertex] } } } } var path: [VerticeType] = [] var currentVertice = destination while currentVertice != source { path.insert(currentVertice, at: 0) currentVertice = prev[currentVertice]! } path.insert(source, at: 0) completion(distance[destination]!, path) } func vertexWithMinDist(vertexDist: [VerticeType: Int], unvisitedVertex: Set<VerticeType>) -> VerticeType { var vertexDicNew = vertexDist for vDist in vertexDicNew { if(unvisitedVertex.contains(vDist.key) == false) { vertexDicNew.removeValue(forKey: vDist.key) } } var minDistVertex = vertexDicNew.first for vertex in vertexDicNew { if(unvisitedVertex.contains(vertex.key) == false) { continue } if(vertex.value < (minDistVertex?.value)!) { minDistVertex = vertex } } return (minDistVertex?.key)! } }
mit
d4738edfe0008f0a421dcb61667758cd
25.878261
133
0.480751
4.898574
false
false
false
false
megabitsenmzq/PomoNow-iOS
PomoNow/PomoNow/PomoListViewController.swift
1
5209
// // PomoListViewController.swift // PomoNow // // Created by Megabits on 15/9/28. // Copyright © 2015年 Jinyu Meng. All rights reserved. // import UIKit class PomoListViewController: UIViewController , UINavigationControllerDelegate{ @IBOutlet weak var TimerView: CProgressView! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var round: UIImageView! @IBOutlet weak var addOneLabel: UILabel! @IBOutlet var swipeDown: UISwipeGestureRecognizer! @IBOutlet var swipeDown2: UISwipeGestureRecognizer! @IBOutlet var swipeDown3: UISwipeGestureRecognizer! @IBAction func pop(_ sender: UITapGestureRecognizer) { timer?.invalidate() timer = nil taskTable.setEditing(false, animated:true) self.navigationController?.popViewController(animated: true) } @IBAction func swipePop(_ sender: UISwipeGestureRecognizer) { timer?.invalidate() timer = nil if sender.direction == UISwipeGestureRecognizerDirection.down || sender.direction == UISwipeGestureRecognizerDirection.right { taskTable.setEditing(false, animated:true) self.navigationController?.popViewController(animated: true) } } @IBOutlet weak var taskTable: TaskTableView! @IBAction func toSettings(_ sender: AnyObject) { taskTable.setEditing(false, animated:true) self.performSegue(withIdentifier: "toSettings", sender: self) } @IBOutlet weak var ListContainer: UIView! @IBAction func addTask(_ sender: UIButton) { //添加新任务 taskTable.setEditing(false, animated:true) Dialog().showAddTask(NSLocalizedString("Add task", comment: "addtask"), doneButtonTitle: NSLocalizedString("Done", comment: "done"), cancelButtonTitle: NSLocalizedString("Cancel", comment: "cancel")) { (timer) -> Void in if taskString != "" { let nowDate = Date() //当前添加的任务的时间信息 let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let dateString = formatter.string(from: nowDate) self.addOneLabel.isHidden = true self.taskTable.isHidden = false if task.count == 0 { withTask = true task.append([String(selectTag),taskString,"0","1",dateString]) pomodoroClass.stop() } else { task.append([String(selectTag),taskString,"0","0",dateString]) } self.setDefaults ("main.withTask",value: withTask as AnyObject) self.setDefaults ("main.task",value: task as AnyObject) self.taskTable.reloadData() } } } var timer: Timer? var process: Float { //进度条 get { return TimerView.valueProgress / 67 * 100 } set { TimerView.valueProgress = newValue / 100 * 67 updateUI() } } fileprivate func updateUI() { TimerView.setNeedsDisplay() timeLabel.text = pomodoroClass.timerLabel } override func viewDidLoad() { super.viewDidLoad() process = pomodoroClass.process updateUI() timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(PomoListViewController.getNowtime(_:)), userInfo: nil, repeats: true) if task.count == 0{ addOneLabel.isHidden = false taskTable.isHidden = true } //返回上一级界面允许向右和向下两种手势 swipeDown.direction = UISwipeGestureRecognizerDirection.down swipeDown2.direction = UISwipeGestureRecognizerDirection.down swipeDown3.direction = UISwipeGestureRecognizerDirection.down } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.navigationController?.delegate = self } @objc func getNowtime(_ timer:Timer) { //同步时间 process = pomodoroClass.process if task.count == 0 { addOneLabel.isHidden = false taskTable.isHidden = true } if taskChanged { taskChanged = false taskTable.reloadData() } } func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == UINavigationControllerOperation.pop { return AnimationFromList() } else { return nil } } //NSUserDefaults fileprivate let defaults = UserDefaults.standard func getDefaults (_ key: String) -> AnyObject? { if key != "" { return defaults.object(forKey: key) as AnyObject } else { return nil } } func setDefaults (_ key: String,value: AnyObject) { if key != "" { defaults.set(value,forKey: key) } } }
mit
d1a805925762b2d1986afd41e252b112
34.818182
246
0.615385
5.184211
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
Pods/HXPHPicker/Sources/HXPHPicker/Camera/View/PreviewMetalView.swift
1
13595
/* See LICENSE folder for this sample’s licensing information. Abstract: The Metal preview view. */ import CoreMedia import Metal import MetalKit class PreviewMetalView: MTKView { enum Rotation: Int { case rotate0Degrees case rotate90Degrees case rotate180Degrees case rotate270Degrees } var mirroring = false { didSet { syncQueue.sync { internalMirroring = mirroring } } } private var internalMirroring: Bool = false var rotation: Rotation = .rotate0Degrees { didSet { syncQueue.sync { internalRotation = rotation } } } private var internalRotation: Rotation = .rotate0Degrees var pixelBuffer: CVPixelBuffer? { didSet { if pixelBuffer == nil { isPreviewing = false } syncQueue.sync { internalPixelBuffer = pixelBuffer } } } var isPreviewing: Bool = false var didPreviewing: ((Bool) -> Void)? private var internalPixelBuffer: CVPixelBuffer? private let syncQueue = DispatchQueue( label: "com.silence.previewViewSyncQueue", qos: .userInitiated, attributes: [], autoreleaseFrequency: .workItem ) private var textureCache: CVMetalTextureCache? private var textureWidth: Int = 0 private var textureHeight: Int = 0 private var textureMirroring = false private var textureRotation: Rotation = .rotate0Degrees private var sampler: MTLSamplerState! private var renderPipelineState: MTLRenderPipelineState! private var commandQueue: MTLCommandQueue? private var vertexCoordBuffer: MTLBuffer! private var textCoordBuffer: MTLBuffer! private var internalBounds: CGRect! private var textureTranform: CGAffineTransform? func texturePointForView(point: CGPoint) -> CGPoint? { var result: CGPoint? guard let transform = textureTranform else { return result } let transformPoint = point.applying(transform) if CGRect(origin: .zero, size: CGSize(width: textureWidth, height: textureHeight)).contains(transformPoint) { result = transformPoint } else { print("Invalid point \(point) result point \(transformPoint)") } return result } func viewPointForTexture(point: CGPoint) -> CGPoint? { var result: CGPoint? guard let transform = textureTranform?.inverted() else { return result } let transformPoint = point.applying(transform) if internalBounds.contains(transformPoint) { result = transformPoint } else { print("Invalid point \(point) result point \(transformPoint)") } return result } func flushTextureCache() { textureCache = nil } private func setupTransform(width: Int, height: Int, mirroring: Bool, rotation: Rotation) { var scaleX: Float = 1.0 var scaleY: Float = 1.0 var resizeAspect: Float = 1.0 internalBounds = self.bounds textureWidth = width textureHeight = height textureMirroring = mirroring textureRotation = rotation if textureWidth > 0 && textureHeight > 0 { switch textureRotation { case .rotate0Degrees, .rotate180Degrees: scaleX = Float(internalBounds.width / CGFloat(textureWidth)) scaleY = Float(internalBounds.height / CGFloat(textureHeight)) case .rotate90Degrees, .rotate270Degrees: scaleX = Float(internalBounds.width / CGFloat(textureHeight)) scaleY = Float(internalBounds.height / CGFloat(textureWidth)) } } // Resize aspect ratio. resizeAspect = min(scaleX, scaleY) if scaleX < scaleY { scaleY = scaleX / scaleY scaleX = 1.0 } else { scaleX = scaleY / scaleX scaleY = 1.0 } if textureMirroring { scaleX *= -1.0 } // Vertex coordinate takes the gravity into account. let vertexData: [Float] = [ -scaleX, -scaleY, 0.0, 1.0, scaleX, -scaleY, 0.0, 1.0, -scaleX, scaleY, 0.0, 1.0, scaleX, scaleY, 0.0, 1.0 ] vertexCoordBuffer = device!.makeBuffer( bytes: vertexData, length: vertexData.count * MemoryLayout<Float>.size, options: [] ) // Texture coordinate takes the rotation into account. var textData: [Float] switch textureRotation { case .rotate0Degrees: textData = [ 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0 ] case .rotate180Degrees: textData = [ 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0 ] case .rotate90Degrees: textData = [ 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0 ] case .rotate270Degrees: textData = [ 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0 ] } textCoordBuffer = device?.makeBuffer( bytes: textData, length: textData.count * MemoryLayout<Float>.size, options: [] ) // Calculate the transform from texture coordinates to view coordinates var transform = CGAffineTransform.identity if textureMirroring { transform = transform.concatenating(CGAffineTransform(scaleX: -1, y: 1)) transform = transform.concatenating(CGAffineTransform(translationX: CGFloat(textureWidth), y: 0)) } switch textureRotation { case .rotate0Degrees: transform = transform.concatenating(CGAffineTransform(rotationAngle: CGFloat(0))) case .rotate180Degrees: transform = transform.concatenating(CGAffineTransform(rotationAngle: CGFloat(Double.pi))) transform = transform.concatenating( CGAffineTransform( translationX: CGFloat(textureWidth), y: CGFloat(textureHeight) ) ) case .rotate90Degrees: transform = transform.concatenating(CGAffineTransform(rotationAngle: CGFloat(Double.pi) / 2)) transform = transform.concatenating(CGAffineTransform(translationX: CGFloat(textureHeight), y: 0)) case .rotate270Degrees: transform = transform.concatenating(CGAffineTransform(rotationAngle: 3 * CGFloat(Double.pi) / 2)) transform = transform.concatenating(CGAffineTransform(translationX: 0, y: CGFloat(textureWidth))) } transform = transform.concatenating(CGAffineTransform(scaleX: CGFloat(resizeAspect), y: CGFloat(resizeAspect))) let tranformRect = CGRect( origin: .zero, size: CGSize(width: textureWidth, height: textureHeight) ).applying(transform) let xShift = (internalBounds.size.width - tranformRect.size.width) / 2 let yShift = (internalBounds.size.height - tranformRect.size.height) / 2 transform = transform.concatenating(CGAffineTransform(translationX: xShift, y: yShift)) textureTranform = transform.inverted() } init() { super.init(frame: .zero, device: MTLCreateSystemDefaultDevice()) configureMetal() createTextureCache() colorPixelFormat = .bgra8Unorm } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configureMetal() { guard let device = device else { return } let defaultLibrary: MTLLibrary PhotoManager.shared.createBundle() if let bundle = PhotoManager.shared.bundle, let path = bundle.path(forResource: "metal/default", ofType: "metallib"), let library = try? device.makeLibrary(filepath: path) { defaultLibrary = library }else { do { defaultLibrary = try device.makeDefaultLibrary(bundle: .main) } catch { return } } let pipelineDescriptor = MTLRenderPipelineDescriptor() pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm pipelineDescriptor.vertexFunction = defaultLibrary.makeFunction(name: "vertexPassThrough") pipelineDescriptor.fragmentFunction = defaultLibrary.makeFunction(name: "fragmentPassThrough") let samplerDescriptor = MTLSamplerDescriptor() samplerDescriptor.sAddressMode = .clampToEdge samplerDescriptor.tAddressMode = .clampToEdge samplerDescriptor.minFilter = .linear samplerDescriptor.magFilter = .linear sampler = device.makeSamplerState(descriptor: samplerDescriptor) do { renderPipelineState = try device.makeRenderPipelineState(descriptor: pipelineDescriptor) } catch { fatalError("Unable to create preview Metal view pipeline state. (\(error))") } preferredFramesPerSecond = 30 commandQueue = device.makeCommandQueue() } func createTextureCache() { guard let device = device else { return } var newTextureCache: CVMetalTextureCache? if CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, device, nil, &newTextureCache) == kCVReturnSuccess { textureCache = newTextureCache } } /// - Tag: DrawMetalTexture override func draw(_ rect: CGRect) { var pixelBuffer: CVPixelBuffer? var mirroring = false var rotation: Rotation = .rotate0Degrees syncQueue.sync { pixelBuffer = internalPixelBuffer mirroring = internalMirroring rotation = internalRotation } guard let drawable = currentDrawable, let currentRenderPassDescriptor = currentRenderPassDescriptor, let previewPixelBuffer = pixelBuffer else { return } // Create a Metal texture from the image buffer. let width = CVPixelBufferGetWidth(previewPixelBuffer) let height = CVPixelBufferGetHeight(previewPixelBuffer) if textureCache == nil { createTextureCache() } guard let textureCache = textureCache else { return } var cvTextureOut: CVMetalTexture? CVMetalTextureCacheCreateTextureFromImage( kCFAllocatorDefault, textureCache, previewPixelBuffer, nil, .bgra8Unorm, width, height, 0, &cvTextureOut ) guard let cvTexture = cvTextureOut, let texture = CVMetalTextureGetTexture(cvTexture) else { print("Failed to create preview texture") CVMetalTextureCacheFlush(textureCache, 0) return } if texture.width != textureWidth || texture.height != textureHeight || self.bounds != internalBounds || mirroring != textureMirroring || rotation != textureRotation { setupTransform( width: texture.width, height: texture.height, mirroring: mirroring, rotation: rotation ) } // Set up command buffer and encoder guard let commandQueue = commandQueue else { print("Failed to create Metal command queue") CVMetalTextureCacheFlush(textureCache, 0) return } guard let commandBuffer = commandQueue.makeCommandBuffer() else { print("Failed to create Metal command buffer") CVMetalTextureCacheFlush(textureCache, 0) return } guard let commandEncoder = commandBuffer.makeRenderCommandEncoder( descriptor: currentRenderPassDescriptor ) else { print("Failed to create Metal command encoder") CVMetalTextureCacheFlush(textureCache, 0) return } commandEncoder.label = "Preview display" commandEncoder.setRenderPipelineState(renderPipelineState!) commandEncoder.setVertexBuffer(vertexCoordBuffer, offset: 0, index: 0) commandEncoder.setVertexBuffer(textCoordBuffer, offset: 0, index: 1) commandEncoder.setFragmentTexture(texture, index: 0) commandEncoder.setFragmentSamplerState(sampler, index: 0) commandEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4) commandEncoder.endEncoding() // Draw to the screen. commandBuffer.present(drawable) commandBuffer.commit() DispatchQueue.main.async { self.didPreviewing?(!self.isPreviewing) self.isPreviewing = true } } }
mit
af757e2c4101c991eeb4d99990d8f068
32.562963
119
0.580299
5.360016
false
false
false
false
Rehsco/StyledOverlay
StyledOverlay/StyledMenuPopoverConfiguration.swift
1
4839
// // StyledMenuPopoverConfiguration.swift // StyledOverlay // // Created by Martin Rehder on 01.01.2018. /* * Copyright 2018-present Martin Jacob Rehder. * http://www.rehsco.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import UIKit import StyledLabel import FlexCollections import FlexControls open class StyledMenuPopoverConfiguration { public init() {} /// Features open var tapOutsideViewToClose: Bool = true /// General Styling open var backgroundTintColor: UIColor = UIColor.black.withAlphaComponent(0.6) open var style: FlexShapeStyle = FlexShapeStyle(style: .roundedFixed(cornerRadius: 5)) open var styleColor: UIColor = .white open var borderWidth: CGFloat = 0 open var borderColor: UIColor = .black open var contentMargins: UIEdgeInsets = UIEdgeInsets.init(top: 5, left: 5, bottom: 5, right: 5) open var menuItemSize: CGSize = CGSize(width: 64, height: 80) open var displayType: FlexCollectionCellDisplayMode = .iconified(size: CGSize(width: 64, height: 80)) open var appearAnimation: StyledOverlayAnimationStyle = .bottomToTop open var disappearAnimation: StyledOverlayAnimationStyle = .fadeInOut open var animationDuration: TimeInterval = 0.2 open var showTitleInHeader: Bool = true open var titleHeightWhenNotInHeader: CGFloat = 26 open var closeButtonEnabled: Bool = true open var closeButtonText: NSAttributedString = NSAttributedString(string: "Close") open var closeButtonTextAlignment: NSTextAlignment = .center open var closeButtonStyle: FlexShapeStyle = FlexShapeStyle(style: .roundedFixed(cornerRadius: 5)) open var closeButtonStyleColor: UIColor = .gray /// Header open var showHeader: Bool = true open var detachedHeader: Bool = false // TODO open var headerFont: UIFont = UIFont.systemFont(ofSize: 18) open var headerTextColor: UIColor = .black open var headerTextAlignment: NSTextAlignment = .center open var headerStyleColor: UIColor = .lightGray open var headerHeight: CGFloat = 32 /// Header Icon open var headerIconPosition: NSTextAlignment = .center open var headerIconSize: CGSize? = nil // Override, if the size should not use the icon size open var headerIconRelativeOffset: CGPoint = CGPoint(x: 0, y: -0.5) // x is relative to icon width, y is relative to headerHeight open var headerIconClipToBounds: Bool = true open var headerIconBackgroundColor: UIColor = .white open var headerIconBorderColor: UIColor = .lightGray open var headerIconBorderWidth: CGFloat = 2.5 /// Footer open var showFooter: Bool = false open var detachedFooter: Bool = false // TODO open var footerFont: UIFont? = nil open var footerTextColor: UIColor? = nil open var footerTextAlignment: NSTextAlignment = .center open var footerStyleColor: UIColor = .lightGray open var footerHeight: CGFloat = 20 /// Menu item styling open var menuItemTextAlignment: NSTextAlignment = .center open var menuSubTitleTextAlignment: NSTextAlignment = .center open var menuItemStyle: FlexShapeStyle = FlexShapeStyle(style: .roundedFixed(cornerRadius: 5)) open var menuItemStyleColor: UIColor = .lightGray open var menuItemSectionMargins: UIEdgeInsets = UIEdgeInsets.init(top: 5, left: 5, bottom: 5, right: 5) /// Fonts and Colors used in Popover factory open var menuItemFont: UIFont = UIFont.systemFont(ofSize: 14) open var closeButtonFont: UIFont = UIFont.systemFont(ofSize: 14) open var menuItemTextColor: UIColor = .white open var closeButtonTextColor: UIColor = .white open var headerIconTintColor: UIColor = .gray open var menuSubtitleFont: UIFont = UIFont.systemFont(ofSize: 12) open var menuSubtitleTextColor: UIColor = .black }
mit
925e677ead92649811eadf752a55d2d1
43.394495
133
0.742922
4.639501
false
false
false
false
tensorflow/swift-models
TrainingLoop/Callbacks/StatisticsRecorder.swift
1
5524
// Copyright 2020 The TensorFlow Authors. 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 TensorFlow /// A handler for recording training and validation statistics. /// /// Data produced by this handler can be used by ProgressPrinter, CVSLogger, etc. public class StatisticsRecorder { /// A function that returns `true` iff recorder should call `reset` /// on `metricMeasurers`. public var shouldReset: ( _ batchIndex: Int, _ batchCount: Int, _ epochIndex: Int, _ epochCount: Int, _ event: TrainingLoopEvent ) -> Bool /// A function that returns `true` iff recorder should call `accumulate` /// on `metricMeasurers`. public var shouldAccumulate: ( _ batchIndex: Int, _ batchCount: Int, _ epochIndex: Int, _ epochCount: Int, _ event: TrainingLoopEvent ) -> Bool /// A function that returns `true` iff recorder should call `measure` /// on `metricMeasurers`. public var shouldCompute: ( _ batchIndex: Int, _ batchCount: Int, _ epochIndex: Int, _ epochCount: Int, _ event: TrainingLoopEvent ) -> Bool /// Instances of MetricsMeasurers that you can reset accumulate and compute /// statistics periodically. fileprivate var metricMeasurers: [MetricsMeasurer] /// Creates an instance that records `metrics` during the training loop. public init(metrics: [TrainingMetrics]) { metricMeasurers = metrics.map { $0.measurer } shouldReset = { ( _ batchIndex: Int, _ batchCount: Int, _ epochIndex: Int, _ epochCount: Int, _ event: TrainingLoopEvent ) -> Bool in return event == .trainingStart || event == .validationStart } shouldAccumulate = { ( _ batchIndex: Int, _ batchCount: Int, _ epochIndex: Int, _ epochCount: Int, _ event: TrainingLoopEvent ) -> Bool in return event == .batchEnd } shouldCompute = { ( _ batchIndex: Int, _ batchCount: Int, _ epochIndex: Int, _ epochCount: Int, _ event: TrainingLoopEvent ) -> Bool in return event == .batchEnd } } /// Records statistics in response of the `event`. /// /// It will record the statistics into lastStatsLog property in the `loop` where other /// callbacks can consume from. public func record<L: TrainingLoopProtocol>(_ loop: inout L, event: TrainingLoopEvent) throws { guard let batchIndex = loop.batchIndex, let batchCount = loop.batchCount, let epochIndex = loop.epochIndex, let epochCount = loop.epochCount, let loss = loop.lastStepLoss, let output = loop.lastStepOutput, let target = loop.lastStepTarget else { return } if shouldReset(batchIndex, batchCount, epochIndex, epochCount, event) { resetMetricMeasurers() loop.lastStatsLog = nil } if shouldAccumulate(batchIndex, batchCount, epochIndex, epochCount, event) { accumulateMetrics(loss: loss, predictions: output, labels: target) } if shouldCompute(batchIndex, batchCount, epochIndex, epochCount, event) { loop.lastStatsLog = computeMetrics() } } /// Resets each of the metricMeasurers. func resetMetricMeasurers() { for index in metricMeasurers.indices { metricMeasurers[index].reset() } } /// Lets each of the metricMeasurers accumulate data from /// `loss`, `predictions`, `labels`. func accumulateMetrics<Output, Target>(loss: Tensor<Float>, predictions: Output, labels: Target) { for index in metricMeasurers.indices { metricMeasurers[index].accumulate(loss: loss, predictions: predictions, labels: labels) } } /// Lets each of the metricMeasurers compute metrics on cumulated data. func computeMetrics() -> [(String, Float)] { var result: [(String, Float)] = [] for measurer in metricMeasurers { result.append((name: measurer.name, value: measurer.measure())) } return result } } extension StatisticsRecorder { /// The events on which statistics will be reported for training and validation phases. public enum ReportTrigger { /// Report statistics at end of training and validation, once per epoch. case endOfEpoch /// Report statistics at end of training and validation, once per batch. case endOfBatch } /// Updates `self` to report statistics when `trigger` is encountered. public func setReportTrigger(_ trigger: ReportTrigger) { if trigger == .endOfBatch { shouldCompute = { ( _ batchIndex: Int, _ batchCount: Int, _ epochIndex: Int, _ epochCount: Int, _ event: TrainingLoopEvent ) -> Bool in return event == .batchEnd } } else { shouldCompute = { ( _ batchIndex: Int, _ batchCount: Int, _ epochIndex: Int, _ epochCount: Int, _ event: TrainingLoopEvent ) -> Bool in return event == .batchEnd && batchIndex + 1 == batchCount } } } }
apache-2.0
9ad8551a6ea121b8317946619d7552e4
33.310559
100
0.657676
4.125467
false
false
false
false
TimurBK/Swift500pxMobile
Carthage/Checkouts/Kingfisher/Tests/KingfisherTests/UIButtonExtensionTests.swift
5
7831
// // UIButtonExtensionTests.swift // Kingfisher // // Created by Wei Wang on 15/4/17. // // Copyright (c) 2017 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import XCTest @testable import Kingfisher class UIButtonExtensionTests: XCTestCase { var button: UIButton! override class func setUp() { super.setUp() LSNocilla.sharedInstance().start() } override class func tearDown() { super.tearDown() LSNocilla.sharedInstance().stop() } override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. button = UIButton() KingfisherManager.shared.downloader = ImageDownloader(name: "testDownloader") cleanDefaultCache() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. LSNocilla.sharedInstance().clearStubs() button = nil cleanDefaultCache() super.tearDown() } func testDownloadAndSetImage() { let expectation = self.expectation(description: "wait for downloading image") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = URL(string: URLString)! var progressBlockIsCalled = false cleanDefaultCache() button.kf.setImage(with: url, for: .highlighted, placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) -> () in progressBlockIsCalled = true }) { (image, error, cacheType, imageURL) -> () in expectation.fulfill() XCTAssert(progressBlockIsCalled, "progressBlock should be called at least once.") XCTAssert(image != nil, "Downloaded image should exist.") XCTAssert(image! == testImage, "Downloaded image should be the same as test image.") XCTAssert(self.button.image(for: UIControlState.highlighted)! == testImage, "Downloaded image should be already set to the image for state") XCTAssert(self.button.kf.webURL(for: .highlighted) == imageURL, "Web URL should equal to the downloaded url.") XCTAssert(cacheType == .none, "The cache type should be none here. This image was just downloaded. But now is: \(cacheType)") } waitForExpectations(timeout: 5, handler: nil) } func testDownloadAndSetBackgroundImage() { let expectation = self.expectation(description: "wait for downloading image") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = Foundation.URL(string: URLString)! var progressBlockIsCalled = false button.kf.setBackgroundImage(with: url, for: .normal, placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) -> () in progressBlockIsCalled = true }) { (image, error, cacheType, imageURL) -> () in expectation.fulfill() XCTAssert(progressBlockIsCalled, "progressBlock should be called at least once.") XCTAssert(image != nil, "Downloaded image should exist.") XCTAssert(image! == testImage, "Downloaded image should be the same as test image.") XCTAssert(self.button.backgroundImage(for: .normal)! == testImage, "Downloaded image should be already set to the image for state") XCTAssert(self.button.kf.backgroundWebURL(for: .normal) == imageURL, "Web URL should equal to the downloaded url.") XCTAssert(cacheType == .none, "cacheType should be .None since the image was just downloaded.") } waitForExpectations(timeout: 5, handler: nil) } func testCacnelImageTask() { let expectation = self.expectation(description: "wait for downloading image") let URLString = testKeys[0] let stub = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)?.delay() let url = URL(string: URLString)! button.kf.setImage(with: url, for: UIControlState.highlighted, placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) -> () in }) { (image, error, cacheType, imageURL) -> () in XCTAssertNotNil(error) XCTAssertEqual(error?.code, NSURLErrorCancelled) expectation.fulfill() } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(Double(NSEC_PER_SEC) * 0.1)) / Double(NSEC_PER_SEC)) { () -> Void in self.button.kf.cancelImageDownloadTask() _ = stub!.go() } waitForExpectations(timeout: 5, handler: nil) } func testCacnelBackgroundImageTask() { let expectation = self.expectation(description: "wait for downloading image") let URLString = testKeys[0] let stub = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)?.delay() let url = URL(string: URLString)! button.kf.setBackgroundImage(with: url, for: UIControlState(), placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) -> () in XCTFail("Progress block should not be called.") }) { (image, error, cacheType, imageURL) -> () in XCTAssertNotNil(error) XCTAssertEqual(error?.code, NSURLErrorCancelled) expectation.fulfill() } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(Double(NSEC_PER_SEC) * 0.1)) / Double(NSEC_PER_SEC)) { () -> Void in self.button.kf.cancelBackgroundImageDownloadTask() _ = stub!.go() } waitForExpectations(timeout: 5, handler: nil) } func testSettingNilURL() { let expectation = self.expectation(description: "wait for downloading image") let url: URL? = nil button.kf.setBackgroundImage(with: url, for: UIControlState(), placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) -> () in XCTFail("Progress block should not be called.") }) { (image, error, cacheType, imageURL) -> () in XCTAssertNil(image) XCTAssertNil(error) XCTAssertEqual(cacheType, CacheType.none) XCTAssertNil(imageURL) expectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } }
mit
ac941042cb44e17dc2d9877cd5aca5bc
43.494318
154
0.637339
4.940694
false
true
false
false
touchopia/HackingWithSwift
project38/Project38/ViewController.swift
1
7233
// // ViewController.swift // Project38 // // Created by TwoStraws on 25/08/2016. // Copyright © 2016 Paul Hudson. All rights reserved. // import CoreData import UIKit class ViewController: UITableViewController, NSFetchedResultsControllerDelegate { var container: NSPersistentContainer! var fetchedResultsController: NSFetchedResultsController<Commit>! var commitPredicate: NSPredicate? override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Filter", style: .plain, target: self, action: #selector(changeFilter)) container = NSPersistentContainer(name: "Project38") container.loadPersistentStores { storeDescription, error in self.container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy if let error = error { print("Unresolved error \(error)") } } performSelector(inBackground: #selector(fetchCommits), with: nil) loadSavedData() } func saveContext() { if container.viewContext.hasChanges { do { try container.viewContext.save() } catch { print("An error occurred while saving: \(error)") } } } func fetchCommits() { let newestCommitDate = getNewestCommitDate() if let data = try? Data(contentsOf: URL(string: "https://api.github.com/repos/apple/swift/commits?per_page=100&since=\(newestCommitDate)")!) { let jsonCommits = JSON(data: data) let jsonCommitArray = jsonCommits.arrayValue print("Received \(jsonCommitArray.count) new commits.") DispatchQueue.main.async { [unowned self] in for jsonCommit in jsonCommitArray { // the following three lines are new let commit = Commit(context: self.container.viewContext) self.configure(commit: commit, usingJSON: jsonCommit) } self.saveContext() self.loadSavedData() } } } func getNewestCommitDate() -> String { let formatter = ISO8601DateFormatter() let newest = Commit.createFetchRequest() let sort = NSSortDescriptor(key: "date", ascending: false) newest.sortDescriptors = [sort] newest.fetchLimit = 1 if let commits = try? container.viewContext.fetch(newest) { if commits.count > 0 { return formatter.string(from: commits[0].date.addingTimeInterval(1)) } } return formatter.string(from: Date(timeIntervalSince1970: 0)) } func configure(commit: Commit, usingJSON json: JSON) { commit.sha = json["sha"].stringValue commit.message = json["commit"]["message"].stringValue commit.url = json["html_url"].stringValue let formatter = ISO8601DateFormatter() commit.date = formatter.date(from: json["commit"]["committer"]["date"].stringValue) ?? Date() var commitAuthor: Author! // see if this author exists already let authorRequest = Author.createFetchRequest() authorRequest.predicate = NSPredicate(format: "name == %@", json["commit"]["committer"]["name"].stringValue) if let authors = try? container.viewContext.fetch(authorRequest) { if authors.count > 0 { // we have this author already commitAuthor = authors[0] } } if commitAuthor == nil { // we didn't find a saved author - create a new one! let author = Author(context: container.viewContext) author.name = json["commit"]["committer"]["name"].stringValue author.email = json["commit"]["committer"]["email"].stringValue commitAuthor = author } // use the author, either saved or new commit.author = commitAuthor } override func numberOfSections(in tableView: UITableView) -> Int { return fetchedResultsController.sections?.count ?? 0 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return fetchedResultsController.sections![section].name } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Commit", for: indexPath) let commit = fetchedResultsController.object(at: indexPath) cell.textLabel!.text = commit.message cell.detailTextLabel!.text = "By \(commit.author.name) on \(commit.date.description)" return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController { vc.detailItem = fetchedResultsController.object(at: indexPath) navigationController?.pushViewController(vc, animated: true) } } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let commit = fetchedResultsController.object(at: indexPath) container.viewContext.delete(commit) saveContext() } } func loadSavedData() { if fetchedResultsController == nil { let request = Commit.createFetchRequest() let sort = NSSortDescriptor(key: "author.name", ascending: true) request.sortDescriptors = [sort] request.fetchBatchSize = 20 fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: container.viewContext, sectionNameKeyPath: "author.name", cacheName: nil) fetchedResultsController.delegate = self } fetchedResultsController.fetchRequest.predicate = commitPredicate do { try fetchedResultsController.performFetch() tableView.reloadData() } catch { print("Fetch failed") } } func changeFilter() { let ac = UIAlertController(title: "Filter commits…", message: nil, preferredStyle: .actionSheet) // 1 ac.addAction(UIAlertAction(title: "Show only fixes", style: .default) { [unowned self] _ in self.commitPredicate = NSPredicate(format: "message CONTAINS[c] 'fix'") self.loadSavedData() }) // 2 ac.addAction(UIAlertAction(title: "Ignore Pull Requests", style: .default) { [unowned self] _ in self.commitPredicate = NSPredicate(format: "NOT message BEGINSWITH 'Merge pull request'") self.loadSavedData() }) // 3 ac.addAction(UIAlertAction(title: "Show only recent", style: .default) { [unowned self] _ in let twelveHoursAgo = Date().addingTimeInterval(-43200) self.commitPredicate = NSPredicate(format: "date > %@", twelveHoursAgo as NSDate) self.loadSavedData() }) // 4 ac.addAction(UIAlertAction(title: "Show only Durian commits", style: .default) { [unowned self] _ in self.commitPredicate = NSPredicate(format: "author.name == 'Joe Groff'") self.loadSavedData() }) // 5 ac.addAction(UIAlertAction(title: "Show all commits", style: .default) { [unowned self] _ in self.commitPredicate = nil self.loadSavedData() }) ac.addAction(UIAlertAction(title: "Cancel", style: .cancel)) present(ac, animated: true) } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .delete: tableView.deleteRows(at: [indexPath!], with: .automatic) default: break } } }
unlicense
782781ecd661c99c9ddd73fe69b20580
31.133333
197
0.730567
4.061798
false
false
false
false
srn214/Floral
Floral/Pods/SwiftLocation/Sources/Support/Support.swift
1
2970
// // SwiftLocation - Efficient Location Tracking for iOS // // Created by Daniele Margutti // - Web: https://www.danielemargutti.com // - Twitter: https://twitter.com/danielemargutti // - Mail: [email protected] // // Copyright © 2019 Daniele Margutti. Licensed under MIT License. import Foundation import CoreLocation extension Sequence { func count(where predicate: (Element) throws -> Bool) rethrows -> Int { var count = 0 for element in self { if try predicate(element) { count += 1 } } return count } } internal struct CLPlacemarkDictionaryKey { // Parse address data static let kAdministrativeArea = "AdministrativeArea" static let kSubAdministrativeArea = "SubAdministrativeArea" static let kSubLocality = "SubLocality" static let kState = "State" static let kStreet = "Street" static let kThoroughfare = "Thoroughfare" static let kFormattedAddressLines = "FormattedAddressLines" static let kSubThoroughfare = "SubThoroughfare" static let kPostCodeExtension = "PostCodeExtension" static let kCity = "City" static let kZIP = "ZIP" static let kCountry = "Country" static let kCountryCode = "CountryCode" } internal func valueAtKeyPath<T>(root: Any, fallback: T? = nil, _ components: [Any]) -> T? { guard components.isEmpty == false else { return nil } var current: Any? = root for component in components { switch (component, current) { case (let index as Int, let list as Array<Any>): guard index >= 0, index < list.count else { fatalError("Invalid index \(index) for node with \(list.count) elements") } current = list[index] case (let key as String, let dict as Dictionary<String,Any>): current = dict[key] default: fatalError("Unsupported path type: \(type(of: component)) for node: \(type(of: current))") } } return (current as? T) ?? fallback } internal extension String { var urlEncoded: String { return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! } } internal extension CLPlacemark { func makeAddressString() -> String { // Unwrapping the optionals using switch statement switch (self.subThoroughfare, self.thoroughfare, self.locality, self.administrativeArea, self.postalCode, self.country) { case let (.some(subThoroughfare), .some(thoroughfare), .some(locality), .some(administrativeArea), .some(postalCode), .some(country)): return "\(subThoroughfare), \(thoroughfare), \(locality), \(administrativeArea), \(postalCode), \(country)" default: return "" } } }
mit
598d5d122ad89cfc303f635bfc03e44f
33.523256
142
0.614011
4.690363
false
false
false
false
Oni-zerone/SwipeControl
SwipeControl/ViewController.swift
1
1372
// // ViewController.swift // SliderProject // // Created by Andrea Altea on 06/06/16. // Copyright © 2016 Studiout. All rights reserved. // import UIKit class ViewController: UIViewController, SOTSwipeControlDelegate { @IBOutlet weak var slider: SOTSwipeControl! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = UIColor.white; slider.delegate = self; slider.isAsync = true; slider.rightEnabled = true; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning(); // Dispose of any resources that can be recreated. } //MARK: Slide Delegate func didSuccessSwipe(_ slider: SOTSwipeControl) { let alertText = slider.sliderStatus == .leftSuccess ? "Left swipe with success!" : "Right swipe with success!"; let alert = UIAlertController(title: "Completed swipe with Success!", message: alertText, preferredStyle: .alert); alert.addAction(UIAlertAction(title: "Complete!", style: .default, handler: { (action) in self.slider.sliderStatus = .normal; })); self.present(alert, animated: true) { //DO NOTHING. }; } }
mit
a7bb5ccfac05b9f74d2dff2074392940
27.5625
122
0.622174
4.727586
false
false
false
false
NeAres/1706C.C.
Solemn/Solemn/Helper.swift
1
414
// // Helper.swift // Cut&Paste // // Created by Arendelle on 2017/7/14. // Copyright © 2017年 AdTech. All rights reserved. // import UIKit func cutImg(image:UIImage, _ xdis:Int, _ ydis:Int) -> UIImage { let x1 = 102 + xdis let y1 = 162 + ydis let w = 2218 let h = 2663 let im = image.cgImage?.cropping(to: CGRect(x: x1, y: y1, width: w, height: h)) return UIImage(cgImage: im!) }
mit
2ace715ef7696946630ba2d0932c6e01
20.631579
83
0.610706
2.777027
false
false
false
false
xin-wo/kankan
kankan/kankan/Class/Tools/WXNavigationProtocol.swift
1
2676
// // WXNavigationProtocol.swift // kankan // // Created by Xin on 16/10/22. // Copyright © 2016年 王鑫. All rights reserved. // import Foundation import UIKit enum Position { case left case right } protocol WXNavigationProtocol: NSObjectProtocol { //添加navigationBar的标题 func addTitle(title: String) //添加navigationBar的左右按钮 func addBarButton(title: String?, imageName: String?, bgImageName: String?, postion: Position, select: Selector) //添加navigationBar的底部图片 func addBottomImage() } extension WXNavigationProtocol where Self: UIViewController { func addTitle(title: String) { let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 44)) label.text = title label.textColor = UIColor.blackColor() label.font = UIFont.systemFontOfSize(20) label.textAlignment = .Center navigationItem.titleView = label } func addBarButton(title: String? = nil, imageName: String? = nil, bgImageName: String? = nil, postion position: Position, select: Selector) { let button = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 44)) if title != nil{ button.setTitle(title, forState: .Normal) } if imageName != nil { button.setImage(UIImage(named: imageName!), forState: .Normal) } if bgImageName != nil{ button.setImage(UIImage(named:bgImageName!), forState: .Highlighted) } button.setTitleColor(UIColor.blackColor(), forState: .Normal) button.setTitleColor(UIColor.grayColor(), forState: .Highlighted) button.addTarget(self, action: select, forControlEvents: .TouchUpInside) let barButtonItem=UIBarButtonItem(customView: button) if position == .left { if navigationItem.leftBarButtonItems != nil{ navigationItem.leftBarButtonItems = navigationItem.leftBarButtonItems! + [barButtonItem] }else{ navigationItem.leftBarButtonItems = [barButtonItem] } }else{ if navigationItem.rightBarButtonItems != nil{ navigationItem.rightBarButtonItems = navigationItem.rightBarButtonItems! + [barButtonItem] }else{ navigationItem.rightBarButtonItems = [barButtonItem] } } } func addBottomImage() { let imageView = UIImageView(frame: CGRect(x: 0, y: 43, width: screenWidth, height: 1)) imageView.image = UIImage(named: "app_nav_separater") navigationController?.navigationBar.addSubview(imageView) } }
mit
4e138e61cfb4c86dbd670e9c8158e615
34.08
145
0.640821
4.774955
false
false
false
false
CalvinChina/Demo
LearnSwiftBasic/LearnSwfitBasic/LearnSwfitBasic/Function/CalvinFunctionOne.swift
1
1446
// // CalvinFunctionOne.swift // LearnSwfitBasic // // Created by pisen on 16/9/21. // Copyright © 2016年 丁文凯. All rights reserved. // import UIKit enum 怪物经验表:Int { case 骷髅 = 80, 跳舞骷髅 = 100, 骷髅叫兽 = 300 } struct 服务器经验倍数 { var 开启 = false var 倍数 = 2 } class 人民币玩家{ var 经验值 = 0 var 经验倍数 = 服务器经验倍数() func 挂机经验(){ 经验值 += 500 print("挂机成功一次+\(经验值)") } func 打怪经验(怪物:怪物经验表,经验倍数:Int) { let 怪物经验值 = 怪物.rawValue self.经验值 += (怪物经验值 * 经验倍数) if self.经验倍数.开启 && self.经验倍数.倍数 > 1{ 经验值 *= self.经验倍数.倍数 } print("当前打怪经验值是\(self.经验值)") } } class CalvinFunctionOne: NSObject { func add(x: Int ,y:Int) -> Int { return x + y } func maxMin() ->(Int,Int){ return(Int.max ,Int.min) } func add2(x:Int ,y :Int, z:Int) -> Int{ return x+y+z } func add3(x:Int, increment:Int = 2) ->Int{ return x + increment } func calculate(x: Int, y: Int, method: (Int,Int)->Int ) -> Int { return method(x, y) } func multiply(x: Int, y: Int) -> Int { return x * y } }
mit
a32968b41810b97e169165fb45523ea8
15.9
68
0.496196
2.634744
false
false
false
false
linchaosheng/CSSwiftWB
SwiftCSWB/SwiftCSWB/Class/Main/C/WBTabBarViewController.swift
1
4639
// // WBTabBarViewController.swift // SwiftCSWB // // Created by Apple on 16/4/21. // Copyright © 2016年 Apple. All rights reserved. // import UIKit class WBTabBarViewController: UITabBarController { deinit{ print("tabbar deinit") } override func viewDidLoad() { super.viewDidLoad() // 设置图片和字体的颜色统一为橙色 tabBar.tintColor = UIColor(red: 233.0/255, green: 117.0/255, blue: 0, alpha: 1) // 加载JSON文件数据动态创建控制器 loadJsonFile() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // 添加加号按钮 setUpPlusBtn() } private func setUpPlusBtn() { let W = UIScreen.mainScreen().bounds.size.width * 0.2 let H = tabBar.bounds.size.height let X = 2 * W let Y = CGFloat(0) let plusBtn = UIButton(frame: CGRect(x: X, y: Y, width: W, height: H)) plusBtn .setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal) plusBtn .setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted) plusBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal) plusBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted) tabBar.addSubview(plusBtn) plusBtn.addTarget(self, action: "plusBtnOnClick", forControlEvents: UIControlEvents.TouchUpInside) } func plusBtnOnClick() { print("plusBtnOnClick") } func loadJsonFile() { let filePath = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil) let data = NSData(contentsOfFile: filePath!) if let jsonData = data{ // NSJSONReadingOptions.MutableContainers 返回的字典为mutable NSJSONSerialization方法会throw异常 do{ // try 捕获到异常来到catch try!: 捕获到异常程序奔溃 let dictArr = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) for itemDict in dictArr as! [[String : String]] { addChildViewController(itemDict["vcName"]!, title: itemDict["title"]!, image: itemDict["image"]!, selectedImage: itemDict["highlightImage"]!) } }catch{ // 若json数据加载解析失败,则创建默认控制器 print(error) // 创建子控制器 addChildViewController("WBHomeViewController", title: "首页", image: "tabbar_home", selectedImage: "tabbar_home_highlighted") addChildViewController("WBMessageViewController", title: "消息", image: "tabbar_message_center", selectedImage: "tabbar_message_center_highlighted") addChildViewController("WBNULLViewController", title: "", image: "", selectedImage: "") addChildViewController("WBPlaygroundViewController", title: "广场", image: "tabbar_discover", selectedImage: "tabbar_discover_highlighted") addChildViewController("WBProfileViewController", title: "个人 ", image: "tabbar_profile", selectedImage: "tabbar_profile_highlighted") } } } // 动态获取命名空间, 根据字符串创建类 Swift中类名为 命名空间.类名 private func addChildViewController(childController: String, title: String, image: String, selectedImage: String){ // 0.动态获取命名空间 let name = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String // 1.根据传入的字符串动态创建控制器 // 1.1获取类名 let className : AnyClass = NSClassFromString(name + "." + childController)! let classVC = className as! UIViewController.Type // 1.2创建控制器 let childVC = classVC.init() childVC.title = title childVC.tabBarItem.image = UIImage(named: image) // 取消image蓝色状态 let temp = UIImage(named: selectedImage) childVC.tabBarItem.selectedImage = temp?.imageWithRenderingMode(.AlwaysOriginal); let nav = WBNavigationController(rootViewController: childVC) self.addChildViewController(nav) } }
apache-2.0
8560df21524682434a99e37d5f71b7a6
36.885965
162
0.618199
4.869222
false
false
false
false
lvogelzang/Blocky
Blocky/Levels/Level87.swift
1
877
// // Level87.swift // Blocky // // Created by Lodewijck Vogelzang on 07-12-18 // Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved. // import UIKit final class Level87: Level { let levelNumber = 87 var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]] let cameraFollowsBlock = false let blocky: Blocky let enemies: [Enemy] let foods: [Food] init() { blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1)) let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)] let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0) let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)] let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1) enemies = [enemy0, enemy1] foods = [] } }
mit
b937b695573c72442a7deba0fad85529
24.794118
89
0.573546
2.649547
false
false
false
false
akio0911/til
20201203/CombineTimer/CombineTimer/TimerModel.swift
1
1329
// // TimerModel.swift // CombineTimer // // Created by akio0911 on 2020/12/03. // import Foundation import Combine final class TimerModel { private let countSubject: CurrentValueSubject<Int, Never> private let isValidSubject: PassthroughSubject<Bool, Never> private var cencelables = Set<AnyCancellable>() var countPublisher: AnyPublisher<Int, Never> init(interval: TimeInterval = 1.0) { let countSubject = CurrentValueSubject<Int, Never>(0) self.countSubject = countSubject self.countPublisher = countSubject.eraseToAnyPublisher() let isValidSubject = PassthroughSubject<Bool, Never>() self.isValidSubject = isValidSubject isValidSubject .flatMapLatest({ isValid in isValid ? Timer.publish(every: interval, on: .main, in: .default).autoconnect().eraseToAnyPublisher() : Empty<Date, Never>(completeImmediately: true).eraseToAnyPublisher() }) .sink { _ in countSubject.send(countSubject.value + 1) } .store(in: &cencelables) } func pauseTimer() { isValidSubject.send(false) } func resetTimer() { countSubject.send(0) } func startTimer() { isValidSubject.send(true) } }
mit
8a4c8c21a9e7e846f2e9424ee3c195d4
27.276596
187
0.625282
4.582759
false
false
false
false
spire-inc/Bond
Sources/UIKit/UIView.swift
6
1783
// // The MIT License (MIT) // // Copyright (c) 2016 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit extension UIView { public var bnd_alpha: Bond<UIView, CGFloat> { return Bond(target: self) { $0.alpha = $1 } } public var bnd_backgroundColor: Bond<UIView, UIColor?> { return Bond(target: self) { $0.backgroundColor = $1 } } public var bnd_isHidden: Bond<UIView, Bool> { return Bond(target: self) { $0.isHidden = $1 } } public var bnd_isUserInteractionEnabled: Bond<UIView, Bool> { return Bond(target: self) { $0.isUserInteractionEnabled = $1 } } public var bnd_tintColor: Bond<UIView, UIColor?> { return Bond(target: self) { $0.tintColor = $1 } } }
mit
6e2ce138c030bf61029df1523a790f31
36.145833
81
0.713965
3.979911
false
false
false
false
ewhitley/CDAKit
CDAKit/health-data-standards/lib/models/physical_quantity_result_value.swift
1
2469
// // physical_quantity_result_value.swift // CDAKit // // Created by Eric Whitley on 12/2/15. // Copyright © 2015 Eric Whitley. All rights reserved. // import Foundation import Mustache // this is sort of annoying // I get that this should be its own class, but the way ResultValue is used in the CDAKRecord makes this cumbersome to use // because you have to cast ResultValue to PhysicalResultValue to access the scalars /** Subclass of CDAKResultValue. Represents a known fixed physical result value (PQ, etc.) */ public class CDAKPhysicalQuantityResultValue: CDAKResultValue { // MARK: CDA properties ///scalar value like "6" or "true" public var scalar: String? //no clue what this type should be, so sticking with String for now ///units. Most commonly UCUM units, but there is no restriction public var units: String? // MARK: - Initializers public init(scalar: Any?, units: String? = nil) { super.init() if let scalar = scalar as? Int { self.scalar = String(scalar) } else if let scalar = scalar as? Double { self.scalar = String(scalar) } else if let scalar = scalar as? String { self.scalar = scalar } else if let scalar = scalar as? Bool { self.scalar = String(scalar) } self.units = units } // MARK: Standard properties ///hash value for comparing objects override public var hashValue: Int { return "\(scalar)\(units)".hashValue } ///Debugging description override public var description: String { return "\(self.dynamicType) => attributes: \(attributes), time: \(time), start_time: \(start_time), end_time: \(end_time), scalar: \(scalar), units: \(units)" } } public func == (lhs: CDAKPhysicalQuantityResultValue, rhs: CDAKPhysicalQuantityResultValue) -> Bool { return lhs.hashValue == rhs.hashValue } extension CDAKPhysicalQuantityResultValue { // MARK: - Mustache marshalling var boxedValues: [String:MustacheBox] { return [ "scalar" : Box(scalar), "units" : Box(units) ] } override public var mustacheBox: MustacheBox { return Box(boxedValues) } } extension CDAKPhysicalQuantityResultValue { // MARK: - JSON Generation ///Dictionary for JSON data override public var jsonDict: [String: AnyObject] { var dict = super.jsonDict if let scalar = scalar { dict["scalar"] = scalar } if let units = units { dict["units"] = units } return dict } }
mit
235c69d3972bae6b62bd234a346efb37
26.433333
162
0.673825
4.147899
false
false
false
false
rmorbach/pagandopave
Apps/iOS/PagandoPave/PagandoPave/Credit.swift
1
1094
// // Credit.swift // PagandoPave // // Created by Rodrigo Morbach on 26/08/17. // Copyright © 2017 Morbach Inc. All rights reserved. // import UIKit class Payment: NSObject { public var cardExpirationMonth: String? public var cardExpirationYear: String? public var cardNumber: String? public var cardType: String? func dictionaryRepresentation()->[String:Any] { var dict = [String: Any]() dict["cardExpirationMonth"] = self.cardExpirationMonth dict["cardExpirationYear"] = self.cardExpirationYear dict["cardNumber"] = self.cardNumber dict["cardType"] = self.cardType return dict } } class Credit: NSObject { public var amount: String? public var currency: String? public var payment: Payment? func dictionaryRepresentation()->[String:Any] { var dict = [String: Any]() dict["amount"] = self.amount dict["currency"] = self.currency dict["payment"] = self.payment?.dictionaryRepresentation() return dict } }
apache-2.0
e6dab00b2fa8437118b2c3d98c4b39ea
22.255319
74
0.624886
4.573222
false
false
false
false
daviwiki/Gourmet_Swift
Gourmet/GourmetModel/Interactors/StoreAccount.swift
1
1728
// // StoreAccount.swift // Gourmet // // Created by David Martinez on 11/12/2016. // Copyright © 2016 Atenea. All rights reserved. // import Foundation public protocol StoreAccountListener : NSObjectProtocol { func onFinish(interactor: StoreAccount) } public class StoreAccount : NSObject { internal static let AccountKey = "AccountKey" private var account : Account? private weak var listener : StoreAccountListener? public func setAccount (account : Account?) { self.account = account } public func setListener (listener : StoreAccountListener) { self.listener = listener } public func execute () { DispatchQueue.global(qos: .background).async { let defaults = UserDefaults.init(suiteName: "group.atenea.gourmet") var data : Data? if let ac = self.account { data = NSKeyedArchiver.archivedData(withRootObject: ac) } defaults?.set(data, forKey: "account") DispatchQueue.main.async { self.listener?.onFinish(interactor: self) self.notifyAccountChange(account: self.account) } } } private func notifyAccountChange (account : Account?) { let center = NotificationCenter.default var userInfo : [AnyHashable : Any] = [:] if (account != nil) { userInfo[StoreAccount.AccountKey] = account! } center.post(name: .storedAccountUpdated, object: nil, userInfo: userInfo) } } extension Notification.Name { static let storedAccountUpdated = Notification.Name("StoreAccountUpdatedNotificationId") }
mit
3c56cc61c6e09bca9aaa6e35de91f4b4
27.783333
92
0.619572
4.783934
false
false
false
false
coshx/caravel
caravel/EventBus.swift
1
10002
import WebKit import UIKit /** **EventBus** In charge of watching a subscriber / webview-wkwebview pair. Deals with any request from the user side, as well as the watched pair, and forward them to the dispatcher. */ open class EventBus: NSObject, IUIWebViewObserver, IWKWebViewObserver { /** **Draft** Required when watching a WKWebView */ open class Draft: NSObject, IWKWebViewObserver { fileprivate var wkWebViewConfiguration: WKWebViewConfiguration internal weak var parent: IWKWebViewObserver? internal var hasBeenUsed = false internal init(wkWebViewConfiguration: WKWebViewConfiguration) { self.wkWebViewConfiguration = wkWebViewConfiguration super.init() WKScriptMessageHandlerProxyMediator.subscribe(self.wkWebViewConfiguration, observer: self) } internal func onMessage(_ busName: String, eventName: String, eventData: AnyObject?) { self.parent?.onMessage(busName, eventName: eventName, eventData: eventData) } } fileprivate class WKWebViewPair { var draft: Draft weak var webView: WKWebView? init(draft: Draft, webView: WKWebView) throws { self.draft = draft self.webView = webView if draft.hasBeenUsed { // If a draft is used twice, the previous listener (parent) is overriden // and will never be notified. Hence, prevent this scenario from happening. throw CaravelError.draftUsedTwice } else { self.draft.hasBeenUsed = true } } } fileprivate let initializationLock = NSObject() fileprivate let subscriberLock = NSObject() fileprivate weak var reference: AnyObject? fileprivate weak var webView: UIWebView? fileprivate var wkWebViewPair: WKWebViewPair? fileprivate weak var dispatcher: Caravel? /** * Bus subscribers */ fileprivate lazy var subscribers: [EventSubscriber] = [] /** * Denotes if the bus has received init event from JS */ fileprivate var isInitialized: Bool /** * Pending initialization subscribers */ fileprivate lazy var initializers: [(callback: (EventBus) -> Void, inBackground: Bool)] = [] // Buffer to save initializers temporary, in order to prevent them from being garbage collected fileprivate lazy var onGoingInitializers: [Int: (callback: (EventBus) -> Void, inBackground: Bool)] = [:] fileprivate lazy var onGoingInitializersId = 0 // Id counter fileprivate init(dispatcher: Caravel, reference: AnyObject) { self.dispatcher = dispatcher self.reference = reference self.isInitialized = false super.init() } internal convenience init(dispatcher: Caravel, reference: AnyObject, webView: UIWebView) { self.init(dispatcher: dispatcher, reference: reference) self.webView = webView UIWebViewDelegateProxyMediator.subscribe(self.webView!, observer: self) } internal convenience init(dispatcher: Caravel, reference: AnyObject, wkWebViewPair: (Draft, WKWebView)) { self.init(dispatcher: dispatcher, reference: reference) try! self.wkWebViewPair = WKWebViewPair(draft: wkWebViewPair.0, webView: wkWebViewPair.1) self.wkWebViewPair!.draft.parent = self } /** * Current name */ open var name: String { return self.dispatcher!.name } fileprivate func unsubscribeFromProxy() { if self.isUsingWebView() { if let w = self.webView { UIWebViewDelegateProxyMediator.unsubscribe(w, observer: self) } } else { if let p = self.wkWebViewPair { WKScriptMessageHandlerProxyMediator.unsubscribe(p.draft.wkWebViewConfiguration, observer: self) } } } internal func getReference() -> AnyObject? { return self.reference } internal func isUsingWebView() -> Bool { return self.webView != nil } internal func getWebView() -> UIWebView? { return self.webView } internal func getWKWebView() -> WKWebView? { return self.wkWebViewPair?.webView } /** Bus is not needed anymore. Stop observing proxy */ internal func notifyAboutCleaning() { self.unsubscribeFromProxy() } /** Runs JS script into current context - parameter toRun: JS script */ internal func forwardToJS(_ toRun: String) { main { if self.isUsingWebView() { _ = self.webView?.stringByEvaluatingJavaScript(from: toRun) } else { self.wkWebViewPair?.webView?.evaluateJavaScript(toRun, completionHandler: nil) } } } internal func onInit() { // Initialization must be run on the main thread. Otherwise, some events would be triggered before onReady // has been run and hence be lost. if self.isInitialized { return } synchronized(self.initializationLock) { if self.isInitialized { return } for pair in self.initializers { let index = self.onGoingInitializersId let action: ((EventBus) -> Void, Int) -> Void = { initializer, id in initializer(self) self.onGoingInitializers.removeValue(forKey: id) } self.onGoingInitializers[index] = pair self.onGoingInitializersId += 1 if pair.inBackground { background { action(pair.callback, index) } } else { main { action(pair.callback, index) } } } self.initializers = [] self.isInitialized = true } } /** Allows dispatcher to fire any event on this bus - parameter name: event's name - parameter data: event's data */ internal func raise(_ name: String, data: AnyObject?) { synchronized(subscriberLock) { for s in self.subscribers { if s.name == name { let action = { s.callback(name, data) } if s.inBackground { background(action) } else { main(action) } } } } } internal func whenReady(_ callback: @escaping (EventBus) -> Void) { background { if self.isInitialized { background { callback(self) } } else { synchronized(self.initializationLock) { if self.isInitialized { background { callback(self) } } else { self.initializers.append((callback, true)) } } } } } internal func whenReadyOnMain(_ callback: @escaping (EventBus) -> Void) { background { if self.isInitialized { main { callback(self) } } else { synchronized(self.initializationLock) { if self.isInitialized { main { callback(self) } } else { self.initializers.append((callback, false)) } } } } } internal static func buildDraft(_ wkWebViewConfiguration: WKWebViewConfiguration) -> Draft { return Draft(wkWebViewConfiguration: wkWebViewConfiguration) } func onMessage(_ busName: String, eventName: String, rawEventData: String?) { self.dispatcher?.dispatch(busName, eventName: eventName, rawEventData: rawEventData) } func onMessage(_ busName: String, eventName: String, eventData: AnyObject?) { self.dispatcher?.dispatch(busName, eventName: eventName, eventData: eventData) } /** Posts event - parameter eventName: Name of the event */ open func post(_ eventName: String) { self.dispatcher?.post(eventName, eventData: nil as AnyObject?) } /** Posts event with extra data - parameter eventName: Name of the event - parameter data: Data to post (see documentation for supported types) */ open func post<T>(_ eventName: String, data: T) { self.dispatcher?.post(eventName, eventData: data) } /** Subscribes to event. Callback is run with the event's name and extra data (if any). - parameter eventName: Event to watch - parameter callback: Action to run when fired */ open func register(_ eventName: String, callback: @escaping (String, AnyObject?) -> Void) { synchronized(subscriberLock) { self.subscribers.append(EventSubscriber(name: eventName, callback: callback, inBackground: true)) } } /** Subscribes to event. Callback is run on main thread with the event's name and extra data (if any). - parameter eventName: Event to watch - parameter callback: Action to run when fired */ open func registerOnMain(_ eventName: String, callback: @escaping (String, AnyObject?) -> Void) { synchronized(subscriberLock) { self.subscribers.append(EventSubscriber(name: eventName, callback: callback, inBackground: false)) } } /** Unregisters subscriber from bus */ open func unregister() { self.dispatcher!.deleteBus(self) self.unsubscribeFromProxy() self.dispatcher = nil self.reference = nil self.webView = nil self.wkWebViewPair = nil } }
mit
b9e091ed13d103fd995b377b5e466d1e
30.062112
114
0.582384
5.222977
false
false
false
false
tichise/PopOverMenu
Sample/Sample/SampleViewController.swift
1
3622
// // SampleViewController // Sample // // Copyright © 2017年 ichise. All rights reserved. // import UIKit import PopOverMenu enum Drink: String, CaseIterable { case coffee case water case milk case tea } class SampleViewController: UIViewController, UIAdaptivePresentationControllerDelegate { let separatorStyle: UITableViewCell.SeparatorStyle = .singleLine var popOverViewController: PopOverViewController? @IBOutlet weak var textLabel: UILabel? var selectedDrink = Drink.water override func viewDidLoad() { super.viewDidLoad() let barButtonItem = UIBarButtonItem(title: "menu", style: .plain, target: self, action: #selector(SampleViewController.openMenu(sender:))) self.navigationItem.rightBarButtonItem = barButtonItem } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @objc func openMenu(sender: UIBarButtonItem) { self.popOverViewController = PopOverViewController.instantiate() let titles = ["Menu1", "Menu2", "Menu3"] let descriptions = ["description1", "description2", "description3"] self.popOverViewController?.setArrayForBarButtonItem(delegate: self, barButtonItem: sender, titles: titles, descriptions: descriptions, separatorStyle: separatorStyle) { (selectRow) in self.textLabel?.text = String(selectRow) } if let popOverViewController = self.popOverViewController { present(popOverViewController, animated: true, completion: nil) } } @IBAction func openDrinkMenu(sender: UIButton) { self.popOverViewController = PopOverViewController.instantiate() guard let popOverViewController = popOverViewController else { return } popOverViewController.setEnumForView(delegate: self, view: sender, enumType: Drink.self, defaultEnum: selectedDrink, separatorStyle: .none) { (key, index) in guard let key = key else { return } self.selectedDrink = key switch (key) { case .water: self.textLabel?.text = "water" break case .coffee: self.textLabel?.text = "coffee" break case .milk: self.textLabel?.text = "milk" break case .tea: self.textLabel?.text = "tea" break default: break } } self.present(popOverViewController, animated: true) {() -> Void in } } // 画面回転時によばれる override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: { context in self.popOverViewController?.dismiss(animated: true) }) } // iPhone でもポップオーバーを表示するためには、下記の delegate メソッドで常に UIModalPresentationNone を返すようにします。 func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return UIModalPresentationStyle.none } // これを入れないと、iPhone PlusでLandscape時にPopOverMenuがModal表示される func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return UIModalPresentationStyle.none } }
mit
aad0309f8b9c1964e260ecbfadfd2108
31.570093
192
0.644763
5.3698
false
false
false
false
mactive/rw-courses-note
DesignCode/layoutandstack/layoutandstack/SceneDelegate.swift
1
2795
// // SceneDelegate.swift // layoutandstack // // Created by Qian Meng on 2020/2/2. // Copyright © 2020 meng. All rights reserved. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // let contentView = PostList() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
mit
ee8f5e509300cdf31b580037abab0751
41.984615
147
0.701503
5.311787
false
false
false
false
ocrickard/Theodolite
Example/TheodoliteFeed/TheodoliteFeed/Featured/NewsItemFeaturedComponent.swift
1
1873
// // NewsItemFeaturedComponent.swift // TheodoliteFeed // // Created by Oliver Rickard on 11/1/17. // Copyright © 2017 Oliver Rickard. All rights reserved. // import Flexbox import Theodolite import SafariServices final class NewsItemFeaturedComponent: Component, TypedComponent { typealias PropType = ( NewsItem, navigationCoordinator: NavigationCoordinator ) override func render() -> [Component] { let props = self.props if props.0.media == .none || props.0.description == nil { return [ NewsItemComponent( props ) ] } return [ SizeComponent(( size: SizeRange(UIScreen.main.bounds.size), component: InsetComponent(( insets: UIEdgeInsets(top: 10, left: 0, bottom: 40, right: 0), component: TapComponent( (action: Handler(self, NewsItemFeaturedComponent.tappedItem), component: FlexboxComponent( (options: FlexOptions(flexDirection: .column), children: [ FlexChild(NewsItemHeaderComponent( props.0.author.name ), margin: Edges(left: 20, right: 20, top: 0, bottom: 0)), FlexChild(NewsItemFeaturedTitleComponent( props.0.title ), margin: Edges(left: 20, right: 20, top: 0, bottom: 0)), FlexChild(NewsItemFeaturedImageComponent( props.0.media.imageURL )), FlexChild(NewsItemDescriptionComponent( props.0.description ), margin: Edges(left: 20, right: 20, top: 10, bottom: 0)) ])))))))) ] } func tappedItem(gesture: UITapGestureRecognizer) { let safariVC = SFSafariViewController(url: self.props.0.url) self.props.navigationCoordinator.presentViewController(viewController: safariVC) } }
mit
b076d5e8821badd0108741c7b3613e19
33.036364
86
0.610043
4.577017
false
false
false
false
minikin/Algorithmics
Algorithmics/BuildArrayOperation.swift
1
1316
// // BuildArrayOperation.swift // Algorithmics // // Created by Sasha Minikin on 3/2/16. // Copyright © 2016 Minikin. All rights reserved. // import Foundation import PSOperations /// An `Operation` to generate array of random strings and save it to JSON format to disk. class BuildArrayOperation: Operation { // MARK: Properties private let arraySize: Int /** - parameter arraySize: The size of generated array. */ init(arraySize:Int) { self.arraySize = arraySize super.init() name = "Array Operation" } // Save array of strings to file. override func execute() { let arrayOfString = buildArray(arraySize) let jsonFile = FileSaveHelper(fileName:"arrayOfStrings", fileExtension: .JSON, subDirectory: "SavingFiles", directory: .DocumentDirectory) do { try jsonFile.saveFile(dataForJson: arrayOfString) } catch { print(error) } print("JSON file exists: \(jsonFile.fileExists)") } // Build array of random strings function private func buildArray(listSize: Int) -> [String] { var stringList = [String]() var i = 0 while i < listSize { i++ let uuid = NSUUID().UUIDString stringList.append(uuid) } return stringList } }
mit
c3020ba98204dc58947e0a092034b592
18.352941
142
0.634221
4.148265
false
false
false
false
silt-lang/silt
Sources/InnerCore/IRGenType.swift
1
7162
/// IRGenType.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Seismography import LLVM import PrettyStackTrace final class TypeConverter { let IGM: IRGenModule private let cache: TypeCache final class TypeCache { enum Entry { case typeInfo(TypeInfo) case llvmType(IRType) } fileprivate var cache: [GIRType: Entry] = [:] fileprivate var paramConventionCache: [GIRType: NativeConvention] = [:] fileprivate var returnConventionCache: [GIRType: NativeConvention] = [:] } init(_ IGM: IRGenModule) { self.cache = TypeCache() self.IGM = IGM } func parameterConvention(for T: GIRType) -> NativeConvention { if let cacheHit = self.cache.paramConventionCache[T] { return cacheHit } let ti = self.getCompleteTypeInfo(T) let conv = NativeConvention(self.IGM, ti, false) self.cache.paramConventionCache[T] = conv return conv } func returnConvention(for T: GIRType) -> NativeConvention { if let cacheHit = self.cache.returnConventionCache[T] { return cacheHit } let ti = self.getCompleteTypeInfo(T) let conv = NativeConvention(self.IGM, ti, true) self.cache.paramConventionCache[T] = conv return conv } func getCompleteTypeInfo(_ T: GIRType) -> TypeInfo { guard case let .typeInfo(entry) = getTypeEntry(T) else { fatalError("getting TypeInfo recursively!") } return entry } private func convertType(_ T: GIRType) -> TypeCache.Entry { switch T { case let type as DataType: return self.convertDataType(type) // case let type as RecordType: // return self.visitRecordType(type) case let type as ArchetypeType: return self.convertArchetypeType(type) case let type as SubstitutedType: return self.convertSubstitutedType(type) case let type as Seismography.FunctionType: return self.convertFunctionType(type) // case let type as TypeMetadataType: // return self.visitTypeMetadataType(type) case let type as TypeType: return self.convertTypeToMetadata(type) case let type as BottomType: return self.convertBottomType(type) // case let type as GIRExprType: // return self.visitGIRExprType(type) case let type as TupleType: return self.convertTupleType(type) case let type as BoxType: return self.convertBoxType(type) default: fatalError("attempt to convert unknown type \(T)") } } private func getTypeEntry(_ T: GIRType) -> TypeCache.Entry { if let cacheHit = self.cache.cache[T] { return cacheHit } // Convert the type. let convertedEntry = convertType(T) guard case .typeInfo(_) = convertedEntry else { // If that gives us a forward declaration (which can happen with // bound generic types), don't propagate that into the cache here, // because we won't know how to clear it later. return convertedEntry } // Cache the entry under the original type and the exemplar type, so that // we can avoid relowering equivalent types. if let existing = self.cache.cache[T], case .typeInfo(_) = existing { fatalError("") } self.cache.cache[T] = convertedEntry return convertedEntry } } extension TypeConverter { func convertArchetypeType(_ type: ArchetypeType) -> TypeCache.Entry { return .typeInfo(OpaqueArchetypeTypeInfo(self.IGM.opaquePtrTy.pointee)) } } extension TypeConverter { func convertBottomType(_ type: BottomType) -> TypeCache.Entry { return .typeInfo(EmptyTypeInfo(IntType.int8)) } } extension TypeConverter { func convertTypeToMetadata(_ type: TypeType) -> TypeCache.Entry { return .typeInfo(EmptyTypeInfo(IntType.int8)) } } extension TypeConverter { func convertSubstitutedType(_ type: SubstitutedType) -> TypeCache.Entry { return self.convertType(type.substitutee) } } extension TypeConverter { func convertDataType(_ type: DataType) -> TypeCache.Entry { let storageType = self.createNominalType(IGM, type) // Create a forward declaration for that type. self.addForwardDecl(type, storageType) // Determine the implementation strategy. let strategy = self.IGM.strategize(self, type, storageType) return .typeInfo(strategy.typeInfo()) } private func addForwardDecl(_ key: GIRType, _ type: IRType) { self.cache.cache[key] = .llvmType(type) } private func createNominalType(_ IGM: IRGenModule, _ type: DataType) -> StructType { var mangler = GIRMangler() mangler.append("T") type.mangle(into: &mangler) return IGM.B.createStruct(name: mangler.finalize()) } } extension TypeConverter { func convertTupleType(_ type: TupleType) -> TypeCache.Entry { var fieldTypesForLayout = [TypeInfo]() fieldTypesForLayout.reserveCapacity(type.elements.count) var loadable = true var explosionSize = 0 for astField in type.elements { // Compute the field's type info. let fieldTI = IGM.getTypeInfo(astField) fieldTypesForLayout.append(fieldTI) guard let loadableFieldTI = fieldTI as? LoadableTypeInfo else { loadable = false continue } explosionSize += loadableFieldTI.explosionSize() } // Perform layout and fill in the fields. let layout = RecordLayout(.nonHeapObject, self.IGM, type.elements, fieldTypesForLayout) let fields = layout.fieldLayouts.map { RecordField(layout: $0) } if loadable { return .typeInfo(LoadableTupleTypeInfo(fields, explosionSize, layout.llvmType, layout.minimumSize, layout.minimumAlignment)) } else if layout.wantsFixedLayout { return .typeInfo(FixedTupleTypeInfo(fields, layout.llvmType, layout.minimumSize, layout.minimumAlignment)) } else { return .typeInfo(NonFixedTupleTypeInfo(fields, layout.llvmType, layout.minimumAlignment)) } } } extension TypeConverter { func convertBoxType(_ T: BoxType) -> TypeCache.Entry { // We can share a type info for all dynamic-sized heap metadata. let UT = T.underlyingType let eltTI = self.IGM.getTypeInfo(UT) guard let fixedTI = eltTI as? FixedTypeInfo else { return .typeInfo(NonFixedBoxTypeInfo(IGM)) } // For fixed-sized types, we can emit concrete box metadata. if fixedTI.isKnownEmpty { return .typeInfo(EmptyBoxTypeInfo(IGM)) } return .typeInfo(FixedBoxTypeInfo(IGM, T.underlyingType)) } } extension TypeConverter { func convertFunctionType(_ T: Seismography.FunctionType) -> TypeCache.Entry { return .typeInfo(FunctionTypeInfo(self.IGM, T, PointerType.toVoid, self.IGM.getPointerSize(), self.IGM.getPointerAlignment())) } }
mit
21954b8e8e9b17cf872668484c42a309
30.275109
79
0.662245
4.258026
false
false
false
false
hanwanjie853710069/Easy-living
易持家/Class/Class_project/ECAdd/View/AddTimeVcCell.swift
1
3492
// // AddTimeVcCell.swift // 易持家 // // Created by 王木木 on 16/5/20. // Copyright © 2016年 王木木. All rights reserved. // import UIKit class AddTimeVcCell: UITableViewCell { var timer: NSTimer! var number = 0 static let cellId = "timeCell" var rollingLabel:UILabel = { let label = UILabel.init(frame: CGRectMake(ScreenWidth, 70, 770, 30)) label.font = UIFont.systemFontOfSize(16) label.text = queryDataWeather() return label }() lazy var timeBtn :UIButton = { let btn = UIButton() btn.backgroundColor = UIColor.whiteColor() btn.setTitle(getLocalTime(), forState: .Normal) btn.setTitleColor(UIColor.brownColor(), forState: .Normal) btn.titleLabel?.textAlignment = .Center btn.addTarget(self, action: #selector(self.addTime), forControlEvents: .TouchUpInside) return btn }() //闭包类似回调 typealias callbackfunc=()->() var myFunc = callbackfunc?() class func cellFor(tableView: UITableView) ->AddTimeVcCell{ var cell = tableView.dequeueReusableCellWithIdentifier(self.cellId) as?AddTimeVcCell if cell == nil { cell = AddTimeVcCell.init(style: .Default, reuseIdentifier: self.cellId) cell?.selectionStyle = .None } return cell! } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) creatUI() } func creatUI(){ timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(self.runColor), userInfo: nil, repeats: true) let nameLabel = UILabel() nameLabel.text = "消费日期" nameLabel.textColor = DarkGrayTextColor nameLabel.textAlignment = .Center self.addSubview(nameLabel) nameLabel.autoAlignAxisToSuperviewAxis(.Vertical) nameLabel.autoPinEdgeToSuperviewEdge(.Top, withInset: 10) nameLabel.autoSetDimensionsToSize(CGSizeMake(100, 30)) /// 消费时间 self.addSubview(self.timeBtn) self.timeBtn.autoPinEdgeToSuperviewEdge(.Left) self.timeBtn.autoPinEdgeToSuperviewEdge(.Right) self.timeBtn.autoPinEdge(.Top, toEdge: .Bottom, ofView: nameLabel, withOffset: 0) self.timeBtn.autoSetDimension(.Height, toSize: 30) self.addSubview(self.rollingLabel) self.addSubview(self.rollingLabel) } func addTime(){ UIApplication.sharedApplication().keyWindow?.endEditing(true) myFunc!() } func initBack( mathFunction:()->() ){ myFunc = mathFunction } func runColor(){ // timeBtn.setTitleColor(randomColor(hue: .Random, luminosity: .Random), forState: .Normal) // timeBtn.backgroundColor = randomColor(hue: .Random, luminosity: .Random) number += 1 if number%10 == 0 { self.rollingLabel.textColor = randomColor(hue: .Random, luminosity: .Random) } self.rollingLabel.frame.origin.x -= 5 if self.rollingLabel.frame.origin.x < -self.rollingLabel.frame.size.width { self.rollingLabel.frame = CGRectMake(ScreenWidth, 70, self.rollingLabel.frame.size.width, 30) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
a94d66e3945babc412fb3faa28fe2870
32.427184
140
0.633459
4.431145
false
false
false
false
headione/eggy
Eggy/GameViewController.swift
1
7983
// // GameViewController.swift // Eggy // // Created by Norman Sander on 16.05.15. // Copyright (c) 2015 Norman Sander. All rights reserved. // import UIKit import QuartzCore import SceneKit class GameViewController: UIViewController { @IBOutlet weak var skView: SCNView! @IBOutlet weak var label: UILabel! @IBOutlet weak var button: UIButton! var currentAngle: Float = 0.0 var top: SCNNode = SCNNode() var seconds: Double = 0 var prevSeconds: Double = 0 var endDate: Date? var timer: Timer? var finished: Bool = true var soundManager: SoundManager? override func viewDidLoad() { self.label.font = UIFont(name: "Futura-CondensedMedium", size: 25) // Register sounds self.soundManager = SoundManager.shared self.soundManager?.register("tick", loops: -1, volume: 0.5) // self.soundManager?.register("tick2") self.soundManager?.register("ring") super.viewDidLoad() // 3D setup let scene = SCNScene(named: "art.scnassets/egg")! let cameraNode = SCNNode() // let lightNode = SCNNode() // Cam cameraNode.camera = SCNCamera() cameraNode.position = SCNVector3(x: 0, y: 0, z: 4) scene.rootNode.addChildNode(cameraNode) // Light // TODO // lightNode.light = SCNLight() // lightNode.position = SCNVector3(x: 0, y: 0, z: 4) // scene.rootNode.addChildNode(lightNode) // Define parts of object self.top = scene.rootNode.childNode(withName: "Top", recursively: true)! scene.rootNode.childNode(withName: "Bottom", recursively: true) let scnView = self.skView scnView?.scene = scene #if DEBUG scnView.showsStatistics = true Helper.printFonts() #endif scnView?.backgroundColor = UIColor.white // Add gesture recognizer let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(GameViewController.panGesture(_:))) scnView?.addGestureRecognizer(panRecognizer) self.updateLabel() self.button.titleLabel?.font = UIFont(name: "Futura-CondensedMedium", size: 25) self.button.setTitle("Start", for: UIControlState()) self.button.setTitle("Stop", for: UIControlState.selected) self.button.layer.cornerRadius = 8.0 self.button.isEnabled = false self.button.layer.borderColor = UIColor.lightGray.cgColor self.button.setTitleColor(UIColor.gray, for: UIControlState.disabled) self.button.setTitleColor(UIColor.white, for: UIControlState()) self.button.setTitleColor(UIColor.white, for: UIControlState.selected) updateButtonBg() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(deviceRotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } override func viewWillDisappear(_ animated: Bool) { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } func deviceRotated(){ if UIDeviceOrientationIsLandscape(UIDevice.current.orientation) { print("Landscape") } if UIDeviceOrientationIsPortrait(UIDevice.current.orientation) { print("Portrait") } } func startTimer() { if self.seconds == 0 { return } self.button.isSelected = true self.endDate = Date().addingTimeInterval(self.seconds) self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(GameViewController.update), userInfo: nil, repeats: true) self.finished = false self.soundManager!.play("tick") self.updateButtonBg() } func stopTimer() { self.timer?.invalidate() self.finished = true self.button.isSelected = false self.soundManager!.stop("tick") self.updateButtonBg() } func ring() { if !self.finished { stopTimer() self.button.isEnabled = false self.soundManager!.play("ring") self.updateButtonBg() } } override var shouldAutorotate: Bool { return true } // override var prefersStatusBarHidden: Bool { // return true // } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return UIInterfaceOrientationMask.allButUpsideDown } else { return UIInterfaceOrientationMask.all } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } func panGesture(_ sender: UIPanGestureRecognizer) { self.stopTimer() self.updateButtonBg() self.button.isEnabled = true let translation = sender.translation(in: sender.view!) var angle: Float if sender.state == UIGestureRecognizerState.changed { angle = (Float)(translation.x * 0.3) * (Float)(Double.pi) / 180.0 angle += self.currentAngle if angle > 0 { angle = 0 } self.seconds = 60 * Double(round((-angle * 3600) / ((Float)(Double.pi) * 2) / 60)) self.updateLabel() self.top.rotation = SCNVector4Make(0, 1, 0, angle) print(self.seconds) // if (self.seconds != self.prevSeconds) { // self.soundManager!.play("tick2") // } self.prevSeconds = self.seconds } else if sender.state == UIGestureRecognizerState.ended { if !self.finished && self.seconds > 0 { self.startTimer() } if seconds == 0 { self.ring() } self.setRotation(self.seconds) } } func update() { if self.endDate != nil { self.seconds = round(self.endDate!.timeIntervalSinceNow) } else { self.seconds = 0 } print(self.seconds) self.setRotation(self.seconds) self.updateLabel() if self.seconds <= 0 { self.seconds = 0 self.ring() } } func setRotation(_ seconds: Double) { let newAngle = (Float(-self.seconds) * (Float)(Double.pi) * 2) / 3600 self.top.rotation = SCNVector4Make(0, 1, 0, newAngle) self.currentAngle = newAngle } func updateLabel() { let seconds: Int = Int(self.seconds.truncatingRemainder(dividingBy: 60)) let minutes: Int = Int((self.seconds / 60).truncatingRemainder(dividingBy: 60)) let hours: Int = Int(self.seconds / 3600) if(hours > 0) { label.text = String(format: "%02d:%02d:%02d", hours, minutes, seconds) } else { label.text = String(format: "%02d:%02d", minutes, seconds) } } func updateButtonBg() { if !self.button.isEnabled { self.button.backgroundColor = UIColor.clear self.button.layer.borderWidth = 1.0 return } self.button.layer.borderWidth = 0 if self.finished { self.button.backgroundColor = UIColor(red: 70 / 255, green: 178 / 255, blue: 157 / 255, alpha: 1) } else { self.button.backgroundColor = UIColor(red: 222 / 255, green: 73 / 255, blue: 73 / 255, alpha: 1) } } @IBAction func btnPressed(_ sender: UIButton) { self.timer?.invalidate() if self.finished { self.startTimer() } else { self.stopTimer() } } @IBAction func showInfo(_ segue: UIStoryboardSegue) { } }
mit
911193d31d1611627b2d0ebd708b4ea4
30.804781
157
0.596017
4.582664
false
false
false
false
coodly/ios-gambrinus
Packages/Sources/KioskCore/Network/NetworkQueue.swift
1
1305
/* * Copyright 2018 Coodly LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation internal class NetworkQueue { private lazy var operationsQueue: OperationQueue = { let queue = OperationQueue() queue.name = "Network queue" queue.qualityOfService = .utility return queue }() internal func append(_ request: URLRequest, priority: Operation.QueuePriority = .normal, completion: @escaping (Data?, URLResponse?, Error?) -> ()) { Log.debug("Append request to \(String(describing: request.url))") let networkRequest = NetworkRequest(request: request) networkRequest.resultHandler = completion networkRequest.queuePriority = priority operationsQueue.addOperation(networkRequest) } }
apache-2.0
e9d210276dca2562361c25359b99af31
36.285714
153
0.704981
4.815498
false
false
false
false
matheusfrozzi/MaskedLabelSwift
MaskedLabelSwift/MaskedLabel.swift
1
1873
// // CustomLabel.swift // Flockr Cam // // Created by Matheus Frozzi Alberton on 27/10/15. // Copyright © 2015 720. All rights reserved. // import UIKit class MaskedLabel: UILabel { var maskColor : UIColor? override init(frame: CGRect) { super.init(frame: frame) customInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) customInit() } func customInit() { maskColor = self.backgroundColor self.textColor = UIColor.whiteColor() backgroundColor = UIColor.clearColor() self.opaque = false } override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() super.drawRect(rect) CGContextConcatCTM(context, CGAffineTransformMake(1, 0, 0, -1, 0, CGRectGetHeight(rect))) let image: CGImageRef = CGBitmapContextCreateImage(context)! let mask: CGImageRef = CGImageMaskCreate(CGImageGetWidth(image), CGImageGetHeight(image), CGImageGetBitsPerComponent(image), CGImageGetBitsPerPixel(image), CGImageGetBytesPerRow(image), CGImageGetDataProvider(image), CGImageGetDecode(image), CGImageGetShouldInterpolate(image))! CGContextClearRect(context, rect) CGContextSaveGState(context) CGContextClipToMask(context, rect, mask) if (self.layer.cornerRadius != 0.0) { CGContextAddPath(context, CGPathCreateWithRoundedRect(rect, self.layer.cornerRadius, self.layer.cornerRadius, nil)) CGContextClip(context) } drawBackgroundInRect(rect) CGContextRestoreGState(context) } func drawBackgroundInRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() if let _ = maskColor { maskColor!.set() } CGContextFillRect(context, rect) } }
mit
84be243a218ffd6a9112be56ab4a268e
27.8
286
0.661859
4.8
false
false
false
false
longsirhero/DinDinShop
DinDinShopDemo/DinDinShopDemo/海外/Views/WCSeasCountryHeadView.swift
1
1618
// // WCSeasCountryHeadView.swift // DinDinShopDemo // // Created by longsirHERO on 2017/8/23. // Copyright © 2017年 WingChingYip(https://longsirhero.github.io) All rights reserved. // import UIKit import FSPagerView class WCSeasCountryHeadView: UICollectionReusableView { let pagerView = FSPagerView() var dataSource:NSArray = NSArray() { didSet { self.pagerView.reloadData() } } override init(frame: CGRect) { super.init(frame: frame) pagerView.automaticSlidingInterval = 3.0 pagerView.isInfinite = true pagerView.dataSource = self pagerView.delegate = self pagerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell") self.addSubview(pagerView) pagerView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension WCSeasCountryHeadView:FSPagerViewDataSource,FSPagerViewDelegate { func numberOfItems(in pagerView: FSPagerView) -> Int { return dataSource.count } func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell { let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index) let model:WCSeasCountryBanerModel = dataSource[index] as! WCSeasCountryBanerModel cell.imageView?.kf.setImage(with: URL(string: model.picLogpath!)) return cell } }
mit
02f038c97c4b70ea51880ef0aa39c962
26.372881
91
0.653251
4.575071
false
false
false
false
remobjects/ElementsSamples
Silver/All/Calculator/Calculator.Engine/Evaluator.swift
1
4144
import RemObjects.Elements.RTL enum EvaluatorTokenType: Int32 { case EOF case Number case Op_Add case Op_Sub case Op_Mul case Op_Div case Error } class EvaluatorError: Exception { } class EvaluatorToken { public init(token: EvaluatorTokenType, value: String, offset: Integer) { self.Token = token self.Value = value self.Offset = offset } public let Token: EvaluatorTokenType public let Value: String public let Offset: Integer } public class Evaluator { public init() { } private static let EOF = EvaluatorToken(token: EvaluatorTokenType.EOF, value: "", offset: 0) private var Tokens: List<EvaluatorToken>! private var Index: Int = 0 // returns the current token, or EOF if at the end private var Current: EvaluatorToken { if Tokens != nil && Index < Tokens.Count { return Tokens[Index] } return EOF } // Evaluates a string expression like (1 + 2 * 4.5) and return the evaluated value public func Evaluate(_ input: String) -> Double { Tokens = Tokenize(input) Index = 0 return ParseAdditionExpression() } // Parses + and - expressions, this is split from * and / so that // + and - have a lower prescendence than * and / private func ParseAdditionExpression() -> Double { var l = ParseMultiplicationExpression() while Current.Token == EvaluatorTokenType.Op_Sub || Current.Token == EvaluatorTokenType.Op_Add { let sub = Current.Token == EvaluatorTokenType.Op_Sub Index += 1 let r = ParseMultiplicationExpression() if (sub) { l = l - r } else { l = l + r } } return l } // Parse * and / private func ParseMultiplicationExpression() -> Double { var l = ParseValueExpression() while Current.Token == EvaluatorTokenType.Op_Mul || Current.Token == EvaluatorTokenType.Op_Div { let mul = Current.Token == EvaluatorTokenType.Op_Mul Index += 1 let r = ParseValueExpression() if (mul) { l = l * r } else { l = l / r } } return l } private func ParseValueExpression() -> Double { switch (Current.Token) { case EvaluatorTokenType.Op_Add: // Process +15 as unary Index += 1 return ParseValueExpression() case EvaluatorTokenType.Op_Sub: // Process -15 as unary Index += 1 return -ParseValueExpression() case EvaluatorTokenType.Number: var res = Current.Value Index += 1 return Convert.ToDoubleInvariant(res) case EvaluatorTokenType.EOF: __throw EvaluatorError("Unexected end of expression") default: __throw EvaluatorError("Unknown value at offset \(Current.Offset)") } } // Splits the string into parts; skipping whitespace private static func Tokenize(_ input: String) -> List<EvaluatorToken> { var res = List<EvaluatorToken>() var input = input; // for parsing convenience so look ahead won't throw exceptions. input = input + "\0\0" var i = 0 while (i < input.Length) { var c: Int = i switch (input[i]){ case "\0": i = input.Length case "0", "1","2","3","4","5","6","7","8","9",".": c = i + 1 var gotDot = input[i] == "." while true { var ch = input[c] if ch == "0" || ch == "1" || ch == "2" || ch == "3" || ch == "4" || ch == "5" || ch == "6" || ch == "7" || ch == "8" || ch == "9" || (!gotDot && ch == ".") { c += 1 if (ch == ".") { gotDot = true } } else { break } } res.Add(EvaluatorToken(token: EvaluatorTokenType.Number, value: input.Substring(i, c-i), offset: i)) i = c case "+": res.Add(EvaluatorToken(token: EvaluatorTokenType.Op_Add, value: "+", offset: i)) i += 1 case "-": res.Add(EvaluatorToken(token: EvaluatorTokenType.Op_Sub, value: "-", offset: i)) i += 1 case "*": res.Add(EvaluatorToken(token: EvaluatorTokenType.Op_Mul, value: "*", offset: i)) i += 1 case "/": res.Add(EvaluatorToken(token: EvaluatorTokenType.Op_Div, value: "/", offset: i)) i += 1 case " ", "\t", "\r", "\n": i += 1 default: res.Add(EvaluatorToken(token: EvaluatorTokenType.Error, value: input[i], offset: i)) i += 1 } } return res } }
mit
773f8729817191e3a17ac1531b63706a
25.551282
114
0.618059
3.266562
false
false
false
false
practicalswift/swift
validation-test/compiler_crashers_2_fixed/0127-sr5546.swift
34
782
// RUN: not %target-swift-frontend %s -typecheck // REQUIRES: asserts public struct Foo<A, B, C> {} public protocol P { associatedtype PA associatedtype PB = Never associatedtype PC = Never typealias Context = Foo<PA, PB, PC> func f1(_ x: Context, _ y: PA) func f2(_ x: Context, _ y: PB) func f3(_ x: Context, _ y: PC) func f4(_ x: Context) } public extension P { public func f1(_ x: Context, _ y: PA) { } public func f2(_ x: Context, _ y: PB) { } public func f3(_ x: Context, _ y: PC) { } public func f4(_ x: Context) { } } public struct S: P { public typealias PA = String public typealias PB = Int public func f1(_ x: Context, _ y: PA) { } public func f2(_ x: Context, _ y: PB) { } }
apache-2.0
262956f793002232ba0f289d284e3c2f
19.578947
48
0.561381
3.128
false
false
false
false
zhangliangzhi/iosStudyBySwift
SavePassword/SavePassword/UpdateViewController.swift
1
6052
// // UpdateViewController.swift // SavePassword // // Created by ZhangLiangZhi on 2016/12/24. // Copyright © 2016年 xigk. All rights reserved. // import UIKit import CloudKit class UpdateViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate { @IBOutlet weak var localCancle: UIButton! @IBOutlet weak var localSave: UIButton! @IBOutlet weak var localNote: UILabel! @IBOutlet weak var localURL: UILabel! @IBOutlet weak var localTitle: UILabel! @IBOutlet weak var sortID: UITextField! @IBOutlet weak var tfTitle: UITextField! @IBOutlet weak var urltxt: UITextField! @IBOutlet weak var textView: UITextView! @IBOutlet weak var lastUpdateTime: UILabel! override func viewDidLoad() { super.viewDidLoad() sortID.delegate = self tfTitle.delegate = self urltxt.delegate = self textView.delegate = self self.title = NSLocalizedString("Update", comment: "") // init data urltxt.text = "" initSpData() initLocalize() textView.becomeFirstResponder() } func initSpData() { let one = arrData[gIndex] let iID:Int64 = (one.value(forKey: "ID") as! Int64?)! sortID.text = String(iID) tfTitle.text = one.value(forKey: "title") as! String? urltxt.text = one.value(forKey: "url") as! String? textView.text = one.value(forKey: "spdata") as! String? let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss" let update:String = dateFormatter.string(from: one.modificationDate!) lastUpdateTime.text = update } func initLocalize() { localTitle.text = NSLocalizedString("Title", comment: "") + ":" localURL.text = NSLocalizedString("URL", comment: "") + ":" localNote.text = NSLocalizedString("Note", comment: "") localCancle.setTitle(NSLocalizedString("Cancel", comment: ""), for: .normal) localSave.setTitle(NSLocalizedString("Save", comment: ""), for: .normal) sortID.placeholder = NSLocalizedString("Enter Sort ID", comment: "") tfTitle.placeholder = NSLocalizedString("Enter Title", comment: "") urltxt.placeholder = NSLocalizedString("Enter URL", comment: "") } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == sortID { tfTitle.becomeFirstResponder() }else if textField == tfTitle { urltxt.becomeFirstResponder() }else if textField == urltxt { textView.becomeFirstResponder() }else{ } return true } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { // 延迟1毫秒 执行 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1 * NSEC_PER_SEC))/Double(1000*NSEC_PER_SEC) , execute: { self.textView.resignFirstResponder() }) } return true } // 保存数据 @IBAction func saveAction(_ sender: Any) { var id:String = sortID.text! var title:String = tfTitle.text! var url:String = urltxt.text! let spData:String = textView.text! id = id.trimmingCharacters(in: .whitespaces) title = title.trimmingCharacters(in: .whitespaces) url = url.trimmingCharacters(in: .whitespaces) // id 是否为空 if id == "" { self.view.makeToast(NSLocalizedString("IDnot", comment: ""), duration: 3.0, position: .center) return } let iID = Int64(id) if iID == nil { self.view.makeToast(NSLocalizedString("IDnot", comment: ""), duration: 3.0, position: .center) return } // id是否重复 // var icount = 0 // for i in 0..<arrData.count { // let getID = arrData[i].value(forKey: "ID") // let igetID:Int64 = getID as! Int64 // if iID == igetID { // icount += 1 // } // } // if icount > 1 { // self.view.makeToast(NSLocalizedString("IDre", comment: ""), duration: 3.0, position: .center) // return // } self.view.isUserInteractionEnabled = false let one = arrData[gIndex] one["ID"] = iID as CKRecordValue? one["title"] = title as CKRecordValue? one["url"] = url as CKRecordValue? one["spdata"] = spData as CKRecordValue? CKContainer.default().privateCloudDatabase.save(one) { (record:CKRecord?, err:Error?) in if err == nil { print("update sucess") // 保存成功 DispatchQueue.main.async { self.view.makeToast(NSLocalizedString("savesucess", comment: ""), duration: 3.0, position: .center) self.navigationController!.popViewController(animated: true) } }else { // 保存不成功 print("update fail") DispatchQueue.main.async { self.view.isUserInteractionEnabled = true // 弹框网络不行 let alert = UIAlertController(title: "⚠️ iCloud ⚠️", message: err?.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "ok", style: .default, handler: { (action:UIAlertAction) in })) self.present(alert, animated: true, completion: nil) } } } } // 取消 @IBAction func cancleAction(_ sender: Any) { navigationController!.popViewController(animated: true) } }
mit
6c548e84c181c7860f9aa73edd5324a7
33.316092
143
0.561045
4.772982
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/BuySellKit/Core/Client/Model/Network/PaymentMethodsResponse.swift
1
4073
// Copyright © Blockchain Luxembourg S.A. All rights reserved. /// The available payment methods public struct PaymentMethodsResponse: Decodable { public struct Method: Decodable { /// Mobile payment types enum MobilePaymentType: String, Decodable { case applePay = "APPLE_PAY" case googlePay = "GOOGLE_PAY" } /// The limits for a given window of time (e.g. annual or daily) struct Limits: Decodable { let available: String let limit: String let used: String enum CodingKeys: String, CodingKey { case available case limit case used } // MARK: - Init init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let availableValue = try values.decode(Int.self, forKey: .available) let limitValue = try values.decode(Int.self, forKey: .limit) let usedValue = try values.decode(Int.self, forKey: .used) available = String(availableValue) limit = String(limitValue) used = String(usedValue) } } struct PaymentMethodLimits: Decodable { /// The minimum limit per transaction let min: String /// The max limit per transaction let max: String /// The limits for the year let annual: Limits? /// The limits for a single day of transactions. let daily: Limits? /// The limits for a single week of transactions. let weekly: Limits? enum CodingKeys: String, CodingKey { case min case max case annual case daily case weekly } // MARK: - Init init( min: String, max: String, annual: Limits? = nil, daily: Limits? = nil, weekly: Limits? = nil ) { self.min = min self.max = max self.annual = annual self.daily = daily self.weekly = weekly } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) min = try values.decode(String.self, forKey: .min) max = try values.decode(String.self, forKey: .max) annual = try values.decodeIfPresent(Limits.self, forKey: .annual) daily = try values.decodeIfPresent(Limits.self, forKey: .daily) weekly = try values.decodeIfPresent(Limits.self, forKey: .weekly) } } let type: String /// The boundaries of the method (min / max) let limits: PaymentMethodLimits? /// The supported subtypes of the payment method /// e.g for a card payment method: ["VISA", "MASTERCARD"] let subTypes: [String] /// The currency limiter of the method let currency: String? /// The eligible state of the payment let eligible: Bool /// When `true`, the payment method can be shown to the user let visible: Bool /// Enables Apple Pay let mobilePayment: [MobilePaymentType]? } /// The currency for the payment method (e.g: `USD`) let currency: String /// The available methods of payment let methods: [Method] } extension PaymentMethodsResponse { public var applePayEligible: Bool { methods.contains { method in method.applePayEligible } } } extension PaymentMethodsResponse.Method { public var applePayEligible: Bool { guard let mobilePayment = mobilePayment else { return false } return mobilePayment.contains { type in type == .applePay } } }
lgpl-3.0
05ef6ca2bc7db5f616f6d06458405680
30.083969
84
0.538065
5.200511
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeCore/AwesomeCore/Classes/Model/QuestSection.swift
1
2459
// // QuestSection.swift // AwesomeCore // // Created by Evandro Harrison Hoffmann on 11/3/17. // import Foundation public struct QuestSection: Codable, Equatable { public let coverAsset: QuestAsset? public let duration: Double? public let id: String? public let info: QuestSectionInfo? public let position: Int? public var primaryAsset: QuestAsset? public let type: String? public let pageId: String? // FK to the CDPage public let productPageId: String? // FK to the CDProductPage public init(coverAsset: QuestAsset?, duration: Double?, id: String?, info: QuestSectionInfo?, position: Int?, primaryAsset: QuestAsset?, type: String?, pageId: String? = nil, productPageId: String? = nil) { self.coverAsset = coverAsset self.duration = duration self.id = id self.info = info self.position = position self.primaryAsset = primaryAsset self.type = type self.pageId = pageId self.productPageId = productPageId } // MARK: - Type information public var sectionType: QuestSectionType { guard let type = type else { return .text } return QuestSectionType(rawValue: type) ?? .text } } // MARK: - Content Section Types public enum QuestSectionType: String { case video case audio case text case file case image case enroll } // MARK: - JSON Key public struct QuestSections: Codable { public let sections: [QuestSection] } // MARK: - Equatable extension QuestSection { public static func ==(lhs: QuestSection, rhs: QuestSection) -> Bool { if lhs.coverAsset != rhs.coverAsset { return false } if lhs.duration != rhs.duration { return false } if lhs.id != rhs.id { return false } if lhs.info != rhs.info { return false } if lhs.position != rhs.position { return false } if lhs.primaryAsset != rhs.primaryAsset { return false } if lhs.type != rhs.type { return false } if lhs.pageId != rhs.pageId { return false } if lhs.productPageId != rhs.productPageId { return false } return true } }
mit
4329c78318975d5eb4f82418ada1b9c2
22.419048
73
0.568117
4.470909
false
false
false
false
jhurray/SelectableTextView
Examples/SelectableTestView-Example/ViewController.swift
1
6516
// // ViewController.swift // SelectableTestView-Example-iOS // // Created by Jeff Hurray on 2/5/17. // Copyright © 2017 jhurray. All rights reserved. // import UIKit import SelectableTextView import SafariServices class ViewController: UIViewController, SelectableTextViewDelegate { @IBOutlet weak var textView: SelectableTextView! @IBOutlet weak var heightConstraint: NSLayoutConstraint! var hashtagFrame: CGRect? { let frames = textView.framesOfWordsMatchingValidator(HashtagTextValidator()) return frames.first } override func viewDidLoad() { super.viewDidLoad() textView.delegate = self let githubLink = "https://github.com/jhurray/SelectableTextView" textView.text = "Hello, I'm {{my_name}}\0. I made \(githubLink) to solve the problem of highlighting and selecting specific text in UILabel and UITextView. An example is a hashtag like #Stars or an unsafe link like http://google.com\0!" let unsafeLinkValidator = UnsafeLinkValidator() textView.registerValidator(unsafeLinkValidator) { (text, validator) in self.showAlert(title: "🚫", message: "This link is bad mm'kay!") } textView.registerValidator(UIClassValidator()) let githubLinkValidator = CustomLinkValidator(urlString: githubLink, replacementText: "SelectableTextView") textView.registerValidator(githubLinkValidator) { (text, validator) in if let linkValidator = validator as? CustomLinkValidator { self.openWebView(url: linkValidator.url) } } let myNameValidator = HandlebarsValidator(searchableText: "my_name", replacementText: "Jeff Hurray") textView.registerValidator(myNameValidator) { (text, validator) in self.openWebView(url: URL(string: "https://twitter.com/jeffhurray")!) } textView.registerValidator(HashtagTextValidator()) { (text, validator) in self.createParticles(seconds: 1) } } func showAlert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } func openWebView(url: URL) { let browser = SFSafariViewController(url: url) present(browser, animated: true, completion: nil) } func animateExpansionButtonForSelectableTextView(textView: SelectableTextView) -> Bool { return false } func selectableTextViewContentHeightDidChange(textView: SelectableTextView, oldHeight: CGFloat, newHeight: CGFloat) { numberOfLinesLabel.text = "\(textView.numberOfLines)" heightConstraint.constant = min(newHeight, view.bounds.height) view.setNeedsLayout() } // MARK: Customization @IBOutlet weak var numberOfLinesLabel: UILabel! @IBOutlet weak var lineSpacingLabel: UILabel! @IBOutlet weak var numberOfLinesStepper: UIStepper! @IBOutlet weak var lineSpacingStepper: UIStepper! @IBAction func textAlignmentSelected(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: textView.textAlignment = .left break case 1: textView.textAlignment = .center break case 2: textView.textAlignment = .right break default: break } } @IBAction func truncationModeSelected(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: textView.truncationMode = .clipping break case 1: textView.truncationMode = .truncateTail break default: break } } @IBAction func numberOfLinesSelected(_ sender: UIStepper) { textView.numberOfLines = Int(sender.value) numberOfLinesLabel.text = "\(textView.numberOfLines)" } @IBAction func lineSpacingSelected(_ sender: UIStepper) { textView.lineSpacing = CGFloat(sender.value) lineSpacingLabel.text = "\(textView.lineSpacing)" } @IBAction func addExpansionButtonToggled(_ sender: UISwitch) { if sender.isOn { let attributes: [NSAttributedStringKey: Any] = [HighlightedTextSelectionAttributes.SelectedBackgroundColorAttribute : UIColor.purple.withAlphaComponent(0.5)] let collapsedNumberOfLines = max(Int(numberOfLinesStepper.value), 1) textView.addExpansionButton(collapsedState: ("More...", collapsedNumberOfLines), expandedState: ("Less", 0), attributes: attributes) } else { textView.removeExpansionButton(numberOfLines: Int(numberOfLinesStepper.value)) } } func createParticles(seconds: TimeInterval) { if let frame = hashtagFrame { let particleEmitter = CAEmitterLayer() let center = CGPoint(x: frame.origin.x + frame.width / 2, y: frame.origin.y + frame.height / 2) particleEmitter.emitterPosition = center particleEmitter.emitterShape = kCAEmitterLayerPoint particleEmitter.emitterSize = frame.size let cell = makeEmitterCell() particleEmitter.emitterCells = [cell] textView.layer.addSublayer(particleEmitter) DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { particleEmitter.removeFromSuperlayer() } } } func makeEmitterCell() -> CAEmitterCell { let cell = CAEmitterCell() let image = UIImage(named: "star")?.withRenderingMode(.alwaysTemplate) cell.contents = image?.cgImage cell.birthRate = 12 cell.lifetime = 1.0 cell.lifetimeRange = 0.2 cell.velocity = 50 cell.velocityRange = 20 cell.emissionRange = CGFloat.pi * 2 cell.spin = 2 cell.spinRange = 3 cell.scaleRange = 0.5 cell.scaleSpeed = -0.05 cell.alphaSpeed = 0.5 cell.alphaRange = 0 cell.scale = 1.0 cell.scaleSpeed = 0.5 cell.color = UIColor.yellow.cgColor return cell } }
mit
c62c696df59e53f6d8eeb9a6fd10122f
35.379888
244
0.6293
5.079563
false
false
false
false
san2ride/iOS10-FHG1.0
FHG1.1/FHG1.1/HelpTableViewController.swift
1
1741
// // HelpTableViewController.swift // FHG1.1 // // Created by don't touch me on 2/7/17. // Copyright © 2017 trvl, LLC. All rights reserved. // import UIKit class HelpTableViewController: UITableViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 128, height: 42)) imageView.contentMode = .scaleAspectFit let image = UIImage(named: "fhgnew4") imageView.image = image navigationItem.titleView = imageView } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let url : URL? switch indexPath.section { case 0: switch indexPath.row { case 0: url = URL(string: "http://www.thefhguide.com/project-6-help.html#goal-1") case 1: url = URL(string: "http://www.thefhguide.com/project-6-help.html#goal-2") case 2: url = URL(string: "http://www.thefhguide.com/project-6-help.html#goal-3") case 3: url = URL(string: "http://www.thefhguide.com/project-6-help.html#goal-4") case 4: url = URL(string: "http://www.thefhguide.com/project-6-help.html#goal-5") case 5: url = URL(string: "http://www.thefhguide.com/project-6-help.html#goal-6") default: return; } default: return; } if url != nil { UIApplication.shared.open(url!, options: [:], completionHandler: nil) } } }
mit
71a1352213ca2d1ead17e76785776908
29.526316
92
0.545402
4.065421
false
false
false
false
Andgfaria/MiniGitClient-iOS
MiniGitClient/MiniGitClientTests/Scenes/List/Cell/RepositoryListTableViewCellSpec.swift
1
2772
/* Copyright 2017 - André Gimenez Faria 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 Quick import Nimble @testable import MiniGitClient class RepositoryListTableViewCellSpec: QuickSpec { override func spec() { describe("The RepositoryListTableViewCell") { var cell = RepositoryListTableViewCell() beforeEach { cell = RepositoryListTableViewCell() } context("has", { it("8 subviews") { expect(cell.contentView.subviews.count) == 8 } it("has 3 UIImageViews (2 private ones)") { expect(cell.contentView.subviews.flatMap { $0 as? UIImageView }.count) == 3 } it("has a title label") { expect(cell.titleLabel).toNot(beNil()) } it("has an info label") { expect(cell.infoLabel).toNot(beNil()) } it("has a stars count label") { expect(cell.starsCountLabel).toNot(beNil()) } it("has a forks count label") { expect(cell.forksCountLabel).toNot(beNil()) } it("has an avatar image view") { expect(cell.avatarImageView).toNot(beNil()) } it("has a repository user label") { expect(cell.repositoryUserLabel).toNot(beNil()) } }) } } }
mit
eeff57186850335dd46b6f516b07f00a
39.15942
461
0.557921
5.833684
false
false
false
false
darkbrow/iina
iina/ThumbnailCache.swift
1
6729
// // ThumbnailCache.swift // iina // // Created by lhc on 14/6/2017. // Copyright © 2017 lhc. All rights reserved. // import Cocoa fileprivate let subsystem = Logger.Subsystem(rawValue: "thumbcache") class ThumbnailCache { private typealias CacheVersion = UInt8 private typealias FileSize = UInt64 private typealias FileTimestamp = Int64 static private let version: CacheVersion = 2 static private let sizeofMetadata = MemoryLayout<CacheVersion>.size + MemoryLayout<FileSize>.size + MemoryLayout<FileTimestamp>.size static private let imageProperties: [NSBitmapImageRep.PropertyKey: Any] = [ .compressionFactor: 0.75 ] static func fileExists(forName name: String) -> Bool { return FileManager.default.fileExists(atPath: urlFor(name).path) } static func fileIsCached(forName name: String, forVideo videoPath: URL?) -> Bool { guard let fileAttr = try? FileManager.default.attributesOfItem(atPath: videoPath!.path) else { Logger.log("Cannot get video file attributes", level: .error, subsystem: subsystem) return false } // file size guard let fileSize = fileAttr[.size] as? FileSize else { Logger.log("Cannot get video file size", level: .error, subsystem: subsystem) return false } // modified date guard let fileModifiedDate = fileAttr[.modificationDate] as? Date else { Logger.log("Cannot get video file modification date", level: .error, subsystem: subsystem) return false } let fileTimestamp = FileTimestamp(fileModifiedDate.timeIntervalSince1970) // Check metadate in the cache if self.fileExists(forName: name) { guard let file = try? FileHandle(forReadingFrom: urlFor(name)) else { Logger.log("Cannot open cache file.", level: .error, subsystem: subsystem) return false } let cacheVersion = file.read(type: CacheVersion.self) if cacheVersion != version { return false } return file.read(type: FileSize.self) == fileSize && file.read(type: FileTimestamp.self) == fileTimestamp } return false } /// Write thumbnail cache to file. /// This method is expected to be called when the file doesn't exist. static func write(_ thumbnails: [FFThumbnail], forName name: String, forVideo videoPath: URL?) { Logger.log("Writing thumbnail cache...", subsystem: subsystem) let maxCacheSize = Preference.integer(for: .maxThumbnailPreviewCacheSize) * FloatingPointByteCountFormatter.PrefixFactor.mi.rawValue if maxCacheSize == 0 { return } else if CacheManager.shared.getCacheSize() > maxCacheSize { CacheManager.shared.clearOldCache() } let pathURL = urlFor(name) guard FileManager.default.createFile(atPath: pathURL.path, contents: nil, attributes: nil) else { Logger.log("Cannot create file.", level: .error, subsystem: subsystem) return } guard let file = try? FileHandle(forWritingTo: pathURL) else { Logger.log("Cannot write to file.", level: .error, subsystem: subsystem) return } // version let versionData = Data(bytesOf: version) file.write(versionData) guard let fileAttr = try? FileManager.default.attributesOfItem(atPath: videoPath!.path) else { Logger.log("Cannot get video file attributes", level: .error, subsystem: subsystem) return } // file size guard let fileSize = fileAttr[.size] as? FileSize else { Logger.log("Cannot get video file size", level: .error, subsystem: subsystem) return } let fileSizeData = Data(bytesOf: fileSize) file.write(fileSizeData) // modified date guard let fileModifiedDate = fileAttr[.modificationDate] as? Date else { Logger.log("Cannot get video file modification date", level: .error, subsystem: subsystem) return } let fileTimestamp = FileTimestamp(fileModifiedDate.timeIntervalSince1970) let fileModificationDateData = Data(bytesOf: fileTimestamp) file.write(fileModificationDateData) // data blocks for tb in thumbnails { let timestampData = Data(bytesOf: tb.realTime) guard let tiffData = tb.image?.tiffRepresentation else { Logger.log("Cannot generate tiff data.", level: .error, subsystem: subsystem) return } guard let jpegData = NSBitmapImageRep(data: tiffData)?.representation(using: .jpeg, properties: imageProperties) else { Logger.log("Cannot generate jpeg data.", level: .error, subsystem: subsystem) return } let blockLength = Int64(timestampData.count + jpegData.count) let blockLengthData = Data(bytesOf: blockLength) file.write(blockLengthData) file.write(timestampData) file.write(jpegData) } CacheManager.shared.needsRefresh = true Logger.log("Finished writing thumbnail cache.", subsystem: subsystem) } /// Read thumbnail cache to file. /// This method is expected to be called when the file exists. static func read(forName name: String) -> [FFThumbnail]? { Logger.log("Reading thumbnail cache...", subsystem: subsystem) let pathURL = urlFor(name) guard let file = try? FileHandle(forReadingFrom: pathURL) else { Logger.log("Cannot open file.", level: .error, subsystem: subsystem) return nil } Logger.log("Reading from \(pathURL.path)", subsystem: subsystem) var result: [FFThumbnail] = [] // get file length file.seekToEndOfFile() let eof = file.offsetInFile // skip metadata file.seek(toFileOffset: UInt64(sizeofMetadata)) // data blocks while file.offsetInFile != eof { // length let blockLength: Int64 = file.read(type: Int64.self) // timestamp let timestamp: Double = file.read(type: Double.self) // jpeg let jpegData = file.readData(ofLength: Int(blockLength) - MemoryLayout.size(ofValue: timestamp)) guard let image = NSImage(data: jpegData) else { Logger.log("Cannot read image. Cache file will be deleted.", level: .warning, subsystem: subsystem) file.closeFile() // try deleting corrupted cache do { try FileManager.default.removeItem(at: pathURL) } catch { Logger.log("Cannot delete corrupted cache.", level: .error, subsystem: subsystem) } return nil } // construct let tb = FFThumbnail() tb.realTime = timestamp tb.image = image result.append(tb) } file.closeFile() Logger.log("Finished reading thumbnail cache, \(result.count) in total", subsystem: subsystem) return result } static private func urlFor(_ name: String) -> URL { return Utility.thumbnailCacheURL.appendingPathComponent(name) } }
gpl-3.0
d1e8758f17519bb293c14e1e5edeeaff
33.860104
136
0.684899
4.377358
false
false
false
false
dulingkang/CALayer-guide
CALayerGuide/CALayerGuide/Controller/CATextLayerViewController.swift
1
5375
// // CATextLayer.swift // CALayerGuide // // Created by ShawnDu on 15/11/3. // Copyright © 2015年 ShawnDu. All rights reserved. // import UIKit class CATextLayerViewController: UIViewController { @IBOutlet weak var viewForTextLayer: UIView! @IBOutlet weak var fontSizeSliderValueLabel: UILabel! @IBOutlet weak var fontSizeSlider: UISlider! @IBOutlet weak var wrapTextSwitch: UISwitch! @IBOutlet weak var alignmentModeSegmentedControl: UISegmentedControl! @IBOutlet weak var truncationModeSegmentedControl: UISegmentedControl! enum Font: Int { case Helvetica, NoteworthyLight } enum AlignmentMode: Int { case Left, Center, Justified, Right } enum TruncationMode: Int { case Start, Middle, End } var noteworthyLightFont: AnyObject? var helveticaFont: AnyObject? let baseFontSize: CGFloat = 24.0 let textLayer = CATextLayer() var fontSize: CGFloat = 24.0 var previouslySelectedTruncationMode = TruncationMode.End // MARK: - Quick reference func setUpTextLayer() { textLayer.frame = viewForTextLayer.bounds var string = "" for _ in 1...20 { string += "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor arcu quis velit congue dictum. " } textLayer.string = string textLayer.font = helveticaFont textLayer.foregroundColor = UIColor.darkGrayColor().CGColor textLayer.wrapped = true textLayer.alignmentMode = kCAAlignmentLeft textLayer.truncationMode = kCATruncationEnd textLayer.contentsScale = UIScreen.mainScreen().scale } func createFonts() { var fontName: CFStringRef = "Noteworthy-Light" noteworthyLightFont = CTFontCreateWithName(fontName, baseFontSize, nil) fontName = "Helvetica" helveticaFont = CTFontCreateWithName(fontName, baseFontSize, nil) } // MARK: - View life cycle override func viewDidLoad() { super.viewDidLoad() createFonts() setUpTextLayer() viewForTextLayer.layer.addSublayer(textLayer) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() textLayer.frame = viewForTextLayer.bounds print(textLayer.frame) textLayer.fontSize = fontSize print(textLayer.fontSize) } // MARK: - IBActions @IBAction func fontSegmentedControlChanged(sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case Font.Helvetica.rawValue: textLayer.font = helveticaFont case Font.NoteworthyLight.rawValue: textLayer.font = noteworthyLightFont default: break } } @IBAction func fontSizeSliderChanged(sender: UISlider) { fontSizeSliderValueLabel.text = "\(Int(sender.value * 100.0))%" fontSize = baseFontSize * CGFloat(sender.value) } @IBAction func wrapTextSwitchChanged(sender: UISwitch) { alignmentModeSegmentedControl.selectedSegmentIndex = AlignmentMode.Left.rawValue textLayer.alignmentMode = kCAAlignmentLeft if sender.on { if let truncationMode = TruncationMode(rawValue: truncationModeSegmentedControl.selectedSegmentIndex) { previouslySelectedTruncationMode = truncationMode } truncationModeSegmentedControl.selectedSegmentIndex = UISegmentedControlNoSegment textLayer.wrapped = true } else { textLayer.wrapped = false truncationModeSegmentedControl.selectedSegmentIndex = previouslySelectedTruncationMode.rawValue } } @IBAction func alignmentModeSegmentedControlChanged(sender: UISegmentedControl) { wrapTextSwitch.on = true textLayer.wrapped = true truncationModeSegmentedControl.selectedSegmentIndex = UISegmentedControlNoSegment textLayer.truncationMode = kCATruncationNone switch sender.selectedSegmentIndex { case AlignmentMode.Left.rawValue: textLayer.alignmentMode = kCAAlignmentLeft case AlignmentMode.Center.rawValue: textLayer.alignmentMode = kCAAlignmentCenter case AlignmentMode.Justified.rawValue: textLayer.alignmentMode = kCAAlignmentJustified case AlignmentMode.Right.rawValue: textLayer.alignmentMode = kCAAlignmentRight default: textLayer.alignmentMode = kCAAlignmentLeft } } @IBAction func truncationModeSegmentedControlChanged(sender: UISegmentedControl) { wrapTextSwitch.on = false textLayer.wrapped = false alignmentModeSegmentedControl.selectedSegmentIndex = UISegmentedControlNoSegment textLayer.alignmentMode = kCAAlignmentLeft switch sender.selectedSegmentIndex { case TruncationMode.Start.rawValue: textLayer.truncationMode = kCATruncationStart case TruncationMode.Middle.rawValue: textLayer.truncationMode = kCATruncationMiddle case TruncationMode.End.rawValue: textLayer.truncationMode = kCATruncationEnd default: textLayer.truncationMode = kCATruncationNone } } }
mit
2481958cfd92f091fd3157cc27c197c4
33.883117
125
0.672748
5.660695
false
false
false
false
qq565999484/RXSwiftDemo
SWIFT_RX_RAC_Demo/SWIFT_RX_RAC_Demo/Service.swift
1
4950
// // Service.swift // SWIFT_RX_RAC_Demo // // Created by chenyihang on 2017/6/6. // Copyright © 2017年 chenyihang. All rights reserved. // import Foundation import RxSwift import RxCocoa class ValidationService { static let shared = ValidationService() private init(){} let minCharactersCount = 6 func validateUsername(_ username: String) -> Observable<Result> { if username.characters.count == 0 { return .just(.empty) } if username.characters.count < minCharactersCount { return .just(.failed(message: "号码长度至少6个字符")) } if usernameValid(username) { return .just(.failed(message: "账户已存在")) } return .just(.ok(message:"用户名可用")) } func validatePassword(_ password: String) -> Result { if password.characters.count == 0 { return .empty } if password.characters.count < minCharactersCount { return .failed(message: "密码长度至少6个字符") } return .ok(message: "密码可用") } func validateRepeatedPassword(_ password: String, repeatedPasswordword: String) -> Result { if repeatedPasswordword.characters.count == 0 { return .empty } if repeatedPasswordword == password { return .ok(message: "密码可用") } return .failed(message: "两次密码不一样") } func register(_ username: String, password: String) -> Observable<Result> { let userDic = [username: password] if usernameValid(username) { return .just(.failed(message:"用户已存在")) } let filePath = NSHomeDirectory() + "/Documents/users.plist" if (userDic as NSDictionary).write(toFile: filePath, atomically: true) { return .just(.ok(message: "注册成功")) } return .just(.failed(message: "注册失败")) } //Observable.just func usernameValid(_ username: String) -> Bool { let filePath = NSHomeDirectory() + "/Documents/users.plist" let userDic = NSDictionary(contentsOfFile: filePath) let usernameArray = userDic!.allKeys as! Array<String> if usernameArray.contains(username) { return true }else{ return false } } func loginUsernameValid(_ username: String) -> Observable<Result> { if username.characters.count == 0 { return .just(.empty) } if usernameValid(username) { return .just(.ok(message:"用户名可用")) } return .just(.failed(message: "用户名不存在")) } func login(_ username: String, password: String) -> Observable<Result> { let filePath = NSHomeDirectory() + "/Documents/users.plist" let userDic = NSDictionary(contentsOfFile: filePath) if let userPass = userDic?.object(forKey: username) as? String { if userPass == password { return .just(.ok(message: "登录成功")) } } return .just(.failed(message: "密码错误")) } } class SearchService { static let shared = SearchService() private init(){} func getHeros() -> Observable<[Hero]> { let herosString = Bundle.main.path(forResource: "heros", ofType: "plist") //类型转换 let heroArray = NSArray(contentsOfFile: herosString!) as! Array<[String: String]> var heros = [Hero]() for heroDic in heroArray{ let hero = Hero(name: heroDic["name"]!, desc: heroDic["intro"]!, icon: heroDic["icon"]!) heros.append(hero) } return Observable.just(heros).observeOn(MainScheduler.instance) } func getHeros(withname name: String) -> Observable<[Hero]> { if name == "" { return getHeros() } let heroString = Bundle.main.path(forResource: "heros", ofType: "plist") let herosArray = NSArray(contentsOfFile: heroString! ) as! Array<[String:String]> var heros = [Hero]() for heroDic in herosArray { if heroDic["name"]!.contains(name) || heroDic["intro"]!.contains(name) { let hero = Hero(name: heroDic["name"]!, desc: heroDic["intro"]!, icon: heroDic["icon"]!) heros.append(hero) } } return Observable.just(heros).observeOn(MainScheduler.instance) } }
apache-2.0
9841fa4dcff575f4efd224987ff147e2
25.458564
104
0.529338
4.746283
false
false
false
false
silence0201/Swift-Study
GuidedTour/12Subscripts.playground/Contents.swift
1
1182
//: Playground - noun: a place where people can play struct TimesTable{ let multiplier: Int subscript(index: Int) -> Int{ return multiplier * index } } let threeTimesTable = TimesTable(multiplier: 3) print("Six time three is \(threeTimesTable[6])") var numberOflegs = ["spider":8,"ant":6,"cat":4] numberOflegs["bird"] = 2 print(numberOflegs) struct Matrix{ let rows: Int,columns: Int var grid: [Double] init(rows: Int,colums: Int){ self.rows = rows self.columns = colums grid = Array(repeating: 0.0, count: rows * colums) } func indexIsValid(row: Int,column: Int) -> Bool{ return row >= 0 && row < rows && column >= 0 && column < columns } subscript(row: Int,column: Int) -> Double{ get{ assert(indexIsValid(row: row, column: column),"Index out of range") return grid[row * columns + column] } set{ assert(indexIsValid(row: row, column: column),"Index out of range") grid[row * columns + column] = newValue } } } var matrix = Matrix(rows: 2, colums: 2) matrix[0,1] = 1.5 matrix[1,0] = 3.2 print(matrix)
mit
5a5bbf2cde56f04a7948f255f9b5c3e6
24.717391
79
0.592217
3.614679
false
false
false
false
insidegui/AppleEvents
Dependencies/swift-protobuf/Sources/SwiftProtobufPluginLibrary/NamingUtils.swift
2
15766
// Sources/SwiftProtobufPluginLibrary/NamingUtils.swift - Utilities for generating names // // Copyright (c) 2014 - 2017 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// This provides some utilities for generating names. /// /// NOTE: Only a very small subset of this is public. The intent is for this to /// expose a defined api within the PluginLib, but the the SwiftProtobufNamer /// to be what exposes the reusable parts at a much higher level. This reduces /// the changes of something being reimplemented but with minor differences. /// // ----------------------------------------------------------------------------- import Foundation /// /// We won't generate types (structs, enums) with these names: /// fileprivate let reservedTypeNames: Set<String> = { () -> Set<String> in var names: Set<String> = [] // Main SwiftProtobuf namespace // Shadowing this leads to Bad Things. names.insert(SwiftProtobufInfo.name) // Subtype of many messages, used to scope nested extensions names.insert("Extensions") // Subtypes are static references, so can conflict with static // class properties: names.insert("protoMessageName") // Methods on Message that we need to avoid shadowing. Testing // shows we do not need to avoid `serializedData` or `isEqualTo`, // but it's not obvious to me what's different about them. Maybe // because these two are generic? Because they throw? names.insert("decodeMessage") names.insert("traverse") // Basic Message properties we don't want to shadow: names.insert("isInitialized") names.insert("unknownFields") // Standard Swift property names we don't want // to conflict with: names.insert("debugDescription") names.insert("description") names.insert("dynamicType") names.insert("hashValue") // We don't need to protect all of these keywords, just the ones // that interfere with type expressions: // names = names.union(swiftKeywordsReservedInParticularContexts) names.insert("Type") names.insert("Protocol") names = names.union(swiftKeywordsUsedInDeclarations) names = names.union(swiftKeywordsUsedInStatements) names = names.union(swiftKeywordsUsedInExpressionsAndTypes) names = names.union(swiftCommonTypes) names = names.union(swiftSpecialVariables) return names }() /* * Many Swift reserved words can be used as fields names if we put * backticks around them: */ fileprivate let quotableFieldNames: Set<String> = { () -> Set<String> in var names: Set<String> = [] names = names.union(swiftKeywordsUsedInDeclarations) names = names.union(swiftKeywordsUsedInStatements) names = names.union(swiftKeywordsUsedInExpressionsAndTypes) return names }() fileprivate let reservedFieldNames: Set<String> = { () -> Set<String> in var names: Set<String> = [] // Properties are instance names, so can't shadow static class // properties such as `protoMessageName`. // Properties can't shadow methods. For example, we don't need to // avoid `isEqualTo` as a field name. // Basic Message properties that we don't want to shadow names.insert("isInitialized") names.insert("unknownFields") // Standard Swift property names we don't want // to conflict with: names.insert("debugDescription") names.insert("description") names.insert("dynamicType") names.insert("hashValue") names.insert("init") names.insert("self") // We don't need to protect all of these keywords, just the ones // that interfere with type expressions: // names = names.union(swiftKeywordsReservedInParticularContexts) names.insert("Type") names.insert("Protocol") names = names.union(swiftCommonTypes) names = names.union(swiftSpecialVariables) return names }() /* * Many Swift reserved words can be used as enum cases if we put * backticks around them: */ fileprivate let quotableEnumCases: Set<String> = { () -> Set<String> in var names: Set<String> = [] // We don't need to protect all of these keywords, just the ones // that interfere with enum cases: // names = names.union(swiftKeywordsReservedInParticularContexts) names.insert("associativity") names.insert("dynamicType") names.insert("optional") names.insert("required") names = names.union(swiftKeywordsUsedInDeclarations) names = names.union(swiftKeywordsUsedInStatements) names = names.union(swiftKeywordsUsedInExpressionsAndTypes) // Common type and variable names don't cause problems as enum // cases, because enum case names only appear in special contexts: // names = names.union(swiftCommonTypes) // names = names.union(swiftSpecialVariables) return names }() /* * Some words cannot be used for enum cases, even if they * are quoted with backticks: */ fileprivate let reservedEnumCases: Set<String> = [ // Don't conflict with standard Swift property names: "allCases", "debugDescription", "description", "dynamicType", "hashValue", "init", "rawValue", "self", ] /* * Message scoped extensions are scoped within the Message struct with * `enum Extensions { ... }`, so we resuse the same sets for backticks * and reserved words. */ fileprivate let quotableMessageScopedExtensionNames: Set<String> = quotableEnumCases fileprivate let reservedMessageScopedExtensionNames: Set<String> = reservedEnumCases fileprivate func isAllUnderscore(_ s: String) -> Bool { if s.isEmpty { return false } for c in s.unicodeScalars { if c != "_" {return false} } return true } fileprivate func sanitizeTypeName(_ s: String, disambiguator: String) -> String { if reservedTypeNames.contains(s) { return s + disambiguator } else if isAllUnderscore(s) { return s + disambiguator } else if s.hasSuffix(disambiguator) { // If `foo` and `fooMessage` both exist, and `foo` gets // expanded to `fooMessage`, then we also should expand // `fooMessage` to `fooMessageMessage` to avoid creating a new // conflict. This can be resolved recursively by stripping // the disambiguator, sanitizing the root, then re-adding the // disambiguator: #if swift(>=3.2) let e = s.index(s.endIndex, offsetBy: -disambiguator.count) let truncated = String(s[..<e]) #else let e = s.index(s.endIndex, offsetBy: -disambiguator.characters.count) let truncated = s.substring(to: e) #endif return sanitizeTypeName(truncated, disambiguator: disambiguator) + disambiguator } else { return s } } fileprivate func isCharacterUppercase(_ s: String, index: Int) -> Bool { let scalars = s.unicodeScalars let start = scalars.index(scalars.startIndex, offsetBy: index) if start == scalars.endIndex { // it ended, so just say the next character wasn't uppercase. return false } return scalars[start].isUppercase } fileprivate func makeUnicodeScalarView( from unicodeScalar: UnicodeScalar ) -> String.UnicodeScalarView { var view = String.UnicodeScalarView() view.append(unicodeScalar) return view } fileprivate func splitIdentifier(_ s: String) -> [String] { var out: [String.UnicodeScalarView] = [] var current = String.UnicodeScalarView() // The exact value used to seed this doesn't matter (as long as it's not an // underscore); we use it to avoid an extra optional unwrap in every loop // iteration. var last: UnicodeScalar = "\0" var lastIsUpper = false var lastIsLower = false for scalar in s.unicodeScalars { let isUpper = scalar.isUppercase let isLower = scalar.isLowercase if scalar.isDigit { if last.isDigit { current.append(scalar) } else { out.append(current) current = makeUnicodeScalarView(from: scalar) } } else if isUpper { if lastIsUpper { current.append(scalar.lowercased()) } else { out.append(current) current = makeUnicodeScalarView(from: scalar.lowercased()) } } else if isLower { if lastIsLower || lastIsUpper { current.append(scalar) } else { out.append(current) current = makeUnicodeScalarView(from: scalar) } } else if last == "_" { out.append(current) current = makeUnicodeScalarView(from: last) } last = scalar lastIsUpper = isUpper lastIsLower = isLower } out.append(current) if last == "_" { out.append(makeUnicodeScalarView(from: last)) } // An empty string will always get inserted first, so drop it. let slice = out.dropFirst(1) return slice.map(String.init) } fileprivate let upperInitials: Set<String> = ["url", "http", "https", "id"] fileprivate let backtickCharacterSet = CharacterSet(charactersIn: "`") // Scope for the utilies to they are less likely to conflict when imported into // generators. public enum NamingUtils { // Returns the type prefix to use for a given static func typePrefix(protoPackage: String, fileOptions: Google_Protobuf_FileOptions) -> String { // Explicit option (including blank), wins. if fileOptions.hasSwiftPrefix { return fileOptions.swiftPrefix } if protoPackage.isEmpty { return String() } // Transforms: // "package.name" -> "Package_Name" // "package_name" -> "PackageName" // "pacakge.some_name" -> "Package_SomeName" var makeUpper = true var prefix = "" #if swift(>=3.2) let protoPackageChars = protoPackage #else let protoPackageChars = protoPackage.characters #endif for c in protoPackageChars { if c == "_" { makeUpper = true } else if c == "." { makeUpper = true prefix += "_" } else if makeUpper { prefix += String(c).uppercased() makeUpper = false } else { prefix += String(c) } } // End in an underscore to split off anything that gets added to it. return prefix + "_" } /// Helper a proto prefix from strings. A proto prefix means underscores /// and letter case are ignored. struct PrefixStripper { private let prefixChars: String.UnicodeScalarView init(prefix: String) { self.prefixChars = prefix.lowercased().replacingOccurrences(of: "_", with: "").unicodeScalars } /// Strip the prefix and return the result, or return nil if it can't /// be stripped. func strip(from: String) -> String? { var prefixIndex = prefixChars.startIndex let prefixEnd = prefixChars.endIndex let fromChars = from.lowercased().unicodeScalars precondition(fromChars.count == from.lengthOfBytes(using: .ascii)) var fromIndex = fromChars.startIndex let fromEnd = fromChars.endIndex while (prefixIndex != prefixEnd) { if (fromIndex == fromEnd) { // Reached the end of the string while still having prefix to go // nothing to strip. return nil } if fromChars[fromIndex] == "_" { fromIndex = fromChars.index(after: fromIndex) continue } if prefixChars[prefixIndex] != fromChars[fromIndex] { // They differed before the end of the prefix, can't drop. return nil } prefixIndex = prefixChars.index(after: prefixIndex) fromIndex = fromChars.index(after: fromIndex) } // Remove any more underscores. while fromIndex != fromEnd && fromChars[fromIndex] == "_" { fromIndex = fromChars.index(after: fromIndex) } if fromIndex == fromEnd { // They matched, can't strip. return nil } let count = fromChars.distance(from: fromChars.startIndex, to: fromIndex) let idx = from.index(from.startIndex, offsetBy: count) return String(from[idx..<from.endIndex]) } } static func sanitize(messageName s: String) -> String { return sanitizeTypeName(s, disambiguator: "Message") } static func sanitize(enumName s: String) -> String { return sanitizeTypeName(s, disambiguator: "Enum") } static func sanitize(oneofName s: String) -> String { return sanitizeTypeName(s, disambiguator: "Oneof") } static func sanitize(fieldName s: String, basedOn: String) -> String { if basedOn.hasPrefix("clear") && isCharacterUppercase(basedOn, index: 5) { return s + "_p" } else if basedOn.hasPrefix("has") && isCharacterUppercase(basedOn, index: 3) { return s + "_p" } else if reservedFieldNames.contains(basedOn) { return s + "_p" } else if basedOn == s && quotableFieldNames.contains(basedOn) { // backticks are only used on the base names, if we're sanitizing based on something else // this is skipped (the "hasFoo" doesn't get backticks just because the "foo" does). return "`\(s)`" } else if isAllUnderscore(basedOn) { return s + "__" } else { return s } } static func sanitize(fieldName s: String) -> String { return sanitize(fieldName: s, basedOn: s) } static func sanitize(enumCaseName s: String) -> String { if reservedEnumCases.contains(s) { return "\(s)_" } else if quotableEnumCases.contains(s) { return "`\(s)`" } else if isAllUnderscore(s) { return s + "__" } else { return s } } static func sanitize(messageScopedExtensionName s: String) -> String { if reservedMessageScopedExtensionNames.contains(s) { return "\(s)_" } else if quotableMessageScopedExtensionNames.contains(s) { return "`\(s)`" } else if isAllUnderscore(s) { return s + "__" } else { return s } } /// Use toUpperCamelCase() to get leading "HTTP", "URL", etc. correct. static func uppercaseFirstCharacter(_ s: String) -> String { let out = s.unicodeScalars if let first = out.first { var result = makeUnicodeScalarView(from: first.uppercased()) result.append( contentsOf: out[out.index(after: out.startIndex)..<out.endIndex]) return String(result) } else { return s } } public static func toUpperCamelCase(_ s: String) -> String { var out = "" let t = splitIdentifier(s) for word in t { if upperInitials.contains(word) { out.append(word.uppercased()) } else { out.append(uppercaseFirstCharacter(word)) } } return out } public static func toLowerCamelCase(_ s: String) -> String { var out = "" let t = splitIdentifier(s) // Lowercase the first letter/word. var forceLower = true for word in t { if forceLower { out.append(word.lowercased()) } else if upperInitials.contains(word) { out.append(word.uppercased()) } else { out.append(uppercaseFirstCharacter(word)) } forceLower = false } return out } static func trimBackticks(_ s: String) -> String { return s.trimmingCharacters(in: backtickCharacterSet) } static func periodsToUnderscores(_ s: String) -> String { return s.replacingOccurrences(of: ".", with: "_") } /// This must be exactly the same as the corresponding code in the /// SwiftProtobuf library. Changing it will break compatibility of /// the generated code with old library version. public static func toJsonFieldName(_ s: String) -> String { var result = String.UnicodeScalarView() var capitalizeNext = false for c in s.unicodeScalars { if c == "_" { capitalizeNext = true } else if capitalizeNext { result.append(c.uppercased()) capitalizeNext = false } else { result.append(c) } } return String(result) } }
bsd-2-clause
17c6af5cfbae96192f18349f0cc45e86
29.732943
100
0.666117
4.214381
false
false
false
false
eeschimosu/SwiftLint
Source/SwiftLintFramework/Rules/OperatorFunctionWhitespaceRule.swift
3
2135
// // OperatorWhitespaceRule.swift // SwiftLint // // Created by Akira Hirakawa on 8/6/15. // Copyright (c) 2015 Realm. All rights reserved. // import SourceKittenFramework public struct OperatorFunctionWhitespaceRule: Rule { public init() {} public let identifier = "operator_whitespace" public func validateFile(file: File) -> [StyleViolation] { let operators = ["/", "=", "-", "+", "!", "*", "|", "^", "~", "?", "."].map({"\\\($0)"}) + ["%", "<", ">", "&"] let zeroOrManySpaces = "(\\s{0}|\\s{2,})" let pattern1 = "func\\s+[" + operators.joinWithSeparator("") + "]+\(zeroOrManySpaces)(<[A-Z]+>)?\\(" let pattern2 = "func\(zeroOrManySpaces)[" + operators.joinWithSeparator("") + "]+\\s+(<[A-Z]+>)?\\(" return file.matchPattern("(\(pattern1)|\(pattern2))").filter { _, syntaxKinds in return syntaxKinds.first == .Keyword }.map { range, _ in return StyleViolation(type: .OperatorFunctionWhitespace, location: Location(file: file, offset: range.location), severity: .Warning, reason: example.ruleDescription) } } public let example = RuleExample( ruleName: "Operator Function Whitespace Rule", ruleDescription: "Use a single whitespace around operators when " + "defining them.", nonTriggeringExamples: [ "func <| (lhs: Int, rhs: Int) -> Int {}\n", "func <|< <A>(lhs: A, rhs: A) -> A {}\n", "func abc(lhs: Int, rhs: Int) -> Int {}\n" ], triggeringExamples: [ "func <|(lhs: Int, rhs: Int) -> Int {}\n", // no spaces after "func <|<<A>(lhs: A, rhs: A) -> A {}\n", // no spaces after "func <| (lhs: Int, rhs: Int) -> Int {}\n", // 2 spaces after "func <|< <A>(lhs: A, rhs: A) -> A {}\n", // 2 spaces after "func <| (lhs: Int, rhs: Int) -> Int {}\n", // 2 spaces before "func <|< <A>(lhs: A, rhs: A) -> A {}\n" // 2 spaces before ] ) }
mit
313b76d3450cbe1c9dc21dbd33615a33
38.537037
98
0.498361
3.93186
false
false
false
false
hovansuit/FoodAndFitness
FoodAndFitness/Controllers/Home/HomeViewModel.swift
1
9487
// // HomeViewModel.swift // FoodAndFitness // // Created by Mylo Ho on 4/16/17. // Copyright © 2017 SuHoVan. All rights reserved. // import UIKit import RealmSwift import RealmS protocol HomeViewModelDelegate: class { func viewModel(_ viewModel: HomeViewModel, needsPerformAction action: HomeViewModel.Action) } final class HomeViewModel { private let _userFoods: Results<UserFood> private let _userExercises: Results<UserExercise> private let _trackings: Results<Tracking> private var userFoods: [UserFood] { return _userFoods.filter({ (userFood) -> Bool in guard let me = User.me, let user = userFood.userHistory?.user else { return false } return userFood.createdAt.isToday && me.id == user.id && userFood.meal.isNotEmpty }) } private var userExercises: [UserExercise] { return _userExercises.filter({ (userExercise) -> Bool in guard let me = User.me, let user = userExercise.userHistory?.user else { return false } return userExercise.createdAt.isToday && me.id == user.id }) } private var trackings: [Tracking] { return _trackings.filter({ (tracking) -> Bool in guard let me = User.me, let user = tracking.userHistory?.user else { return false } return tracking.createdAt.isToday && me.id == user.id }) } private var foodsToken: NotificationToken? private var exercisesToken: NotificationToken? private var trackingToken: NotificationToken? weak var delegate: HomeViewModelDelegate? enum Action { case userFoodChanged case userExerciseChanged case trackingsChanged } init() { _userFoods = RealmS().objects(UserFood.self) _userExercises = RealmS().objects(UserExercise.self) _trackings = RealmS().objects(Tracking.self) foodsToken = _userFoods.addNotificationBlock({ [weak self](change) in guard let this = self else { return } switch change { case .initial(_): break case .error(_): break case .update(_, deletions: _, insertions: _, modifications: _): this.delegate?.viewModel(this, needsPerformAction: .userFoodChanged) } }) exercisesToken = _userExercises.addNotificationBlock({ [weak self](change) in guard let this = self else { return } switch change { case .initial(_): break case .error(_): break case .update(_, deletions: _, insertions: _, modifications: _): this.delegate?.viewModel(this, needsPerformAction: .userExerciseChanged) } }) trackingToken = _trackings.addNotificationBlock({ [weak self](change) in guard let this = self else { return } switch change { case .initial(_): break case .error(_): break case .update(_, deletions: _, insertions: _, modifications: _): this.delegate?.viewModel(this, needsPerformAction: .trackingsChanged) } }) } func dataForAddActivityCell(activity: HomeViewController.AddActivity) -> AddActivityCell.Data? { guard let user = User.me else { return nil } let calories = user.caloriesToday var recommend = "" switch activity { case .breakfast: let preCalories = Int(calories.percent(value: 40)) let nextCalories = Int(calories.percent(value: 50)) recommend = "Recommended: \(preCalories) - \(nextCalories) kcal" case .lunch: let preCalories = Int(calories.percent(value: 30)) let nextCalories = Int(calories.percent(value: 40)) recommend = "Recommended: \(preCalories) - \(nextCalories) kcal" case .dinner: let preCalories = Int(calories.percent(value: 25)) let nextCalories = Int(calories.percent(value: 35)) recommend = "Recommended: \(preCalories) - \(nextCalories) kcal" case .exercise: guard let goal = user.goal, let goals = Goals(rawValue: goal.id) else { break } var minGoal: Int = 30 switch goals { case .beHealthier: break case .gainWeight: minGoal = 60 case .loseWeight: minGoal = 90 } recommend = "Daily goal: \(minGoal) min" case .tracking: guard let goal = user.goal, let goals = Goals(rawValue: goal.id) else { break } var minGoal: Int = 30 switch goals { case .beHealthier: break case .gainWeight: minGoal = 60 case .loseWeight: minGoal = 90 } recommend = "Daily goal: \(minGoal) min" } return AddActivityCell.Data(thumbnail: activity.image, title: activity.title, recommend: recommend, addImage: #imageLiteral(resourceName: "ic_add")) } func valueForProgressBar() -> ProgressCell.ProgressBarValue? { guard let user = User.me else { return nil } let burn = burnToday() let calories = user.caloriesToday + Double(burn) let carbsEaten = userFoods.map { (userFood) -> Int in return userFood.carbs }.reduce(0) { (result, carbs) -> Int in return result + carbs } let proteinEaten = userFoods.map { (userFood) -> Int in return userFood.protein }.reduce(0) { (result, protein) -> Int in return result + protein } let fatEaten = userFoods.map { (userFood) -> Int in return userFood.fat }.reduce(0) { (result, fat) -> Int in return result + fat } return ProgressCell.ProgressBarValue(carbs: carbsEaten, carbsMax: carbs(calories: calories), protein: proteinEaten, proteinMax: protein(calories: calories), fat: fatEaten, fatMax: fat(calories: calories)) } func dataForProgressCell() -> ProgressCell.Data? { guard let user = User.me else { return nil } var eaten = eatenToday() let burn = burnToday() let calories = user.caloriesToday + Double(burn) if Int(calories) - eaten < 0 { eaten = Int(calories) } let carbsString = "\(carbsLeft(calories: calories))" + Strings.gLeft let proteinString = "\(proteinLeft(calories: calories))" + Strings.gLeft let fatString = "\(fatLeft(calories: calories))" + Strings.gLeft return ProgressCell.Data(calories: Int(calories), eaten: eaten, burn: burn, carbs: carbsString, protein: proteinString, fat: fatString) } func eatenToday() -> Int { let eaten = userFoods.map { (userFood) -> Int in return userFood.calories }.reduce(0) { (result, calories) -> Int in return result + calories } return eaten } func carbsLeft(calories: Double) -> Int { let carbsUserFoods = userFoods.map { (userFood) -> Int in return userFood.carbs }.reduce(0) { (result, carbs) -> Int in return result + carbs } let carbsLeft = carbs(calories: calories) - carbsUserFoods if carbsLeft < 0 { return 0 } else { return carbsLeft } } func proteinLeft(calories: Double) -> Int { let proteinUserFoods = userFoods.map { (userFood) -> Int in return userFood.protein }.reduce(0) { (result, protein) -> Int in return result + protein } let proteinLeft = protein(calories: calories) - proteinUserFoods if proteinLeft < 0 { return 0 } else { return proteinLeft } } func fatLeft(calories: Double) -> Int { let fatUserFoods = userFoods.map { (userFood) -> Int in return userFood.fat }.reduce(0) { (result, fat) -> Int in return result + fat } let fatLeft = fat(calories: calories) - fatUserFoods if fatLeft < 0 { return 0 } else { return fatLeft } } func burnToday() -> Int { let exercisesBurn = userExercises.map { (userExercise) -> Int in return userExercise.calories }.reduce(0) { (result, calories) -> Int in return result + calories } let trackingsBurn = trackings.map { (tracking) -> Int in return tracking.caloriesBurn }.reduce(0) { (result, calories) -> Int in return result + calories } return exercisesBurn + trackingsBurn } func getSuggestionsIfNeeds(completion: @escaping Completion) { let suggestions: [Suggestion] = RealmS().objects(Suggestion.self).filter { (suggestion) -> Bool in return SuggestionViewModel.filterByGoal(suggestion: suggestion) } if suggestions.isEmpty { guard let me = User.me, let goal = me.goal else { completion(.failure(NSError(message: Strings.Errors.tokenError))) return } SuggestionServices.get(goalId: goal.id, completion: completion) } else { completion(.success([:])) } } }
mit
76271b526d9ad28226b2827b2b34c144
37.404858
156
0.576323
4.598158
false
false
false
false
maxim-pervushin/Overlap
Overlap/App/Storage/Json/PlistStorage.swift
1
1941
// // Created by Maxim Pervushin on 05/05/16. // Copyright (c) 2016 Maxim Pervushin. All rights reserved. // import Foundation class PlistStorage { private var _updated: (Void -> Void)? private var _overlapsById: [String:Overlap] = [:] { didSet { _updated?() } } private func _filePath() -> String { if let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first { return path + "/overlaps.plist" } // TODO: Write error somewhere return "" } private func _load() { guard let arr = NSArray(contentsOfFile: _filePath()) as? [[String:AnyObject]] else { _overlapsById = [:] return } var overlapsById = [String: Overlap]() for overlapDictionary in arr { if let overlap = Overlap(dictionary: overlapDictionary) { overlapsById[overlap.id] = overlap } } _overlapsById = overlapsById } private func _save() { var serialized = [[String: AnyObject]]() for (_, overlap) in _overlapsById { serialized.append(overlap.serializeToDictionary()) } if !(serialized as NSArray).writeToFile(_filePath(), atomically: true) { // TODO: Write error somewhere } } init() { _load() } } extension PlistStorage: Storage { var updated: (Void -> Void)? { set { _updated = newValue } get { return _updated } } var overlaps: [Overlap] { return Array(_overlapsById.values) } func saveOverlap(overlap: Overlap) -> Bool { _overlapsById[overlap.id] = overlap _save() return true } func deleteOverlap(overlap: Overlap) -> Bool { _overlapsById[overlap.id] = nil _save() return true } }
mit
e935567ab770b9ecaa83818f762c1982
22.39759
108
0.545595
4.567059
false
false
false
false
AliSoftware/Dip
SampleApp/DipSampleApp/Providers/FakePersonsProviders.swift
3
3481
// // PlistPersonProvider.swift // Dip // // Created by Ilya Puchka on 12/09/2015. // Copyright © 2015 AliSoftware. All rights reserved. // import Foundation ///Provides some dummy Person entities struct DummyPilotProvider : PersonProviderAPI { func fetchIDs(completion: @escaping ([Int]) -> Void) { completion(Array(0..<5)) } func fetch(id: Int, completion: @escaping (Person?) -> Void) { completion(dummyPerson(idx: id)) } private func dummyPerson(idx: Int) -> Person { let colors = ["blue", "brown", "yellow", "orange", "red", "dark"] let genders: [Gender?] = [Gender.Male, Gender.Female, nil] return Person( name: "John Dummy Doe #\(idx)", height: 150 + (idx*27%40), mass: 50 + (idx*7%30), hairColor: colors[idx*3%colors.count], eyeColor: colors[idx*2%colors.count], gender: genders[idx%3], starshipIDs: [idx % 3, 2*idx % 4] ) } } ///Provides Person entities reading then from plist file class PlistPersonProvider : PersonProviderAPI { let people: [Person] init(plist basename: String) { guard let path = Bundle.main.path(forResource: basename, ofType: "plist"), let list = NSArray(contentsOfFile: path), let peopleDict = list as? [[String:AnyObject]] else { fatalError("PLIST for \(basename) not found") } self.people = peopleDict.map(PlistPersonProvider.personFromDict) } func fetchIDs(completion: @escaping ([Int]) -> Void) { completion(Array(0..<people.count)) } func fetch(id: Int, completion: @escaping (Person?) -> Void) { guard id < people.count else { completion(nil) return } completion(people[id]) } private static func personFromDict(dict: [String:AnyObject]) -> Person { guard let name = dict["name"] as? String, let height = dict["height"] as? Int, let mass = dict["mass"] as? Int, let hairColor = dict["hairColor"] as? String, let eyeColor = dict["eyeColor"] as? String, let genderStr = dict["gender"] as? String, let starshipsIDs = dict["starships"] as? [Int] else { fatalError("Invalid Plist") } return Person( name: name, height: height, mass: mass, hairColor: hairColor, eyeColor: eyeColor, gender: Gender(rawValue: genderStr), starshipIDs: starshipsIDs ) } } class FakePersonsProvider: PersonProviderAPI { let dummyProvider: PersonProviderAPI var plistProvider: PersonProviderAPI! //In this class we use both constructor injection and property injection, //nil is a valid local default init(dummyProvider: PersonProviderAPI) { self.dummyProvider = dummyProvider } func fetchIDs(completion: @escaping ([Int]) -> Void) { dummyProvider.fetchIDs(completion: completion) } func fetch(id: Int, completion: @escaping (Person?) -> Void) { if let plistProvider = plistProvider, id == 0 { plistProvider.fetch(id: id, completion: completion) } else { dummyProvider.fetch(id: id, completion: completion) } } }
mit
5e4f98b02f49252b8e81e682fd934c17
29.526316
80
0.569828
4.233577
false
false
false
false
kotoole1/Paranormal
Paranormal/Paranormal/Operations/TextureOperation.swift
1
1152
import Foundation import CoreGraphics import GPUImage import Appkit class TextureOperation { // TODO: Make a controller and a UI for adding an operation, // make this a subclass of PNOperation. var document : Document init(document: Document) { self.document = document } func perform() { let panel = NSOpenPanel() panel.allowedFileTypes = ["png", "jpg", "jpeg"] panel.beginWithCompletionHandler { (status) -> Void in if status == NSFileHandlingPanelOKButton{ if let url = panel.URL { let image = NSImage(contentsOfURL: url) if let currentLayer = self.document.currentLayer { if let newLayer = self.document.rootLayer?.addLayer() { newLayer.imageData = image?.TIFFRepresentation newLayer.name = "Noise Layer" newLayer.blendMode = BlendMode.Tilted currentLayer.combineLayerOntoSelf(newLayer) } } } } } } }
mit
13e7780c19676319017dd8e730670bf8
32.882353
79
0.536458
5.511962
false
false
false
false
apple/swift
test/Migrator/post_fixit_pass.swift
11
655
// RUN: %empty-directory(%t) && %target-swift-frontend -c -update-code -primary-file %s -emit-migrated-file-path %t/post_fixit_pass.swift.result -o /dev/null -F %S/mock-sdk -swift-version 4 %api_diff_data_dir // RUN: %diff -u %S/post_fixit_pass.swift.expected %t/post_fixit_pass.swift.result #if swift(>=4.2) public struct SomeAttribute: RawRepresentable { public init(rawValue: Int) { self.rawValue = rawValue } public init(_ rawValue: Int) { self.rawValue = rawValue } public var rawValue: Int public typealias RawValue = Int } #else public typealias SomeAttribute = Int #endif func foo(_ d: SomeAttribute) { let i: Int = d }
apache-2.0
7ffb10c1328a11611ae0abb3de27b7df
35.388889
208
0.696183
3.210784
false
false
false
false
githubxiangdong/DouYuZB
DouYuZB/DouYuZB/Classes/Tools/NetworkTools.swift
1
985
// // NetworkTools.swift // DouYuZB // // Created by new on 2017/4/27. // Copyright © 2017年 9-kylins. All rights reserved. // import UIKit import Alamofire enum MethodType { case get case post } class NetworkTools { // 类方法 class func request(_ type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallBack : @escaping (_ result : Any) -> ()){ // 1, 获取数据类型 let method = type == .get ? HTTPMethod.get : HTTPMethod.post // 三目运算 // 2, 发送网络请求 Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (respone) in // 3, 获取结果 guard let result = respone.result.value else{ print(respone.result.error!) return; } // 4, 将结果回调出去 finishedCallBack(result) } } }
mit
368ec45b119084549eed7fad75245a98
23.263158
153
0.539046
4.328638
false
false
false
false
sugimotoak/ExpressBusTimetable
ExpressBusTimetable/Controllers/TableTypeCommuteTableViewController.swift
1
2878
// // TableTypeCommuteTableViewController.swift // ExpressBusTimetable // // Created by akira on 4/30/17. // Copyright © 2017 Spreadcontent G.K. All rights reserved. // import UIKit class TableTypeCommuteTableViewController: CommuteTableViewController { override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) for (section, item) in sct.array.enumerated() { for (_, ct) in item.enumerated() { if ct.isNext { self.tableView.scrollToRow(at: IndexPath(row: 0, section: section), at: UITableViewScrollPosition.middle, animated: false) break } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "tableCell") var minuteList = [String]() var nextBusStopMinuteIndex: Int? sct.array[indexPath.section].enumerated().forEach { index, ct in minuteList.append(ct.onBusStopMinute) if ct.isNext { nextBusStopMinuteIndex = index } } let text = minuteList.joined(separator: " ") cell.backgroundColor = EBTColor.sharedInstance.secondaryColor cell.textLabel?.font = UIFont.monospacedDigitSystemFont(ofSize: 17, weight: UIFont.Weight.light) cell.textLabel?.textColor = EBTColor.sharedInstance.secondaryTextColor if let index = nextBusStopMinuteIndex { let attrText = NSMutableAttributedString(string: text) let startIndex = index * 3 attrText.addAttributes([NSAttributedStringKey.foregroundColor: EBTColor.sharedInstance.nextTimeColor], range: NSMakeRange(startIndex, 2)) cell.textLabel?.attributedText = attrText } else { cell.textLabel?.text = text } return cell } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
81d0c8e51ee03f61e6f568f57bf5cf69
34.493827
118
0.622957
5.265568
false
false
false
false
awind/Pixel
Pixel/Router.swift
1
8743
// // Router.swift // Pixel // // Created by SongFei on 15/12/4. // Copyright © 2015年 SongFei. All rights reserved. // import UIKit import Alamofire enum Router: URLRequestConvertible { static let baseURLString = "https://api.500px.com/v1" static let consumerKey = "7AqOElDfu35aVav8bgztEdMWLVojPEFZoAp66JJw" case PopularPhotos(Int) case HighestPhotos(Int) case UpcomingPhotos(Int) case EditorsPhotos(Int) case PhotoInfo(Int, ImageSize) case Comments(Int, Int) case CommentPhoto(Int, String) case Users() case UsersShow(Int) case UserPhotos(Int, Int) case SearchUsers(String, Int) case SearchPhotos(String, Int) case VotePhoto(Int, Int) case UserFriends(Int, Int) case UserFollowers(Int, Int) case FollowUser(Int) case UnFollowUser(Int) case Report(Int, Int, String) private var method: Alamofire.Method { switch self { case .CommentPhoto(_, _): return .POST case .VotePhoto(_, _): return .POST case .FollowUser(_): return .POST case .UnFollowUser(_): return .DELETE case .Report(_, _, _): return .POST default: return .GET } } var URLRequest: NSMutableURLRequest { let userDefaults = NSUserDefaults.standardUserDefaults() var oauthToken: String = "" if let accessToken = userDefaults.valueForKey("accessToken") { oauthToken = accessToken as! String // print("oauthToken: \(oauthToken)") } let result: (path: String, parameters: [String: AnyObject]) = { switch self { case .PopularPhotos(let page): let params = [ "consumer_key": Router.consumerKey, "oauth_token": oauthToken, "page": "\(page)", "feature": "popular", "rpp": "50", "image_size": "6,20", //"include_store": //"store_download", "include_states": "votes" ] return ("/photos", params) case .HighestPhotos(let page): let params = [ "consumer_key": Router.consumerKey, "oauth_token": oauthToken, "page": "\(page)", "image_size": "6,20", "feature": "highest_rated", "rpp": "50", //"include_store": //"store_download", "include_states": "votes" ] return ("/photos", params) case .UpcomingPhotos(let page): let params = [ "consumer_key": Router.consumerKey, "oauth_token": oauthToken, "page": "\(page)", "image_size": "6,20", "feature": "upcoming", "rpp": "50", //"include_store": //"store_download", "include_states": "votes" ] return ("/photos", params) case .EditorsPhotos(let page): let params = [ "consumer_key": Router.consumerKey, "oauth_token": oauthToken, "page": "\(page)", "image_size": "6,20", "feature": "editors", "rpp": "50", //"include_store": //"store_download", "include_states": "votes" ] return ("/photos", params) case .PhotoInfo(let photoID, let imageSize): let params = [ "consumer_key": Router.consumerKey, "image_size": "\(imageSize.rawValue)", "oauth_token": oauthToken ] return ("/photos/\(photoID)", params) case .Comments(let photoID, let commentsPage): let params = [ "consumer_key": Router.consumerKey, "comments": "1", "oauth_token": oauthToken, "page": "\(commentsPage)" ] return ("/photos/\(photoID)/comments", params) case .Users(): let paramas = [ "oauth_token": oauthToken ] return ("/users", paramas) case .UsersShow(let userId): let params = [ "consumer_key": Router.consumerKey, "oauth_token": oauthToken, "id": "\(userId)" ] return ("/users/show", params) case .UserPhotos(let userId, let page): let params = [ "consumer_key": Router.consumerKey, "oauth_token": oauthToken, "page": "\(page)", "feature": "user", "rpp": "50", "image_size": "6,20", "user_id": "\(userId)", "include_states": "votes" ] return ("/photos", params) case .UserFriends(let userId, let page): let params = [ "consumer_key": Router.consumerKey, "oauth_token": oauthToken, "page": "\(page)", "rpp": "50" ] return ("/users/\(userId)/friends", params) case .UserFollowers(let userId, let page): let params = [ "consumer_key": Router.consumerKey, "oauth_token": oauthToken, "page": "\(page)", "rpp": "50" ] return ("/users/\(userId)/followers", params) case .FollowUser(let userId): let params = [ "consumer_key": Router.consumerKey, "oauth_token": oauthToken ] return ("/users/\(userId)/friends", params) case .UnFollowUser(let userId): let params = [ "consumer_key": Router.consumerKey, "oauth_token": oauthToken ] return ("/users/\(userId)/friends", params) case .CommentPhoto(let photoId, let commentBody): let params = [ "consumer_key": Router.consumerKey, "oauth_token": oauthToken, "body": commentBody ] return ("/photos/\(photoId)/comments", params) case .SearchUsers(let keyword, let page): let params = [ "consumer_key": Router.consumerKey, "oauth_token": oauthToken, "page": "\(page)", "term": keyword ] return ("/users/search", params) case .SearchPhotos(let keyword, let page): let params = [ "consumer_key": Router.consumerKey, "oauth_token": oauthToken, "page": "\(page)", "term": keyword, "rpp": "50", "image_size": "6,20", "include_states": "1", "sort": "highest_rating" ] return ("photos/search", params) case .VotePhoto(let id, let vote): let params = [ "consumer_key": Router.consumerKey, "oauth_token": oauthToken, "vote": "\(vote)" ] return ("photos/\(id)/vote", params) case .Report(let photoId, let reason, let reasonBody): let params = [ "consumer_key": Router.consumerKey, "reason": "\(reason)", "reason_details": reasonBody ] return ("photos/\(photoId)/report", params) } }() let URL = NSURL(string: Router.baseURLString)! let URLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(result.path)) URLRequest.HTTPMethod = method.rawValue let encoding = Alamofire.ParameterEncoding.URL return encoding.encode(URLRequest, parameters: result.parameters).0 } }
apache-2.0
b0d363c29c5aa65fa70011e996472f16
36.195745
95
0.439588
5.193108
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
Test/VideoBlockViewControllerTests.swift
1
1487
// // VideoBlockViewControllerTests.swift // edX // // Created by Akiva Leffert on 3/15/16. // Copyright © 2016 edX. All rights reserved. // import Foundation @testable import edX class VideoBlockViewControllerTests : SnapshotTestCase { func testSnapshotYoutubeOnly() { // Create a course with a youtube video let summary = OEXVideoSummary(videoID: "some-video", name: "Youtube Video", encodings: [ OEXVideoEncodingYoutube: OEXVideoEncoding(name: OEXVideoEncodingYoutube, URL: "https://some-youtube-url", size: 12)]) let outline = CourseOutline(root: "root", blocks: [ "root" : CourseBlock(type: CourseBlockType.Course, children: ["video"], blockID: "root", minifiedBlockID: "123456", name: "Root", multiDevice: true, graded: false), "video" : CourseBlock(type: CourseBlockType.Video(summary), children: [], blockID: "video", minifiedBlockID: "123456", name: "Youtube Video", blockURL: NSURL(string: "www.example.com"), multiDevice: true, graded: false) ]) let environment = TestRouterEnvironment() environment.mockCourseDataManager.querier = CourseOutlineQuerier(courseID: "some-course", outline: outline) let videoController = VideoBlockViewController(environment: environment, blockID: "video", courseID: "some-course") inScreenNavigationContext(videoController) { assertSnapshotValidWithContent(videoController.navigationController!) } } }
apache-2.0
78d1bea9ec6839ef82627936e8cffc42
45.4375
231
0.700538
4.516717
false
true
false
false
abelsanchezali/ViewBuilder
ViewBuilderDemo/ViewBuilderDemo/ViewControllers/Card4CollectionViewCell.swift
1
3833
// // Card4CollectionViewCell.swift // ViewBuilderDemo // // Created by Abel Sanchez on 8/7/16. // Copyright © 2016 Abel Sanchez. All rights reserved. // import UIKit public class Card4CollectionViewCell: UICollectionViewCell, DataSourceReceiverProtocol { static let shared = Card4CollectionViewCell(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) var summaryLabel: UILabel! var insightLabel: UILabel! var imageView: UIView! var separatorView: UIView! public override init(frame: CGRect) { super.init(frame: frame) self.margin = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8) if !self.contentView.loadFromDocument(Constants.bundle.path(forResource: "SampleCard4", ofType: "xml")!) { fatalError("Ups!!!") } summaryLabel = self.contentView.documentReferences!["summaryLabel"] as! UILabel insightLabel = self.contentView.documentReferences!["insightLabel"] as! UILabel imageView = self.contentView.documentReferences!["imageView"] as! UIView separatorView = self.contentView.documentReferences!["separator"] as!UIView } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public var dataSource: AnyObject? = nil { didSet { let dataSource = self.dataSource as? ViewModel let summary = dataSource?["summary"] as? String let insight = dataSource?["insight"] as? String let mode = dataSource?["mode"] as? Int ?? 0 var color = UIColor.red switch mode { case 1: color = UIColor.blue case 2: color = UIColor.brown case 3: color = UIColor.green case 4: color = UIColor.black case 5: color = UIColor.orange case 6: color = UIColor.darkGray case 7: color = UIColor.cyan case 8: color = UIColor.magenta case 9: color = UIColor.purple default: color = UIColor.red } summaryLabel.text = summary insightLabel.text = insight imageView.backgroundColor = color } } public override func layoutSubviews() { // Measure Subviews // Arrange Subviews } static let borderMargin: CGFloat = 12.0 static let itemMargin: CGFloat = 8 } extension Card4CollectionViewCell: CollectionViewCellProtocol { public static func measureForFitSize(_ size: CGSize, dataSource: AnyObject?) -> CGSize { let width = size.width - shared.margin.left - shared.margin.right shared.dataSource = dataSource shared.imageView.frame = CGRect(x: borderMargin, y: borderMargin, width: shared.imageView.bounds.size.width, height: shared.imageView.bounds.size.width) let summarySize = shared.summaryLabel.sizeThatFits(CGSize(width: width - borderMargin * 2 - itemMargin, height: CGFloat.greatestFiniteMagnitude)) shared.summaryLabel.frame = CGRect(x: shared.imageView.bounds.size.width + itemMargin, y: borderMargin, width: summarySize.width, height: summarySize.height) let measure = CGSize(width: width, height: 250) return measure } } extension Card4CollectionViewCell: DocumentAssociatedProtocol { public var associatedDocumentPath: String? { return Constants.bundle.path(forResource: "SampleCard4", ofType: "xml") } }
mit
8d3ab32815efb10b0393a486b8be62fb
36.568627
153
0.591075
5.062087
false
false
false
false
APUtils/APExtensions
APExtensions/Classes/Storyboard/UIScrollView+Storyboard.swift
1
5134
// // UIScrollView+Storyboard.swift // APExtensions // // Created by Anton Plebanovich on 5/18/17. // Copyright © 2019 Anton Plebanovich. All rights reserved. // import RoutableLogger import UIKit // ******************************* MARK: - Helper Extension private extension UIView { var _viewController: UIViewController? { var nextResponder: UIResponder? = self while nextResponder != nil { nextResponder = nextResponder?.next if let viewController = nextResponder as? UIViewController { return viewController } } return nil } } // ******************************* MARK: - Bars Avoid @available(iOS, introduced: 2.0, deprecated: 13.0, message: "Use the statusBarManager property of the window scene instead.") private let _statusBarHeight: CGFloat = UIApplication.shared.statusBarFrame.height private let _navigationBarHeight: CGFloat = 44 @available(iOS, introduced: 2.0, deprecated: 13.0, message: "Use the statusBarManager property of the window scene instead.") private let _topBarsHeight: CGFloat = _statusBarHeight + _navigationBarHeight public extension UIScrollView { /// Sets (status bar + 44) or 0 for top content inset and disables automatic mechanisms to prevent conflict. /// Returns true if scroll view avoids top bars. Takes into account `contentInsetAdjustmentBehavior`. @available(iOS, introduced: 2.0, deprecated: 13.0, message: "Deprecated. Please use something else.") @IBInspectable var avoidNavigationBar: Bool { get { if #available(iOS 11.0, *) { switch contentInsetAdjustmentBehavior { case .always: return adjustedContentInset.top == _topBarsHeight case .never: return contentInset.top == _topBarsHeight case .scrollableAxes: if isScrollEnabled || alwaysBounceVertical { return adjustedContentInset.top == _topBarsHeight } else { return contentInset.top == _topBarsHeight } case .automatic: if let _ = _viewController?.navigationController { return adjustedContentInset.top == _topBarsHeight } else { return contentInset.top == _topBarsHeight } @unknown default: return false } } else { return contentInset.top == _topBarsHeight } } set { if #available(iOS 11.0, *) { contentInsetAdjustmentBehavior = .never } if #available(iOS 11.0, *) {} else { _viewController?.automaticallyAdjustsScrollViewInsets = false } contentInset.top = newValue ? _topBarsHeight : 0 // Scroll indicator inset behavior changed on iOS 13 and now its added to `contentInset` if #available(iOS 13.0, *) {} else { scrollIndicatorInsets.top = newValue ? _topBarsHeight : 0 } } } /// Sets 49 or 0 for bottom inset and disables automatic mechanisms to prevent conflict. /// Returns true if scroll view avoids bottom bars. Takes into account `contentInsetAdjustmentBehavior`. @IBInspectable var avoidTabBar: Bool { get { if #available(iOS 11.0, *) { switch contentInsetAdjustmentBehavior { case .always: return adjustedContentInset.bottom == 49 case .never: return contentInset.bottom == 49 case .scrollableAxes: if isScrollEnabled || alwaysBounceVertical { return adjustedContentInset.bottom == 49 } else { return contentInset.bottom == 49 } case .automatic: if let _ = _viewController?.tabBarController { return adjustedContentInset.bottom == 49 } else { return contentInset.bottom == 49 } @unknown default: return false } } else { return contentInset.bottom == 49 } } set { if #available(iOS 11.0, *) { contentInsetAdjustmentBehavior = .never } if #available(iOS 11.0, *) {} else { _viewController?.automaticallyAdjustsScrollViewInsets = false } contentInset.bottom = newValue ? 49 : 0 // Scroll indicator inset behavior changed on iOS 13 and now its added to `contentInset` if #available(iOS 13.0, *) {} else { scrollIndicatorInsets.bottom = newValue ? 49 : 0 } } } }
mit
7d06e3443fe8233e724f3265852f56cb
37.30597
125
0.535944
5.872998
false
false
false
false
BluechipSystems/viper-module-generator
VIPERGenDemo/VIPERGenDemo/Libraries/Swifter/Swifter/SwifterPlaces.swift
5
7119
// // SwifterPlaces.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public extension Swifter { /* GET geo/id/:place_id Returns all the information about a known place. */ public func getGeoIDWithPlaceID(placeID: String, success: ((place: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) { let path = "geo/id/\(placeID).json" self.getJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(place: json.object) return }, failure: failure) } /* GET geo/reverse_geocode Given a latitude and a longitude, searches for up to 20 places that can be used as a place_id when updating a status. This request is an informative call and will deliver generalized results about geography. */ public func getGeoReverseGeocodeWithLat(lat: Double, long: Double, accuracy: String?, granularity: String?, maxResults: Int?, callback: String?, success: ((place: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) { let path = "geo/reverse_geocode.json" var parameters = Dictionary<String, AnyObject>() parameters["lat"] = lat parameters["long"] = long if accuracy != nil { parameters["accuracy"] = accuracy! } if granularity != nil { parameters["granularity"] = granularity! } if maxResults != nil { parameters["max_results"] = maxResults! } if callback != nil { parameters["callback"] = callback! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(place: json.object) return }, failure: failure) } /* GET geo/search Search for places that can be attached to a statuses/update. Given a latitude and a longitude pair, an IP address, or a name, this request will return a list of all the valid places that can be used as the place_id when updating a status. Conceptually, a query can be made from the user's location, retrieve a list of places, have the user validate the location he or she is at, and then send the ID of this location with a call to POST statuses/update. This is the recommended method to use find places that can be attached to statuses/update. Unlike GET geo/reverse_geocode which provides raw data access, this endpoint can potentially re-order places with regards to the user who is authenticated. This approach is also preferred for interactive place matching with the user. */ public func getGeoSearchWithLat(lat: Double?, long: Double?, query: String?, ipAddress: String?, accuracy: String?, granularity: String?, maxResults: Int?, containedWithin: String?, attributeStreetAddress: String?, callback: String?, success: ((places: [JSONValue]?) -> Void)?, failure: FailureHandler?) { assert(lat != nil || long != nil || query != nil || ipAddress != nil, "At least one of the following parameters must be provided to access this resource: lat, long, ipAddress, or query") let path = "geo/search.json" var parameters = Dictionary<String, AnyObject>() if lat != nil { parameters["lat"] = lat! } if long != nil { parameters["long"] = long! } if query != nil { parameters["query"] = query! } if ipAddress != nil { parameters["ipAddress"] = ipAddress! } if accuracy != nil { parameters["accuracy"] = accuracy! } if granularity != nil { parameters["granularity"] = granularity! } if maxResults != nil { parameters["max_results"] = maxResults! } if containedWithin != nil { parameters["contained_within"] = containedWithin! } if attributeStreetAddress != nil { parameters["attribute:street_address"] = attributeStreetAddress } if callback != nil { parameters["callback"] = callback! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(places: json.array) return }, failure: failure) } /* GET geo/similar_places Locates places near the given coordinates which are similar in name. Conceptually you would use this method to get a list of known places to choose from first. Then, if the desired place doesn't exist, make a request to POST geo/place to create a new one. The token contained in the response is the token needed to be able to create a new place. */ public func getGeoSimilarPlacesWithLat(lat: Double, long: Double, name: String, containedWithin: String?, attributeStreetAddress: String?, callback: String?, success: ((places: [JSONValue]?) -> Void)?, failure: FailureHandler?) { let path = "geo/similar_places.json" var parameters = Dictionary<String, AnyObject>() parameters["lat"] = lat parameters["long"] = long parameters["name"] = name if containedWithin != nil { parameters["contained_within"] = containedWithin! } if attributeStreetAddress != nil { parameters["attribute:street_address"] = attributeStreetAddress } if callback != nil { parameters["callback"] = callback! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(places: json.array) return }, failure: failure) } }
mit
7cee78d554420fd8655c8f095587b7d5
39.68
328
0.643208
4.749166
false
false
false
false
kzaher/RxSwift
RxSwift/Traits/PrimitiveSequence/Completable.swift
2
12154
// // Completable.swift // RxSwift // // Created by sergdort on 19/08/2017. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // #if DEBUG import Foundation #endif /// Sequence containing 0 elements public enum CompletableTrait { } /// Represents a push style sequence containing 0 elements. public typealias Completable = PrimitiveSequence<CompletableTrait, Swift.Never> public enum CompletableEvent { /// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`) case error(Swift.Error) /// Sequence completed successfully. case completed } extension PrimitiveSequenceType where Trait == CompletableTrait, Element == Swift.Never { public typealias CompletableObserver = (CompletableEvent) -> Void /** Creates an observable sequence from a specified subscribe method implementation. - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method. - returns: The observable sequence with the specified implementation for the `subscribe` method. */ public static func create(subscribe: @escaping (@escaping CompletableObserver) -> Disposable) -> PrimitiveSequence<Trait, Element> { let source = Observable<Element>.create { observer in return subscribe { event in switch event { case .error(let error): observer.on(.error(error)) case .completed: observer.on(.completed) } } } return PrimitiveSequence(raw: source) } /** Subscribes `observer` to receive events for this sequence. - returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources. */ public func subscribe(_ observer: @escaping (CompletableEvent) -> Void) -> Disposable { var stopped = false return self.primitiveSequence.asObservable().subscribe { event in if stopped { return } stopped = true switch event { case .next: rxFatalError("Completables can't emit values") case .error(let error): observer(.error(error)) case .completed: observer(.completed) } } } /** Subscribes a completion handler and an error handler for this sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - parameter onError: Action to invoke upon errored termination of the observable sequence. - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has gracefully completed, errored, or if the generation is canceled by disposing subscription). - returns: Subscription object used to unsubscribe from the observable sequence. */ public func subscribe(onCompleted: (() -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable { #if DEBUG let callStack = Hooks.recordCallStackOnError ? Thread.callStackSymbols : [] #else let callStack = [String]() #endif let disposable: Disposable if let onDisposed = onDisposed { disposable = Disposables.create(with: onDisposed) } else { disposable = Disposables.create() } let observer: CompletableObserver = { event in switch event { case .error(let error): if let onError = onError { onError(error) } else { Hooks.defaultErrorHandler(callStack, error) } disposable.dispose() case .completed: onCompleted?() disposable.dispose() } } return Disposables.create( self.primitiveSequence.subscribe(observer), disposable ) } } extension PrimitiveSequenceType where Trait == CompletableTrait, Element == Swift.Never { /** Returns an observable sequence that terminates with an `error`. - seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: The observable sequence that terminates with specified error. */ public static func error(_ error: Swift.Error) -> Completable { PrimitiveSequence(raw: Observable.error(error)) } /** Returns a non-terminating observable sequence, which can be used to denote an infinite duration. - seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: An observable sequence whose observers will never get called. */ public static func never() -> Completable { PrimitiveSequence(raw: Observable.never()) } /** Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. - seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: An observable sequence with no elements. */ public static func empty() -> Completable { Completable(raw: Observable.empty()) } } extension PrimitiveSequenceType where Trait == CompletableTrait, Element == Swift.Never { /** Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) - parameter onNext: Action to invoke for each element in the observable sequence. - parameter onError: Action to invoke upon errored termination of the observable sequence. - parameter afterError: Action to invoke after errored termination of the observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - parameter afterCompleted: Action to invoke after graceful termination of the observable sequence. - parameter onSubscribe: Action to invoke before subscribing to source observable sequence. - parameter onSubscribed: Action to invoke after subscribing to source observable sequence. - parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed. - returns: The source sequence with the side-effecting behavior applied. */ public func `do`(onError: ((Swift.Error) throws -> Void)? = nil, afterError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, afterCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) -> Completable { return Completable(raw: self.primitiveSequence.source.do( onError: onError, afterError: afterError, onCompleted: onCompleted, afterCompleted: afterCompleted, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose) ) } /** Concatenates the second observable sequence to `self` upon successful termination of `self`. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - parameter second: Second observable sequence. - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. */ public func concat(_ second: Completable) -> Completable { Completable.concat(self.primitiveSequence, second) } /** Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ public static func concat<Sequence: Swift.Sequence>(_ sequence: Sequence) -> Completable where Sequence.Element == Completable { let source = Observable.concat(sequence.lazy.map { $0.asObservable() }) return Completable(raw: source) } /** Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ public static func concat<Collection: Swift.Collection>(_ collection: Collection) -> Completable where Collection.Element == Completable { let source = Observable.concat(collection.map { $0.asObservable() }) return Completable(raw: source) } /** Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ public static func concat(_ sources: Completable ...) -> Completable { let source = Observable.concat(sources.map { $0.asObservable() }) return Completable(raw: source) } /** Merges the completion of all Completables from a collection into a single Completable. - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) - note: For `Completable`, `zip` is an alias for `merge`. - parameter sources: Collection of Completables to merge. - returns: A Completable that merges the completion of all Completables. */ public static func zip<Collection: Swift.Collection>(_ sources: Collection) -> Completable where Collection.Element == Completable { let source = Observable.merge(sources.map { $0.asObservable() }) return Completable(raw: source) } /** Merges the completion of all Completables from an array into a single Completable. - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) - note: For `Completable`, `zip` is an alias for `merge`. - parameter sources: Array of observable sequences to merge. - returns: A Completable that merges the completion of all Completables. */ public static func zip(_ sources: [Completable]) -> Completable { let source = Observable.merge(sources.map { $0.asObservable() }) return Completable(raw: source) } /** Merges the completion of all Completables into a single Completable. - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) - note: For `Completable`, `zip` is an alias for `merge`. - parameter sources: Collection of observable sequences to merge. - returns: The observable sequence that merges the elements of the observable sequences. */ public static func zip(_ sources: Completable...) -> Completable { let source = Observable.merge(sources.map { $0.asObservable() }) return Completable(raw: source) } }
mit
44fba0e3296f4d259abb5ec9b5c23118
41.493007
220
0.656052
5.265598
false
false
false
false
EugeneTrapeznikov/ETCollapsableTable
Source/ETCollapsableTableItem.swift
1
620
// // ETCollapsableTableItem.swift // ETCollapsableTable // // Created by Eugene Trapeznikov on 9/2/16. // Copyright © 2016 Evgenii Trapeznikov. All rights reserved. // import Foundation open class ETCollapsableTableItem { open var title: String = "" open var isOpen: Bool = false open var items: [ETCollapsableTableItem] = [] //MARK: - init public init() { } public init(title: String) { self.title = title } } func ==(left: ETCollapsableTableItem, right: ETCollapsableTableItem) -> Bool { return left.title == right.title && left.isOpen == right.isOpen && left.items.count == right.items.count }
mit
2c868939070480465f21505cdd0d28bb
21.107143
105
0.702746
3.158163
false
false
false
false
lieonCX/Live
Live/View/Home/Room/RooHomeViewController.swift
1
2180
// // RooHomeViewController.swift // Live // // Created by lieon on 2017/7/4. // Copyright © 2017年 ChengDuHuanLeHui. All rights reserved. // import UIKit import RxSwift import RxCocoa class RooHomeViewController: BaseViewController { fileprivate lazy var tableView: UITableView = { let taleView = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height)) taleView.separatorStyle = .none taleView.isPagingEnabled = true taleView.backgroundColor = UIColor(hex: 0xf2f2f2) taleView.register(RoomTableViewCell.self, forCellReuseIdentifier: "RoomTableViewCell") return taleView }() fileprivate lazy var containerView: UIView = UIView(frame: self.view.bounds) override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) } override func viewDidLoad() { super.viewDidLoad() setupUI() } } extension RooHomeViewController { fileprivate func setupUI() { view.addSubview(tableView) let items = Observable<[String]>.just(["1", "2", "3", "4", "5", "6"]) items.bind(to: tableView.rx.items(cellIdentifier: "RoomTableViewCell", cellType: RoomTableViewCell.self)) { [unowned self] (row, element, cell) in cell.backgroundColor = UIColor.blue cell.roomVC.closeBtn.rx.tap .subscribe(onNext: { (value) in self.dismiss(animated: true, completion: nil) }) .disposed(by: self.disposeBag) } .disposed(by: disposeBag) tableView.rx .setDelegate(self) .disposed(by: disposeBag) tableView.rx .modelSelected(String.self) .subscribe(onNext: { (value) in }) .disposed(by: disposeBag) } } extension RooHomeViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return view.bounds.height } }
mit
faf1d9c5c7907a3c58ee87687a63eada
31.014706
154
0.622416
4.622081
false
false
false
false
migueloruiz/la-gas-app-swift
lasgasmx/UIButton+Custome.swift
1
1801
// // UIButton+Custome.swift // lasgasmx // // Created by Desarrollo on 4/18/17. // Copyright © 2017 migueloruiz. All rights reserved. // import UIKit enum UIMapControlButtonType { case navigation case controls case refresh } class UIMapControlButton: UIButton { init( withTarget target: Any?, action: Selector, radius: CGFloat, type: UIMapControlButtonType ){ super.init(frame: CGRect(x: 0, y: 0, width: radius, height: radius)) self.layer.cornerRadius = radius self.clipsToBounds = true self.backgroundColor = .white self.tintColor = .black self.addTarget(target, action: action, for: .touchUpInside) self.setImage( getImageBy(type).withRenderingMode(.alwaysTemplate), for: .normal) self.imageView?.contentMode = .scaleAspectFit } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func getImageBy(_ type: UIMapControlButtonType ) -> UIImage{ switch type { case .refresh: return #imageLiteral(resourceName: "refresh") case .controls: return #imageLiteral(resourceName: "controls") case .navigation: return #imageLiteral(resourceName: "navigation") } } } class UIRoundedButton: UIButton { init( withTarget target: Any?, action: Selector, radius: CGFloat ){ super.init(frame: CGRect(x: 0, y: 0, width: radius, height: radius)) self.layer.cornerRadius = radius self.clipsToBounds = true self.tintColor = .white self.addTarget(target, action: action, for: .touchUpInside) self.isHidden = true self.alpha = 0 } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
5d5e4568c1c6fef9ba41120bf01bac73
28.508197
101
0.636111
4.255319
false
false
false
false
oarrabi/RangeSliderView
Pod/Classes/KnobViewOsx.swift
1
1267
// // KnobViewOsx.swift // Pods // // Created by Omar Abdelhafith on 07/02/2016. // // #if os(OSX) import Cocoa class KnobView: NSView { var backgroundNormalColor = NSColor(calibratedRed: 1, green: 1, blue: 1, alpha: 1) { didSet { needsDisplay = true } } var backgroundHighligtedColor = NSColor(red: 0.941, green: 0.941, blue: 0.941, alpha: 1) { didSet { needsDisplay = true } } var borderColor = NSColor(calibratedRed: 0.722, green: 0.722, blue: 0.722, alpha: 1) { didSet { needsDisplay = true } } var isHighlighted = false { didSet { needsDisplay = true } } var fillColor: NSColor { return isHighlighted ? backgroundHighligtedColor : backgroundNormalColor } override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) KnobViewImpl.drawKnob(forView: self, dirtyRect: dirtyRect) } override func mouseDown(theEvent: NSEvent) { isHighlighted = true super.mouseDown(theEvent) } override func mouseUp(theEvent: NSEvent) { isHighlighted = false super.mouseUp(theEvent) } } extension KnobView: Knob { } #endif
mit
a4200cabc5d75088b642ea32dc258c27
19.451613
94
0.592739
4.100324
false
false
false
false
svdo/swift-RichString
Pods/Nimble/Sources/Nimble/Adapters/NMBExpectation.swift
4
6897
#if canImport(Darwin) && !SWIFT_PACKAGE import class Foundation.NSObject import typealias Foundation.TimeInterval import enum Dispatch.DispatchTimeInterval private func from(objcPredicate: NMBPredicate) -> Predicate<NSObject> { return Predicate { actualExpression in let result = objcPredicate.satisfies(({ try actualExpression.evaluate() }), location: actualExpression.location) return result.toSwift() } } private func from(matcher: NMBMatcher, style: ExpectationStyle) -> Predicate<NSObject> { // Almost same as `Matcher.toClosure` let closure: (Expression<NSObject>, FailureMessage) throws -> Bool = { expr, msg in switch style { case .toMatch: return matcher.matches( // swiftlint:disable:next force_try ({ try! expr.evaluate() }), failureMessage: msg, location: expr.location ) case .toNotMatch: return !matcher.doesNotMatch( // swiftlint:disable:next force_try ({ try! expr.evaluate() }), failureMessage: msg, location: expr.location ) } } return Predicate._fromDeprecatedClosure(closure) } // Equivalent to Expectation, but for Nimble's Objective-C interface public class NMBExpectation: NSObject { internal let _actualBlock: () -> NSObject? internal var _negative: Bool internal let _file: FileString internal let _line: UInt internal var _timeout: DispatchTimeInterval = .seconds(1) @objc public init(actualBlock: @escaping () -> NSObject?, negative: Bool, file: FileString, line: UInt) { self._actualBlock = actualBlock self._negative = negative self._file = file self._line = line } private var expectValue: Expectation<NSObject> { return expect(file: _file, line: _line, self._actualBlock() as NSObject?) } @objc public var withTimeout: (TimeInterval) -> NMBExpectation { return { timeout in self._timeout = timeout.dispatchInterval return self } } @objc public var to: (NMBMatcher) -> NMBExpectation { return { matcher in if let pred = matcher as? NMBPredicate { self.expectValue.to(from(objcPredicate: pred)) } else { self.expectValue.to(from(matcher: matcher, style: .toMatch)) } return self } } @objc public var toWithDescription: (NMBMatcher, String) -> NMBExpectation { return { matcher, description in if let pred = matcher as? NMBPredicate { self.expectValue.to(from(objcPredicate: pred), description: description) } else { self.expectValue.to(from(matcher: matcher, style: .toMatch), description: description) } return self } } @objc public var toNot: (NMBMatcher) -> NMBExpectation { return { matcher in if let pred = matcher as? NMBPredicate { self.expectValue.toNot(from(objcPredicate: pred)) } else { self.expectValue.toNot(from(matcher: matcher, style: .toNotMatch)) } return self } } @objc public var toNotWithDescription: (NMBMatcher, String) -> NMBExpectation { return { matcher, description in if let pred = matcher as? NMBPredicate { self.expectValue.toNot(from(objcPredicate: pred), description: description) } else { self.expectValue.toNot(from(matcher: matcher, style: .toNotMatch), description: description) } return self } } @objc public var notTo: (NMBMatcher) -> NMBExpectation { return toNot } @objc public var notToWithDescription: (NMBMatcher, String) -> NMBExpectation { return toNotWithDescription } @objc public var toEventually: (NMBMatcher) -> Void { return { matcher in if let pred = matcher as? NMBPredicate { self.expectValue.toEventually( from(objcPredicate: pred), timeout: self._timeout, description: nil ) } else { self.expectValue.toEventually( from(matcher: matcher, style: .toMatch), timeout: self._timeout, description: nil ) } } } @objc public var toEventuallyWithDescription: (NMBMatcher, String) -> Void { return { matcher, description in if let pred = matcher as? NMBPredicate { self.expectValue.toEventually( from(objcPredicate: pred), timeout: self._timeout, description: description ) } else { self.expectValue.toEventually( from(matcher: matcher, style: .toMatch), timeout: self._timeout, description: description ) } } } @objc public var toEventuallyNot: (NMBMatcher) -> Void { return { matcher in if let pred = matcher as? NMBPredicate { self.expectValue.toEventuallyNot( from(objcPredicate: pred), timeout: self._timeout, description: nil ) } else { self.expectValue.toEventuallyNot( from(matcher: matcher, style: .toNotMatch), timeout: self._timeout, description: nil ) } } } @objc public var toEventuallyNotWithDescription: (NMBMatcher, String) -> Void { return { matcher, description in if let pred = matcher as? NMBPredicate { self.expectValue.toEventuallyNot( from(objcPredicate: pred), timeout: self._timeout, description: description ) } else { self.expectValue.toEventuallyNot( from(matcher: matcher, style: .toNotMatch), timeout: self._timeout, description: description ) } } } @objc public var toNotEventually: (NMBMatcher) -> Void { return toEventuallyNot } @objc public var toNotEventuallyWithDescription: (NMBMatcher, String) -> Void { return toEventuallyNotWithDescription } @objc public class func failWithMessage(_ message: String, file: FileString, line: UInt) { fail(message, location: SourceLocation(file: file, line: line)) } } #endif
mit
07de1516b268b65ce9baa74427ed85d4
34.369231
113
0.556184
5.358974
false
false
false
false
insidegui/WWDC
WWDC/Preferences.swift
1
5100
// // Preferences.swift // WWDC // // Created by Guilherme Rambo on 13/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Foundation import ConfCore extension Notification.Name { static let LocalVideoStoragePathPreferenceDidChange = Notification.Name("LocalVideoStoragePathPreferenceDidChange") static let RefreshPeriodicallyPreferenceDidChange = Notification.Name("RefreshPeriodicallyPreferenceDidChange") static let SkipBackAndForwardBy30SecondsPreferenceDidChange = Notification.Name("SkipBackAndForwardBy30SecondsPreferenceDidChange") static let SyncUserDataPreferencesDidChange = Notification.Name("SyncUserDataPreferencesDidChange") static let PreferredTranscriptLanguageDidChange = Notification.Name("PreferredTranscriptLanguageDidChange") } final class Preferences { static let shared: Preferences = Preferences() private let defaults = UserDefaults.standard private static let defaultLocalVideoStoragePath = NSString.path(withComponents: [NSHomeDirectory(), "Library", "Application Support", "WWDC"]) init() { defaults.register(defaults: [ "localVideoStoragePath": Self.defaultLocalVideoStoragePath, "includeAppBannerInSharedClips": true ]) } /// The URL for the folder where downloaded videos will be saved var localVideoStorageURL: URL { get { URL(fileURLWithPath: localVideoStoragePath) } set { localVideoStoragePath = newValue.path } } private var localVideoStoragePath: String { get { if let path = defaults.object(forKey: #function) as? String { return path } else { return Self.defaultLocalVideoStoragePath } } set { defaults.set(newValue, forKey: #function) } } #if !AGENT var activeTab: MainWindowTab { get { let rawValue = defaults.integer(forKey: #function) return MainWindowTab(rawValue: rawValue) ?? .schedule } set { defaults.set(newValue.rawValue, forKey: #function) } } #endif var selectedScheduleItemIdentifier: String? { get { return defaults.object(forKey: #function) as? String } set { defaults.set(newValue, forKey: #function) } } var selectedVideoItemIdentifier: String? { get { return defaults.object(forKey: #function) as? String } set { defaults.set(newValue, forKey: #function) } } var filtersState: String? { get { defaults.object(forKey: #function) as? String } set { defaults.set(newValue, forKey: #function) } } var userOptedOutOfCrashReporting: Bool { get { return defaults.bool(forKey: #function) } set { defaults.set(newValue, forKey: #function) } } var searchInTranscripts: Bool { get { return defaults.bool(forKey: #function) } set { defaults.set(newValue, forKey: #function) } } var searchInBookmarks: Bool { get { return defaults.bool(forKey: #function) } set { defaults.set(newValue, forKey: #function) } } var refreshPeriodically: Bool { get { return defaults.bool(forKey: #function) } set { defaults.set(newValue, forKey: #function) NotificationCenter.default.post(name: .RefreshPeriodicallyPreferenceDidChange, object: nil) } } var skipIntro: Bool { get { defaults.bool(forKey: #function) } set { defaults.set(newValue, forKey: #function) } } var includeAppBannerInSharedClips: Bool { get { defaults.bool(forKey: #function) } set { defaults.set(newValue, forKey: #function) } } var skipBackAndForwardBy30Seconds: Bool { get { return defaults.bool(forKey: #function) } set { defaults.set(newValue, forKey: #function) NotificationCenter.default.post(name: .SkipBackAndForwardBy30SecondsPreferenceDidChange, object: nil) } } var syncUserData: Bool { get { return defaults.bool(forKey: #function) } set { defaults.set(newValue, forKey: #function) NotificationCenter.default.post(name: .SyncUserDataPreferencesDidChange, object: nil) } } public static let fallbackTranscriptLanguageCode = "en" var transcriptLanguageCode: String { get { defaults.string(forKey: #function) ?? ConfigResponse.fallbackFeedLanguage } set { let notify = newValue != transcriptLanguageCode defaults.set(newValue, forKey: #function) guard notify else { return } NotificationCenter.default.post(name: .PreferredTranscriptLanguageDidChange, object: newValue) } } }
bsd-2-clause
a804b17115ba2ae84c5424d88513a81b
27.486034
146
0.618553
4.86082
false
false
false
false
ahoppen/swift
test/SourceKit/CursorInfo/cursor_generics.swift
8
1790
func testGenerics<T>(x: T) { } /// Doc Comment... func testGenericsWithComment<T>(x: T) { } func someFunc <A>() -> A { fatalError() } // rdar://problem/36871908 class MyType<T> { let test: Bool = false let items: [Int] = [] func myMethod() { if test {} for i in items {} } } // rdar://76750555 public protocol IP { init(networkBytes: Int) } public struct HostRecord<IPType: IP> { func foo() { let ipType = IPType(networkBytes: 42) } } // RUN: %sourcekitd-test -req=cursor -pos=1:10 %s -- %s | %FileCheck -check-prefix=CHECK1 %s // CHECK1: <Declaration>func testGenerics&lt;T&gt;(x: <Type usr="s:15cursor_generics12testGenerics1xyx_tlF1TL_xmfp">T</Type>)</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=5:10 %s -- %s | %FileCheck -check-prefix=CHECK2 %s // CHECK2: <Function // CHECK2: <Declaration>func testGenericsWithComment&lt;T&gt;(x: T)</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=8:16 %s -- %s | %FileCheck -check-prefix=CHECK3 %s // CHECK3: source.lang.swift.decl.generic_type_param // CHECK3: <Declaration>A</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=17:8 %s -- %s | %FileCheck -check-prefix=CHECK4 %s // CHECK4: source.lang.swift.ref.var.instance // CHECK4: <Declaration>let test: <Type usr="s:Sb">Bool</Type></Declaration> // RUN: %sourcekitd-test -req=cursor -pos=18:14 %s -- %s | %FileCheck -check-prefix=CHECK5 %s // CHECK5: source.lang.swift.ref.var.instance // CHECK5: <Declaration>let items: [<Type usr="s:Si">Int</Type>]</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=29:22 %s -- %s | %FileCheck -check-prefix=CHECK_IP_TYPE %s // CHECK_IP_TYPE: source.lang.swift.ref.generic_type_param // CHECK_IP_TYPE: <Declaration>IPType : <Type usr="s:15cursor_generics2IPP">IP</Type></Declaration>
apache-2.0
85cb4d9052b9d1001ce1637a0d33280a
32.148148
139
0.672067
2.823344
false
true
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/00104-swift-constraints-constraintsystem-finalize.swift
11
784
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse func k<q>() -> [n<q>] { r [] } func k(l: Int = 0) { } n n = k n() func n<q { l n { func o o _ = o } } func ^(k: m, q) -> q { r !(k) } protocol k { j q j o = q j f = q } class l<r : n, l : n p r.q == l> : k { } class l<r, l> { } protocol n { j q } protocol k : k { } class k<f : l, q : l p f.q == q> { } protocol l { j q j o } struct n<r : l>
apache-2.0
415929c1647d0adf148c1cf13b368c97
16.422222
78
0.561224
2.712803
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/EditImageModalController.swift
1
16258
// // EditImagModalController.swift // Telegram // // Created by Mikhail Filimonov on 01/10/2018. // Copyright © 2018 Telegram. All rights reserved. // import Cocoa import TGUIKit import SwiftSignalKit private final class EditImageView : View { fileprivate let imageView: ImageView = ImageView() private var image: CGImage fileprivate let selectionRectView: SelectionRectView = SelectionRectView(frame: NSMakeRect(0, 0, 100, 100)) private let imageContainer: View = View() private let reset: TitleButton = TitleButton() private var currentData: EditedImageData? private let fakeCorners: (topLeft: ImageView, topRight: ImageView, bottomLeft: ImageView, bottomRight: ImageView) private var canReset: Bool = false required init(frame frameRect: NSRect, image: CGImage) { self.image = image fakeCorners = (topLeft: ImageView(), topRight: ImageView(), bottomLeft: ImageView(), bottomRight: ImageView()) let corners = generateSelectionAreaCorners(.white) fakeCorners.topLeft.image = corners.topLeft fakeCorners.topRight.image = corners.topRight fakeCorners.bottomLeft.image = corners.bottomLeft fakeCorners.bottomRight.image = corners.bottomRight fakeCorners.topLeft.sizeToFit() fakeCorners.topRight.sizeToFit() fakeCorners.bottomLeft.sizeToFit() fakeCorners.bottomRight.sizeToFit() imageView.background = .white super.init(frame: frameRect) imageContainer.addSubview(fakeCorners.topLeft) imageContainer.addSubview(fakeCorners.topRight) imageContainer.addSubview(fakeCorners.bottomLeft) imageContainer.addSubview(fakeCorners.bottomRight) imageView.wantsLayer = true imageView.image = image addSubview(imageContainer) imageContainer.addSubview(imageView) imageView.addSubview(selectionRectView) addSubview(reset) // reset.isHidden = true autoresizesSubviews = false reset.set(font: .medium(.title), for: .Normal) reset.set(color: .white, for: .Normal) reset.set(text: strings().editImageControlReset, for: .Normal) _ = reset.sizeToFit() } var controls: View? { didSet { oldValue?.removeFromSuperview() if let controls = controls { addSubview(controls) } } } var selectedRect: NSRect { let multiplierX = self.imageView.image!.size.width / selectionRectView.frame.width let multiplierY = self.imageView.image!.size.height / selectionRectView.frame.height let rect = NSMakeRect(selectionRectView.selectedRect.minX, selectionRectView.selectedRect.minY, selectionRectView.selectedRect.width, selectionRectView.selectedRect.height) return rect.apply(multiplier: NSMakeSize(multiplierX, multiplierY)) } fileprivate func updateVisibleCorners() { } func applyEditedData(_ value: EditedImageData, canReset: Bool, reset: @escaping()->Void) { if value.isNeedToRegenerate(currentData) { self.imageView.image = value.makeImage(self.image) } self.currentData = value setFrameSize(frame.size) if value.selectedRect != NSZeroRect { self.selectionRectView.applyRect(value.selectedRect, force: self.selectionRectView.dimensions != value.dimensions, dimensions: value.dimensions) } else { selectionRectView.applyRect(imageView.bounds, dimensions: value.dimensions) } self.canReset = canReset self.reset.isHidden = !canReset self.reset.removeAllHandlers() self.reset.set(handler: { _ in reset() }, for: .Click) needsLayout = true } override func mouseUp(with event: NSEvent) { super.mouseUp(with: event) if !imageView._mouseInside() && !controls!.mouseInside() && !selectionRectView.inDragging { if let data = self.currentData, selectionRectView.isWholeSelected && data.hasntData { (controls as? EditImageControlsView)?.cancel.send(event: .Click) } else { confirm(for: mainWindow, information: strings().editImageControlConfirmDiscard, successHandler: { [weak self] _ in (self?.controls as? EditImageControlsView)?.cancel.send(event: .Click) }) } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } override func setFrameSize(_ newSize: NSSize) { let oldSize = self.frame.size super.setFrameSize(newSize) imageContainer.setFrameSize(frame.width, frame.height - 120) let imageSize = imageView.image!.size.fitted(NSMakeSize(imageContainer.frame.width - 8, imageContainer.frame.height - 8)) let oldImageSize = imageView.frame.size imageView.setFrameSize(imageSize) selectionRectView.frame = imageView.bounds imageView.center() if oldSize != newSize, oldSize != NSZeroSize, inLiveResize { let multiplier = NSMakeSize(imageSize.width / oldImageSize.width, imageSize.height / oldImageSize.height) selectionRectView.applyRect(selectionRectView.selectedRect.apply(multiplier: multiplier)) } if let controls = controls { controls.centerX(y: frame.height - controls.frame.height) reset.centerX(y: controls.frame.minY - (80 - reset.frame.height) / 2) } } func hideElements(_ hide: Bool) { imageContainer.isHidden = hide reset.isHidden = hide || !canReset } func contentSize(maxSize: NSSize) -> NSSize { return NSMakeSize(maxSize.width, maxSize.height) } override func layout() { super.layout() fakeCorners.topLeft.setFrameOrigin(selectionRectView.convert(selectionRectView.topLeftPosition, to: fakeCorners.topLeft.superview)) fakeCorners.topRight.setFrameOrigin(selectionRectView.convert(selectionRectView.topRightPosition, to: fakeCorners.topRight.superview)) fakeCorners.bottomLeft.setFrameOrigin(selectionRectView.convert(selectionRectView.bottomLeftPosition, to: fakeCorners.bottomLeft.superview)) fakeCorners.bottomRight.setFrameOrigin(selectionRectView.convert(selectionRectView.bottomRightPosition, to: fakeCorners.bottomRight.superview)) } } enum EditControllerSettings { case disableSizes(dimensions: SelectionRectDimensions) case plain } class EditImageModalController: ModalViewController { private let path: URL private let editValue: ValuePromise<EditedImageData> = ValuePromise(ignoreRepeated: true) private let editState: Atomic<EditedImageData> private let updateDisposable = MetaDisposable() private let updatedRectDisposable = MetaDisposable() private var controls: EditImageControls! private let image: CGImage private let settings: EditControllerSettings private let resultValue: Promise<(URL, EditedImageData?)> = Promise() private var canReset: Bool var onClose: () -> Void = {} init(_ path: URL, defaultData: EditedImageData? = nil, settings: EditControllerSettings = .plain) { self.canReset = defaultData != nil editState = Atomic(value: defaultData ?? EditedImageData(originalUrl: path)) self.image = NSImage(contentsOf: path)!.cgImage(forProposedRect: nil, context: nil, hints: nil)! self.path = path self.settings = settings super.init() bar = .init(height: 0) editValue.set(defaultData ?? EditedImageData(originalUrl: path)) } override func close(animationType: ModalAnimationCloseBehaviour = .common) { super.close(animationType: animationType) onClose() } var result:Signal<(URL, EditedImageData?), NoError> { return resultValue.get() } private var markAsClosed: Bool = false override func returnKeyAction() -> KeyHandlerResult { guard !markAsClosed else { return .invoked } let currentData = editState.modify {$0} resultValue.set(EditedImageData.generateNewUrl(data: currentData, selectedRect: genericView.selectedRect) |> map { ($0, $0 == currentData.originalUrl ? nil : currentData)}) let signal = resultValue.get() |> take(1) |> deliverOnMainQueue |> delay(0.1, queue: .mainQueue()) markAsClosed = true _ = signal.start(next: { [weak self] _ in self?.close() }) return .invoked } override open func measure(size: NSSize) { if let contentSize = self.modal?.window.contentView?.frame.size { self.modal?.resize(with:genericView.contentSize(maxSize: NSMakeSize(contentSize.width - 80, contentSize.height - 80)), animated: false) } } public func updateSize(_ animated: Bool) { if let contentSize = self.modal?.window.contentView?.frame.size { self.modal?.resize(with:genericView.contentSize(maxSize: NSMakeSize(contentSize.width - 80, contentSize.height - 80)), animated: animated) } } override var dynamicSize: Bool { return true } override func initializer() -> NSView { return EditImageView.init(frame: NSMakeRect(_frameRect.minX, _frameRect.minY, _frameRect.width, _frameRect.height - bar.height), image: image) } override var containerBackground: NSColor { return .clear } override func viewClass() -> AnyClass { return EditImageView.self } private var genericView: EditImageView { return self.view as! EditImageView } override var background: NSColor { return .clear } override var isVisualEffectBackground: Bool { return true } private func updateValue(_ f:@escaping(EditedImageData) -> EditedImageData) { self.editValue.set(editState.modify(f)) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) switch settings { case let .disableSizes(dimensions): let imageSize = self.genericView.imageView.frame.size let size = NSMakeSize(200, 200).aspectFitted(imageSize) let rect = NSMakeRect((imageSize.width - size.width) / 2, (imageSize.height - size.height) / 2, size.width, size.height) genericView.selectionRectView.isCircleCap = true updateValue { data in return data.withUpdatedDimensions(dimensions).withUpdatedSelectedRect(rect) } default: genericView.selectionRectView.isCircleCap = false } } override var responderPriority: HandlerPriority { return .modal } override var handleAllEvents: Bool { return true } private func loadCanvas() { guard let window = self.window else { return } genericView.hideElements(true) showModal(with: EditImageCanvasController(image: self.image, actions: editState.with { $0.paintings }, updatedImage: { [weak self] paintings in self?.updateValue { $0.withUpdatedPaintings(paintings) } }, closeHandler: { [weak self] in self?.genericView.hideElements(false) }), for: window, animated: false, animationType: .alpha) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.controls.arguments.rotate() return .invoked }, with: self, for: .R, priority: .modal, modifierFlags: [.command]) window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.loadCanvas() return .invoked }, with: self, for: .D, priority: .modal, modifierFlags: [.command]) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) window?.removeAllHandlers(for: self) } private func rotate() { var rect = NSZeroRect let imageSize = genericView.imageView.frame.size var isFlipped: Bool = false var newRotation: ImageOrientation? self.updateValue { current in rect = current.selectedRect let orientation: ImageOrientation? if let value = current.orientation { switch value { case .right: orientation = .down case .down: orientation = .left default: orientation = nil } } else { orientation = .right } newRotation = orientation isFlipped = current.isHorizontalFlipped return current.withUpdatedOrientation(orientation) } // if isFlipped, let newRotation = newRotation, newRotation == .right { // rect.origin.x = imageSize.width - rect.maxX // } else if isFlipped, newRotation == nil { // rect.origin.x = imageSize.width - rect.maxX // } let newSize = genericView.imageView.frame.size let multiplierWidth = newSize.height / imageSize.width let multiplierHeight = newSize.width / imageSize.height rect = rect.rotate90Degress(parentSize: imageSize) rect = rect.apply(multiplier: NSMakeSize(multiplierHeight, multiplierWidth)) self.updateValue { current in return current.withUpdatedSelectedRect(rect) } } private func flip() { let imageSize = genericView.imageView.frame.size updateValue { value in var rect = value.selectedRect rect.origin.x = imageSize.width - rect.maxX return value.withUpdatedFlip(!value.isHorizontalFlipped).withUpdatedSelectedRect(rect) } } override func viewDidLoad() { super.viewDidLoad() self.controls = EditImageControls(settings: settings, arguments: EditImageControlsArguments(cancel: { [weak self] in self?.close() }, success: { [weak self] in _ = self?.returnKeyAction() }, flip: { [weak self] in self?.flip() }, selectionDimensions: { [weak self] dimension in self?.updateValue { value in return value.withUpdatedDimensions(dimension) } }, rotate: { [weak self] in self?.rotate() }, draw: { [weak self] in self?.loadCanvas() }), stateValue: editValue.get()) genericView.controls = self.controls.genericView updateDisposable.set((editValue.get() |> deliverOnMainQueue).start(next: { [weak self] data in guard let `self` = self else {return} self.readyOnce() self.updateSize(false) self.genericView.applyEditedData(data, canReset: self.canReset, reset: { [weak self] in self?.canReset = false self?.updateValue {$0.withUpdatedSelectedRect(NSZeroRect).withUpdatedFlip(false).withUpdatedDimensions(.none).withUpdatedOrientation(nil).withUpdatedPaintings([])} }) })) updatedRectDisposable.set(genericView.selectionRectView.updatedRect.start(next: { [weak self] rect in self?.updateValue { $0.withUpdatedSelectedRect(rect) } self?.genericView.updateVisibleCorners() })) } deinit { updateDisposable.dispose() updatedRectDisposable.dispose() } }
gpl-2.0
eb163c8e01e91b450bde50ec8cba3c51
35.450673
180
0.62693
4.948858
false
false
false
false
seorenn/SRChoco
Tests/TestStringExtensions.swift
1
2928
// // TestStringExtensions.swift // SRChocoDemo-OSX // // Created by Seorenn. // Copyright (c) 2014 Seorenn. All rights reserved. // import Foundation import XCTest import SRChoco class TestStringExtensions: XCTestCase { 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 testSubscript() { let str = "123 ABC abc-" XCTAssertEqual(str[0], Character("1")) XCTAssertEqual(str[4], Character("A")) XCTAssertEqual(str[-1], Character("-")) XCTAssertEqual(str[-2], Character("c")) } func testSubstring() { let strA = "This is test string..." let strB = strA[1..<4] XCTAssertEqual(strB, "his") XCTAssertEqual(strA[2..<6], "is i") let strC = strA[1..<3] XCTAssertEqual(strC, "hi") XCTAssertEqual(strA.substring(startIndex: 4, length: 4), " is ") XCTAssertEqual(strA.prefix(length: 4), "This") XCTAssertEqual(strA.postfix(length: 3), "...") let strD = strA[NSMakeRange(0, 3)] XCTAssertEqual(strD, "Thi") let strE = strA[NSMakeRange(5, 4)] XCTAssertEqual(strE, "is t") } func testTrim() { let strA = " A string " XCTAssertEqual(strA.trimmedString(), "A string") } func testContain() { let str = "This is test string by test contain" XCTAssertTrue(str.contain(string: "test")) XCTAssertFalse(str.contain(string: "TEST")) XCTAssertTrue(str.contain(string: "TEST", ignoreCase: true)) XCTAssertTrue(str.contain(strings: ["is", "test", "string"])) XCTAssertTrue(str.contain(strings: ["is", "test", "string"], ORMode: false, ignoreCase: false)) XCTAssertTrue(str.contain(strings: ["IS", "TEST", "String"], ORMode: false, ignoreCase: true)) XCTAssertTrue(str.contain(strings: ["is", "testxx", "nonstring", "aaa"], ORMode: true)) XCTAssertTrue(str.contain(strings: ["IS", "XX", "non", "aaa"], ORMode: true, ignoreCase: true)) XCTAssertFalse(str.contain(strings: ["aaa", "bbb"])) } func testSplit() { let str = "This is test" let array = str.array(bySplitter: nil) XCTAssertEqual(array.count, 3) XCTAssertEqual(array[0], "This") XCTAssertEqual(array[1], "is") XCTAssertEqual(array[2], "test") } func testOptionalString() { let a: String? = nil let b: String? = "" let c: String? = "good" XCTAssertTrue(a.isNilOrEmpty) XCTAssertTrue(b.isNilOrEmpty) XCTAssertFalse(c.isNilOrEmpty) } }
mit
8241e816e25c90cfec308314ee8bee41
29.5
111
0.588456
3.989101
false
true
false
false
SunshineYG888/YG_NetEaseOpenCourse
YG_NetEaseOpenCourse/YG_NetEaseOpenCourse/Classes/View/Home/YGHomeTableViewController.swift
1
5125
// // YGHomeTableViewController.swift // YG_NetEaseOpenCourse // // Created by male on 16/4/13. // Copyright © 2016年 yg. All rights reserved. // import UIKit import SVProgressHUD import MJRefresh private let HomeCellID = "home_cell_id" class YGHomeTableViewController: UITableViewController { /* 属性 */ private lazy var courseListViewModel: YGCourseListViewModel = YGCourseListViewModel() private var searchView: YGSearchView = YGSearchView(searViewType: SearchViewType.Home, frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 44)) let gifHeader = MJRefreshGifHeader() let gifFooter = MJRefreshAutoGifFooter() override func viewDidLoad() { super.viewDidLoad() tableView.backgroundColor = UIColor.whiteColor() setupUI() loadData() registerNotifications() } /* 下拉刷新组图 */ private lazy var headerRefreshingImages: [UIImage] = { var images = [UIImage]() for i in 32...58 { images.append(UIImage(named: "pull_000\(i)")!) } return images }() /* 上拉刷新组图 */ private lazy var footerRefreshingImages: [UIImage] = { var images = [UIImage]() for i in 31...44 { images.append(UIImage(named: "loading4_000\(i)")!) } for i in 32...45 { images.append(UIImage(named: "loading4_000\(76 - i)")!) } return images }() @objc private func clearSearchHistoryBtnDidClick() { print("clearSearchHistoryBtnDidClick") } /* 注册通知 */ private func registerNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "clearSearchHistoryBtnDidClick", name: ClearBtnDidClickNotification, object: nil) } /* 移除通知 */ deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } } /* 设置界面 */ extension YGHomeTableViewController { private func setupUI() { setNavBar() prepareForTableView() } private func setNavBar() { navigationItem.titleView = searchView } private func prepareForTableView() { // 注册 cell tableView.registerClass(YGHomeCourseCell.self, forCellReuseIdentifier: HomeCellID) // 设置自动计算行高 tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 300 // 设置分割线 tableView.separatorStyle = .None setheaderRefresh() setFooterRefresh() } /* 设置 headerView 的刷新功能 */ private func setheaderRefresh() { gifHeader.setRefreshingTarget(self, refreshingAction: Selector("loadMoreNewData")) gifHeader.setImages([headerRefreshingImages.first!], forState: .Idle) gifHeader.setImages([headerRefreshingImages.first!], forState: .Pulling) gifHeader.setImages(headerRefreshingImages, forState: .Refreshing) gifHeader.lastUpdatedTimeLabel?.hidden = true gifHeader.stateLabel?.hidden = true tableView.mj_header = gifHeader } func loadMoreNewData() { print("loadNewData") dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in self.tableView.mj_header.endRefreshing() } } /* 设置 footerView 的自动刷新功能 */ private func setFooterRefresh() { gifFooter.setRefreshingTarget(self, refreshingAction: Selector("loadMoreFormerData")) gifFooter.setImages(footerRefreshingImages, forState: .Refreshing) gifFooter.refreshingTitleHidden = true tableView.mj_footer = gifFooter } func loadMoreFormerData() { print("loadMoreFormerData") dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in self.tableView.mj_header.endRefreshing() } } } /* 加载数据相关 */ extension YGHomeTableViewController { private func loadData() { courseListViewModel.loadHomeData { (isSuccess) -> () in if !isSuccess { SVProgressHUD.showErrorWithStatus(AppErrorTip) return } self.tableView.reloadData() //print(self.courseListViewModel.courseDataViewModelArr[0].courseData) } } } /* tableView's dataSource && delegate */ extension YGHomeTableViewController { override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return courseListViewModel.courseDataViewModelArr.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(HomeCellID, forIndexPath: indexPath) as! YGHomeCourseCell cell.courseDataViewModel = courseListViewModel.courseDataViewModelArr[indexPath.row] return cell } }
mit
f2e78ff6d15c152ac79b5d6bd6a0fdd6
29.839506
154
0.647318
4.822394
false
false
false
false
ProcedureKit/ProcedureKit
Tests/ProcedureKitCloudTests/CKMarkNotificationsReadOperationTests.swift
2
7553
// // ProcedureKit // // Copyright © 2015-2018 ProcedureKit. All rights reserved. // import XCTest import CloudKit import ProcedureKit import TestingProcedureKit @testable import ProcedureKitCloud class TestCKMarkNotificationsReadOperation: TestCKOperation, CKMarkNotificationsReadOperationProtocol, AssociatedErrorProtocol { typealias AssociatedError = MarkNotificationsReadError<String> var notificationIDs: [String] = [] var error: Error? = nil var markNotificationsReadCompletionBlock: (([String]?, Error?) -> Void)? = nil init(markIDsToRead: [String] = [], error: Error? = nil) { self.notificationIDs = markIDsToRead self.error = error super.init() } override func main() { markNotificationsReadCompletionBlock?(notificationIDs, error) } } class CKMarkNotificationsReadOperationTests: CKProcedureTestCase { var target: TestCKMarkNotificationsReadOperation! var operation: CKProcedure<TestCKMarkNotificationsReadOperation>! var toMark: [TestCKMarkNotificationsReadOperation.NotificationID]! override func setUp() { super.setUp() toMark = [ "this-is-an-id", "this-is-another-id" ] target = TestCKMarkNotificationsReadOperation(markIDsToRead: toMark) operation = CKProcedure(operation: target) } override func tearDown() { target = nil operation = nil super.tearDown() } func test__set_get__notificationIDs() { let notificationIDs = [ "an-id", "another-id" ] operation.notificationIDs = notificationIDs XCTAssertEqual(operation.notificationIDs, notificationIDs) XCTAssertEqual(target.notificationIDs, notificationIDs) } func test__success_without_completion_block() { wait(for: operation) PKAssertProcedureFinished(operation) } func test__success_with_completion_block() { var didExecuteBlock = false var receivedNotificationIDs: [String]? operation.setMarkNotificationsReadCompletionBlock { notificationIDsMarkedRead in didExecuteBlock = true receivedNotificationIDs = notificationIDsMarkedRead } wait(for: operation) PKAssertProcedureFinished(operation) XCTAssertTrue(didExecuteBlock) XCTAssertEqual(receivedNotificationIDs ?? ["this is not the id you're looking for"], toMark) } func test__error_without_completion_block() { target.error = TestError() wait(for: operation) PKAssertProcedureFinished(operation) } func test__error_with_completion_block() { var didExecuteBlock = false operation.setMarkNotificationsReadCompletionBlock { notificationIDsMarkedRead in didExecuteBlock = true } let error = TestError() target.error = error wait(for: operation) PKAssertProcedureFinished(operation, withErrors: true) XCTAssertFalse(didExecuteBlock) } } class CloudKitProcedureMarkNotificationsReadOperationTests: CKProcedureTestCase { typealias T = TestCKMarkNotificationsReadOperation var cloudkit: CloudKitProcedure<T>! override func setUp() { super.setUp() cloudkit = CloudKitProcedure(strategy: .immediate) { TestCKMarkNotificationsReadOperation() } cloudkit.container = container cloudkit.notificationIDs = [ "notification id 1", "notification id 2" ] } override func tearDown() { cloudkit = nil super.tearDown() } func test__set_get__errorHandlers() { cloudkit.set(errorHandlers: [.internalError: cloudkit.passthroughSuggestedErrorHandler]) XCTAssertEqual(cloudkit.errorHandlers.count, 1) XCTAssertNotNil(cloudkit.errorHandlers[.internalError]) } func test__set_get_container() { cloudkit.container = "I'm a different container!" XCTAssertEqual(cloudkit.container, "I'm a different container!") } func test__set_get__notificationIDs() { cloudkit.notificationIDs = [ "notification id 3", "notification id 4" ] XCTAssertEqual(cloudkit.notificationIDs, [ "notification id 3", "notification id 4" ]) } func test__cancellation() { cloudkit.cancel() wait(for: cloudkit) PKAssertProcedureCancelled(cloudkit) } func test__success_without_completion_block_set() { wait(for: cloudkit) PKAssertProcedureFinished(cloudkit) } func test__success_with_completion_block_set() { var didExecuteBlock = false cloudkit.setMarkNotificationsReadCompletionBlock { _ in didExecuteBlock = true } wait(for: cloudkit) PKAssertProcedureFinished(cloudkit) XCTAssertTrue(didExecuteBlock) } func test__error_without_completion_block_set() { cloudkit = CloudKitProcedure(strategy: .immediate) { let operation = TestCKMarkNotificationsReadOperation() operation.error = NSError(domain: CKErrorDomain, code: CKError.internalError.rawValue, userInfo: nil) return operation } wait(for: cloudkit) PKAssertProcedureFinished(cloudkit) } func test__error_with_completion_block_set() { let error = NSError(domain: CKErrorDomain, code: CKError.internalError.rawValue, userInfo: nil) cloudkit = CloudKitProcedure(strategy: .immediate) { let operation = TestCKMarkNotificationsReadOperation() operation.error = error return operation } var didExecuteBlock = false cloudkit.setMarkNotificationsReadCompletionBlock { _ in didExecuteBlock = true } wait(for: cloudkit) PKAssertProcedureFinished(cloudkit, withErrors: true) XCTAssertFalse(didExecuteBlock) } func test__error_which_retries_using_retry_after_key() { var shouldError = true cloudkit = CloudKitProcedure(strategy: .immediate) { let op = TestCKMarkNotificationsReadOperation() if shouldError { let userInfo = [CKErrorRetryAfterKey: NSNumber(value: 0.001)] op.error = NSError(domain: CKErrorDomain, code: CKError.Code.serviceUnavailable.rawValue, userInfo: userInfo) shouldError = false } return op } var didExecuteBlock = false cloudkit.setMarkNotificationsReadCompletionBlock { _ in didExecuteBlock = true } wait(for: cloudkit) PKAssertProcedureFinished(cloudkit) XCTAssertTrue(didExecuteBlock) } func test__error_which_retries_using_custom_handler() { var shouldError = true cloudkit = CloudKitProcedure(strategy: .immediate) { let op = TestCKMarkNotificationsReadOperation() if shouldError { op.error = NSError(domain: CKErrorDomain, code: CKError.Code.limitExceeded.rawValue, userInfo: nil) shouldError = false } return op } var didRunCustomHandler = false cloudkit.set(errorHandlerForCode: .limitExceeded) { _, _, _, suggestion in didRunCustomHandler = true return suggestion } var didExecuteBlock = false cloudkit.setMarkNotificationsReadCompletionBlock { _ in didExecuteBlock = true } wait(for: cloudkit) PKAssertProcedureFinished(cloudkit) XCTAssertTrue(didExecuteBlock) XCTAssertTrue(didRunCustomHandler) } }
mit
2234bfa182b68849f6f7e8ae250153eb
33.642202
128
0.667903
5.172603
false
true
false
false
Jintin/Swimat
Parser/Extension/ExtensionChar.swift
1
792
import Foundation extension Character { func isAZ() -> Bool { if self >= "a" && self <= "z" { return true } else if self >= "A" && self <= "Z" { return true } else if self >= "0" && self <= "9" { return true } return false } func isOperator() -> Bool { return self == "+" || self == "-" || self == "*" || self == "/" || self == "%" } func isUpperBlock() -> Bool { return self == "{" || self == "[" || self == "(" } func isLowerBlock() -> Bool { return self == "}" || self == "]" || self == ")" } func isSpace() -> Bool { return self == " " || self == "\t" } func isBlank() -> Bool { return isSpace() || self == "\n" } }
mit
012cf5a7440b786d88763bb15205fbf8
21
86
0.396465
3.940299
false
false
false
false
marekhac/WczasyNadBialym-iOS
WczasyNadBialym/WczasyNadBialym/ViewControllers/Service/ServiceMap/ServiceMapViewController.swift
1
1523
// // ServiceMapViewController.swift // WczasyNadBialym // // Created by Marek Hać on 10.11.2017. // Copyright © 2017 Marek Hać. All rights reserved. // import UIKit import MapKit import GoogleMobileAds class ServiceMapViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var bannerView: GADBannerView! @IBOutlet weak var bannerViewHeightConstraint: NSLayoutConstraint! var adHandler : AdvertisementHandler? var gpsLat: Double = 0.0 var gpsLng: Double = 0.0 var pinTitle: String = "" var pinSubtitle: String = "" let mapType: MKMapType = MKMapType.hybridFlyover @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() self.mapView.fillMap(self.gpsLat, self.gpsLng, self.pinTitle, self.pinSubtitle, mapType) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) displayAdvertisementBanner() } // MARK: - Request for advertisement func displayAdvertisementBanner() { self.adHandler = AdvertisementHandler(bannerAdView: self.bannerView) if let adHandler = self.adHandler { adHandler.adViewHeightConstraint = self.bannerViewHeightConstraint adHandler.showAd(viewController: self) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-3.0
c85ebd2b312c20e4c7cfe8d5388c8577
26.636364
96
0.673684
4.76489
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/CloudDirectory/CloudDirectory_Error.swift
1
11073
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for CloudDirectory public struct CloudDirectoryErrorType: AWSErrorType { enum Code: String { case accessDeniedException = "AccessDeniedException" case batchWriteException = "BatchWriteException" case cannotListParentOfRootException = "CannotListParentOfRootException" case directoryAlreadyExistsException = "DirectoryAlreadyExistsException" case directoryDeletedException = "DirectoryDeletedException" case directoryNotDisabledException = "DirectoryNotDisabledException" case directoryNotEnabledException = "DirectoryNotEnabledException" case facetAlreadyExistsException = "FacetAlreadyExistsException" case facetInUseException = "FacetInUseException" case facetNotFoundException = "FacetNotFoundException" case facetValidationException = "FacetValidationException" case incompatibleSchemaException = "IncompatibleSchemaException" case indexedAttributeMissingException = "IndexedAttributeMissingException" case internalServiceException = "InternalServiceException" case invalidArnException = "InvalidArnException" case invalidAttachmentException = "InvalidAttachmentException" case invalidFacetUpdateException = "InvalidFacetUpdateException" case invalidNextTokenException = "InvalidNextTokenException" case invalidRuleException = "InvalidRuleException" case invalidSchemaDocException = "InvalidSchemaDocException" case invalidTaggingRequestException = "InvalidTaggingRequestException" case limitExceededException = "LimitExceededException" case linkNameAlreadyInUseException = "LinkNameAlreadyInUseException" case notIndexException = "NotIndexException" case notNodeException = "NotNodeException" case notPolicyException = "NotPolicyException" case objectAlreadyDetachedException = "ObjectAlreadyDetachedException" case objectNotDetachedException = "ObjectNotDetachedException" case resourceNotFoundException = "ResourceNotFoundException" case retryableConflictException = "RetryableConflictException" case schemaAlreadyExistsException = "SchemaAlreadyExistsException" case schemaAlreadyPublishedException = "SchemaAlreadyPublishedException" case stillContainsLinksException = "StillContainsLinksException" case unsupportedIndexTypeException = "UnsupportedIndexTypeException" case validationException = "ValidationException" } private let error: Code public let context: AWSErrorContext? /// initialize CloudDirectory public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// Access denied. Check your permissions. public static var accessDeniedException: Self { .init(.accessDeniedException) } /// A BatchWrite exception has occurred. public static var batchWriteException: Self { .init(.batchWriteException) } /// Cannot list the parents of a Directory root. public static var cannotListParentOfRootException: Self { .init(.cannotListParentOfRootException) } /// Indicates that a Directory could not be created due to a naming conflict. Choose a different name and try again. public static var directoryAlreadyExistsException: Self { .init(.directoryAlreadyExistsException) } /// A directory that has been deleted and to which access has been attempted. Note: The requested resource will eventually cease to exist. public static var directoryDeletedException: Self { .init(.directoryDeletedException) } /// An operation can only operate on a disabled directory. public static var directoryNotDisabledException: Self { .init(.directoryNotDisabledException) } /// Operations are only permitted on enabled directories. public static var directoryNotEnabledException: Self { .init(.directoryNotEnabledException) } /// A facet with the same name already exists. public static var facetAlreadyExistsException: Self { .init(.facetAlreadyExistsException) } /// Occurs when deleting a facet that contains an attribute that is a target to an attribute reference in a different facet. public static var facetInUseException: Self { .init(.facetInUseException) } /// The specified Facet could not be found. public static var facetNotFoundException: Self { .init(.facetNotFoundException) } /// The Facet that you provided was not well formed or could not be validated with the schema. public static var facetValidationException: Self { .init(.facetValidationException) } /// Indicates a failure occurred while performing a check for backward compatibility between the specified schema and the schema that is currently applied to the directory. public static var incompatibleSchemaException: Self { .init(.incompatibleSchemaException) } /// An object has been attempted to be attached to an object that does not have the appropriate attribute value. public static var indexedAttributeMissingException: Self { .init(.indexedAttributeMissingException) } /// Indicates a problem that must be resolved by Amazon Web Services. This might be a transient error in which case you can retry your request until it succeeds. Otherwise, go to the AWS Service Health Dashboard site to see if there are any operational issues with the service. public static var internalServiceException: Self { .init(.internalServiceException) } /// Indicates that the provided ARN value is not valid. public static var invalidArnException: Self { .init(.invalidArnException) } /// Indicates that an attempt to make an attachment was invalid. For example, attaching two nodes with a link type that is not applicable to the nodes or attempting to apply a schema to a directory a second time. public static var invalidAttachmentException: Self { .init(.invalidAttachmentException) } /// An attempt to modify a Facet resulted in an invalid schema exception. public static var invalidFacetUpdateException: Self { .init(.invalidFacetUpdateException) } /// Indicates that the NextToken value is not valid. public static var invalidNextTokenException: Self { .init(.invalidNextTokenException) } /// Occurs when any of the rule parameter keys or values are invalid. public static var invalidRuleException: Self { .init(.invalidRuleException) } /// Indicates that the provided SchemaDoc value is not valid. public static var invalidSchemaDocException: Self { .init(.invalidSchemaDocException) } /// Can occur for multiple reasons such as when you tag a resource that doesn’t exist or if you specify a higher number of tags for a resource than the allowed limit. Allowed limit is 50 tags per resource. public static var invalidTaggingRequestException: Self { .init(.invalidTaggingRequestException) } /// Indicates that limits are exceeded. See Limits for more information. public static var limitExceededException: Self { .init(.limitExceededException) } /// Indicates that a link could not be created due to a naming conflict. Choose a different name and then try again. public static var linkNameAlreadyInUseException: Self { .init(.linkNameAlreadyInUseException) } /// Indicates that the requested operation can only operate on index objects. public static var notIndexException: Self { .init(.notIndexException) } /// Occurs when any invalid operations are performed on an object that is not a node, such as calling ListObjectChildren for a leaf node object. public static var notNodeException: Self { .init(.notNodeException) } /// Indicates that the requested operation can only operate on policy objects. public static var notPolicyException: Self { .init(.notPolicyException) } /// Indicates that the object is not attached to the index. public static var objectAlreadyDetachedException: Self { .init(.objectAlreadyDetachedException) } /// Indicates that the requested operation cannot be completed because the object has not been detached from the tree. public static var objectNotDetachedException: Self { .init(.objectNotDetachedException) } /// The specified resource could not be found. public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) } /// Occurs when a conflict with a previous successful write is detected. For example, if a write operation occurs on an object and then an attempt is made to read the object using “SERIALIZABLE” consistency, this exception may result. This generally occurs when the previous write did not have time to propagate to the host serving the current request. A retry (with appropriate backoff logic) is the recommended response to this exception. public static var retryableConflictException: Self { .init(.retryableConflictException) } /// Indicates that a schema could not be created due to a naming conflict. Please select a different name and then try again. public static var schemaAlreadyExistsException: Self { .init(.schemaAlreadyExistsException) } /// Indicates that a schema is already published. public static var schemaAlreadyPublishedException: Self { .init(.schemaAlreadyPublishedException) } /// The object could not be deleted because links still exist. Remove the links and then try the operation again. public static var stillContainsLinksException: Self { .init(.stillContainsLinksException) } /// Indicates that the requested index type is not supported. public static var unsupportedIndexTypeException: Self { .init(.unsupportedIndexTypeException) } /// Indicates that your request is malformed in some manner. See the exception message. public static var validationException: Self { .init(.validationException) } } extension CloudDirectoryErrorType: Equatable { public static func == (lhs: CloudDirectoryErrorType, rhs: CloudDirectoryErrorType) -> Bool { lhs.error == rhs.error } } extension CloudDirectoryErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
2cb337bcdb5de848708876e6c975bead
68.603774
444
0.75305
5.2851
false
false
false
false
SmallElephant/FEAlgorithm-Swift
8-Search/8-Search/SearchMin.swift
1
1421
// // SearchMin.swift // 8-Search // // Created by FlyElephant on 16/12/21. // Copyright © 2016年 FlyElephant. All rights reserved. // import Foundation class SearchMin { //最小的K个数 //题目:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4. func leastMinNumbers(arr:[Int],k:Int) -> [Int] { var data:[Int] = arr var result:[Int] = [] quickSort(arr: &data, low: 0, high: data.count-1) for i in 0..<k { result.append(data[i]) } return result } func quickSort(arr:inout [Int],low:Int,high:Int) { if low > high { return } let middle = partition(arr: &arr, low: low, high: high) quickSort(arr: &arr, low: low, high: middle-1) quickSort(arr: &arr, low: middle+1, high: high) } func partition(arr:inout [Int],low:Int,high:Int) -> Int { let root:Int = arr[high] var index:Int = low for i in low..<high { if arr[i] < root { if i != index { swap(&arr[i], &arr[index]) } index += 1 } } if index != high { swap(&arr[index], &arr[high]) } return index } }
mit
ef05e3c4a6157cbe16f2c9ef8091d87e
22.473684
69
0.46562
3.421995
false
false
false
false
mercadopago/sdk-ios
MercadoPagoSDKExamples/MercadoPagoSDKExamples/FinalVaultViewController.swift
1
5241
// // FinalVaultViewController.swift // MercadoPagoSDK // // Created by Matias Gualino on 4/2/15. // Copyright (c) 2015 com.mercadopago. All rights reserved. // import Foundation import MercadoPagoSDK class FinalVaultViewController : AdvancedVaultViewController { var finalCallback : ((paymentMethod: PaymentMethod, token: String?, issuerId: NSNumber?, installments: Int) -> Void)? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(merchantPublicKey: String, merchantBaseUrl: String, merchantGetCustomerUri: String, merchantAccessToken: String, amount: Double, supportedPaymentTypes: [String], callback: ((paymentMethod: PaymentMethod, token: String?, issuerId: NSNumber?, installments: Int) -> Void)?) { super.init(merchantPublicKey: merchantPublicKey, merchantBaseUrl: merchantBaseUrl, merchantGetCustomerUri: merchantGetCustomerUri, merchantAccessToken: merchantAccessToken, amount: amount, supportedPaymentTypes: supportedPaymentTypes, callback: nil) self.finalCallback = callback } override func getSelectionCallbackPaymentMethod() -> (paymentMethod : PaymentMethod) -> Void { return { (paymentMethod : PaymentMethod) -> Void in self.selectedPaymentMethod = paymentMethod if MercadoPago.isCardPaymentType(paymentMethod.paymentTypeId) { self.selectedCard = nil if paymentMethod.settings != nil && paymentMethod.settings.count > 0 { self.securityCodeLength = paymentMethod.settings![0].securityCode!.length self.securityCodeRequired = self.securityCodeLength != 0 } let newCardViewController = MercadoPago.startNewCardViewController(MercadoPago.PUBLIC_KEY, key: ExamplesUtils.MERCHANT_PUBLIC_KEY, paymentMethod: self.selectedPaymentMethod!, requireSecurityCode: self.securityCodeRequired, callback: self.getNewCardCallback()) if self.selectedPaymentMethod!.isIssuerRequired() { let issuerViewController = MercadoPago.startIssuersViewController(ExamplesUtils.MERCHANT_PUBLIC_KEY, paymentMethod: self.selectedPaymentMethod!, callback: { (issuer: Issuer) -> Void in self.selectedIssuer = issuer self.showViewController(newCardViewController) }) self.showViewController(issuerViewController) } else { self.showViewController(newCardViewController) } } else { self.tableview.reloadData() self.navigationController!.popToViewController(self, animated: true) } } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (self.selectedCard == nil && self.selectedCardToken == nil) || (self.selectedPaymentMethod != nil && !MercadoPago.isCardPaymentType(self.selectedPaymentMethod!.paymentTypeId)) { return 1 } else if self.selectedPayerCost == nil { return 2 } else if !securityCodeRequired { return 2 } return 3 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == 0 { if self.selectedCardToken == nil && self.selectedCard == nil && self.selectedPaymentMethod == nil { self.emptyPaymentMethodCell = self.tableview.dequeueReusableCellWithIdentifier("emptyPaymentMethodCell") as! MPPaymentMethodEmptyTableViewCell return self.emptyPaymentMethodCell } else { self.paymentMethodCell = self.tableview.dequeueReusableCellWithIdentifier("paymentMethodCell") as! MPPaymentMethodTableViewCell if !MercadoPago.isCardPaymentType(self.selectedPaymentMethod!.paymentTypeId) { self.paymentMethodCell.fillWithPaymentMethod(self.selectedPaymentMethod!) } else if self.selectedCardToken != nil { self.paymentMethodCell.fillWithCardTokenAndPaymentMethod(self.selectedCardToken, paymentMethod: self.selectedPaymentMethod!) } else { self.paymentMethodCell.fillWithCard(self.selectedCard) } return self.paymentMethodCell } } else if indexPath.row == 1 { self.installmentsCell = self.tableview.dequeueReusableCellWithIdentifier("installmentsCell") as! MPInstallmentsTableViewCell self.installmentsCell.fillWithPayerCost(self.selectedPayerCost, amount: self.amount) return self.installmentsCell } else if indexPath.row == 2 { self.securityCodeCell = self.tableview.dequeueReusableCellWithIdentifier("securityCodeCell") as! MPSecurityCodeTableViewCell self.securityCodeCell.fillWithPaymentMethod(self.selectedPaymentMethod!) self.securityCodeCell.securityCodeTextField.delegate = self return self.securityCodeCell } return UITableViewCell() } }
mit
24021cefc8644b97d51a2eaa907e0032
54.765957
287
0.671818
5.996568
false
false
false
false
tlax/looper
looper/View/Main/Parent/VParent.swift
1
6413
import UIKit class VParent:UIView { weak var viewBar:VParentBar! private weak var controller:CParent! private weak var layoutBarTop:NSLayoutConstraint! private let kAnimationDuration:TimeInterval = 0.4 private let kBarHeight:CGFloat = 64 convenience init(controller:CParent) { self.init() clipsToBounds = true backgroundColor = UIColor.white self.controller = controller let viewBar:VParentBar = VParentBar(controller:controller) self.viewBar = viewBar addSubview(viewBar) layoutBarTop = NSLayoutConstraint.topToTop( view:viewBar, toView:self) NSLayoutConstraint.equalsHorizontal( view:viewBar, toView:self) NSLayoutConstraint.height( view:viewBar, constant:kBarHeight) } //MARK: public func scrollDidScroll(offsetY:CGFloat) { let barTopConstant:CGFloat if offsetY > 0 { barTopConstant = offsetY } else { barTopConstant = 0 } layoutBarTop.constant = -barTopConstant } func mainView(view:VView) { insertSubview(view, belowSubview:viewBar) view.layoutTop = NSLayoutConstraint.topToTop( view:view, toView:self) view.layoutBottom = NSLayoutConstraint.bottomToBottom( view:view, toView:self) view.layoutLeft = NSLayoutConstraint.leftToLeft( view:view, toView:self) view.layoutRight = NSLayoutConstraint.rightToRight( view:view, toView:self) } func slide( currentView:VView, newView:VView, left:CGFloat, completion:@escaping(() -> ())) { insertSubview(newView, belowSubview:viewBar) newView.layoutTop = NSLayoutConstraint.topToTop( view:newView, toView:self) newView.layoutBottom = NSLayoutConstraint.bottomToBottom( view:newView, toView:self) newView.layoutLeft = NSLayoutConstraint.leftToLeft( view:newView, toView:self, constant:-left) newView.layoutRight = NSLayoutConstraint.rightToRight( view:newView, toView:self, constant:-left) layoutIfNeeded() currentView.layoutRight.constant = left currentView.layoutLeft.constant = left newView.layoutRight.constant = 0 newView.layoutLeft.constant = 0 UIView.animate( withDuration:kAnimationDuration, animations: { self.layoutIfNeeded() }) { (done:Bool) in currentView.removeFromSuperview() completion() } } func push( newView:VView, left:CGFloat, top:CGFloat, completion:@escaping(() -> ())) { addSubview(newView) newView.layoutTop = NSLayoutConstraint.topToTop( view:newView, toView:self, constant:top) newView.layoutBottom = NSLayoutConstraint.bottomToBottom( view:newView, toView:self, constant:top) newView.layoutLeft = NSLayoutConstraint.leftToLeft( view:newView, toView:self, constant:left) newView.layoutRight = NSLayoutConstraint.rightToRight( view:newView, toView:self, constant:left) layoutIfNeeded() if top >= 0 { newView.layoutTop.constant = 0 newView.layoutBottom.constant = 0 } else { newView.layoutBottom.constant = 0 newView.layoutTop.constant = 0 } if left >= 0 { newView.layoutLeft.constant = 0 newView.layoutRight.constant = 0 } else { newView.layoutRight.constant = 0 newView.layoutLeft.constant = 0 } UIView.animate( withDuration:kAnimationDuration, animations: { self.layoutIfNeeded() }) { (done:Bool) in completion() } } func animateOver( newView:VView, completion:@escaping(() -> ())) { newView.alpha = 0 addSubview(newView) newView.layoutTop = NSLayoutConstraint.topToTop( view:newView, toView:self) newView.layoutBottom = NSLayoutConstraint.bottomToBottom( view:newView, toView:self) newView.layoutLeft = NSLayoutConstraint.leftToLeft( view:newView, toView:self) newView.layoutRight = NSLayoutConstraint.rightToRight( view:newView, toView:self) UIView.animate( withDuration:kAnimationDuration, animations: { [weak newView] in newView?.alpha = 1 }) { (done:Bool) in completion() } } func pop( currentView:VView, left:CGFloat, top:CGFloat, completion:@escaping(() -> ())) { currentView.layoutTop.constant = top currentView.layoutBottom.constant = top currentView.layoutRight.constant = left currentView.layoutLeft.constant = left UIView.animate( withDuration:kAnimationDuration, animations: { self.layoutIfNeeded() }) { (done:Bool) in currentView.removeFromSuperview() completion() } } func dismissAnimateOver( currentView:VView, completion:@escaping(() -> ())) { UIView.animate( withDuration:kAnimationDuration, animations: { [weak currentView] in currentView?.alpha = 0 }) { [weak currentView] (done:Bool) in currentView?.removeFromSuperview() completion() } } }
mit
6ab8077d481597d89ca8dbc19a7abf5b
24.858871
66
0.524559
5.845943
false
false
false
false
kesun421/firefox-ios
Client/Frontend/Home/ActivityStreamPanel.swift
1
46406
/* 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 Shared import UIKit import Deferred import Storage import SDWebImage import XCGLogger import SyncTelemetry import SnapKit private let log = Logger.browserLogger private let DefaultSuggestedSitesKey = "topSites.deletedSuggestedSites" // MARK: - Lifecycle struct ASPanelUX { static let backgroundColor = UIConstants.AppBackgroundColor static let rowSpacing: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 30 : 20 static let highlightCellHeight: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 250 : 200 static let sectionInsetsForSizeClass = UXSizeClasses(compact: 0, regular: 101, other: 14) static let numberOfItemsPerRowForSizeClassIpad = UXSizeClasses(compact: 3, regular: 4, other: 2) static let SectionInsetsForIpad: CGFloat = 101 static let SectionInsetsForIphone: CGFloat = 14 static let MinimumInsets: CGFloat = 14 static let BookmarkHighlights = 2 } /* Size classes are the way Apple requires us to specify our UI. Split view on iPad can make a landscape app appear with the demensions of an iPhone app Use UXSizeClasses to specify things like offsets/itemsizes with respect to size classes For a primer on size classes https://useyourloaf.com/blog/size-classes/ */ struct UXSizeClasses { var compact: CGFloat var regular: CGFloat var unspecified: CGFloat init(compact: CGFloat, regular: CGFloat, other: CGFloat) { self.compact = compact self.regular = regular self.unspecified = other } subscript(sizeClass: UIUserInterfaceSizeClass) -> CGFloat { switch sizeClass { case .compact: return self.compact case .regular: return self.regular case .unspecified: return self.unspecified } } } class ActivityStreamPanel: UICollectionViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? fileprivate let profile: Profile fileprivate let telemetry: ActivityStreamTracker fileprivate let pocketAPI = Pocket() fileprivate let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() fileprivate let topSitesManager = ASHorizontalScrollCellManager() fileprivate var showHighlightIntro = false fileprivate var sessionStart: Timestamp? fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(ActivityStreamPanel.longPress(_:))) }() // Not used for displaying. Only used for calculating layout. lazy var topSiteCell: ASHorizontalScrollCell = { let customCell = ASHorizontalScrollCell(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 0)) customCell.delegate = self.topSitesManager return customCell }() var highlights: [Site] = [] var pocketStories: [PocketStory] = [] init(profile: Profile, telemetry: ActivityStreamTracker? = nil) { self.profile = profile self.telemetry = telemetry ?? ActivityStreamTracker(eventsTracker: PingCentre.clientForTopic(.ActivityStreamEvents, clientID: profile.clientID), sessionsTracker: PingCentre.clientForTopic(.ActivityStreamSessions, clientID: profile.clientID)) super.init(collectionViewLayout: flowLayout) self.collectionView?.delegate = self self.collectionView?.dataSource = self collectionView?.addGestureRecognizer(longPressRecognizer) NotificationCenter.default.addObserver(self, selector: #selector(didChangeFontSize(notification:)), name: NotificationDynamicFontChanged, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() Section.allValues.forEach { self.collectionView?.register(Section($0.rawValue).cellType, forCellWithReuseIdentifier: Section($0.rawValue).cellIdentifier) } self.collectionView?.register(ASHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header") self.collectionView?.register(ASFooterView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "Footer") collectionView?.backgroundColor = ASPanelUX.backgroundColor collectionView?.keyboardDismissMode = .onDrag self.profile.panelDataObservers.activityStream.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) sessionStart = Date.now() reloadAll() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) telemetry.reportSessionStop(Date.now() - (sessionStart ?? 0)) sessionStart = nil } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: {context in //The AS context menu does not behave correctly. Dismiss it when rotating. if let _ = self.presentedViewController as? PhotonActionSheet { self.presentedViewController?.dismiss(animated: true, completion: nil) } self.collectionViewLayout.invalidateLayout() self.collectionView?.reloadData() }, completion: nil) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) self.topSitesManager.currentTraits = self.traitCollection } func didChangeFontSize(notification: Notification) { // Don't need to invalidate the data for a font change. Just reload the UI. reloadAll() } } // MARK: - Section management extension ActivityStreamPanel { enum Section: Int { case topSites case pocket case highlights case highlightIntro static let count = 4 static let allValues = [topSites, pocket, highlights, highlightIntro] var title: String? { switch self { case .highlights: return Strings.ASHighlightsTitle case .pocket: return Strings.ASPocketTitle case .topSites: return nil case .highlightIntro: return nil } } var headerHeight: CGSize { switch self { case .highlights, .pocket: return CGSize(width: 50, height: 40) case .topSites: return CGSize(width: 0, height: 0) case .highlightIntro: return CGSize(width: 50, height: 2) } } var footerHeight: CGSize { switch self { case .highlights, .highlightIntro, .pocket: return CGSize.zero case .topSites: return CGSize(width: 50, height: 5) } } func cellHeight(_ traits: UITraitCollection, width: CGFloat) -> CGFloat { switch self { case .highlights, .pocket: return ASPanelUX.highlightCellHeight case .topSites: return 0 //calculated dynamically case .highlightIntro: return 200 } } /* There are edge cases to handle when calculating section insets - An iPhone 7+ is considered regular width when in landscape - An iPad in 66% split view is still considered regular width */ func sectionInsets(_ traits: UITraitCollection, frameWidth: CGFloat) -> CGFloat { var currentTraits = traits if (traits.horizontalSizeClass == .regular && UIScreen.main.bounds.size.width != frameWidth) || UIDevice.current.userInterfaceIdiom == .phone { currentTraits = UITraitCollection(horizontalSizeClass: .compact) } switch self { case .highlights, .pocket: var insets = ASPanelUX.sectionInsetsForSizeClass[currentTraits.horizontalSizeClass] insets = insets + ASPanelUX.MinimumInsets return insets case .topSites: return ASPanelUX.sectionInsetsForSizeClass[currentTraits.horizontalSizeClass] case .highlightIntro: return ASPanelUX.sectionInsetsForSizeClass[currentTraits.horizontalSizeClass] } } func numberOfItemsForRow(_ traits: UITraitCollection) -> CGFloat { switch self { case .highlights, .pocket: var numItems: CGFloat = ASPanelUX.numberOfItemsPerRowForSizeClassIpad[traits.horizontalSizeClass] if UIInterfaceOrientationIsPortrait(UIApplication.shared.statusBarOrientation) { numItems = numItems - 1 } if traits.horizontalSizeClass == .compact && UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) { numItems = numItems - 1 } return numItems case .topSites, .highlightIntro: return 1 } } func cellSize(for traits: UITraitCollection, frameWidth: CGFloat) -> CGSize { let height = cellHeight(traits, width: frameWidth) let inset = sectionInsets(traits, frameWidth: frameWidth) * 2 switch self { case .highlights, .pocket: let numItems = numberOfItemsForRow(traits) return CGSize(width: floor(((frameWidth - inset) - (ASPanelUX.MinimumInsets * (numItems - 1))) / numItems), height: height) case .topSites: return CGSize(width: frameWidth - inset, height: height) case .highlightIntro: return CGSize(width: frameWidth - inset - (ASPanelUX.MinimumInsets * 2), height: height) } } var headerView: UIView? { switch self { case .highlights, .highlightIntro, .pocket: let view = ASHeaderView() view.title = title return view case .topSites: return nil } } var cellIdentifier: String { switch self { case .topSites: return "TopSiteCell" case .highlights: return "HistoryCell" case .pocket: return "PocketCell" case .highlightIntro: return "HighlightIntroCell" } } var cellType: UICollectionViewCell.Type { switch self { case .topSites: return ASHorizontalScrollCell.self case .highlights, .pocket: return ActivityStreamHighlightCell.self case .highlightIntro: return HighlightIntroCell.self } } init(at indexPath: IndexPath) { self.init(rawValue: indexPath.section)! } init(_ section: Int) { self.init(rawValue: section)! } } } // MARK: - Tableview Delegate extension ActivityStreamPanel: UICollectionViewDelegateFlowLayout { override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case UICollectionElementKindSectionHeader: let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header", for: indexPath) as! ASHeaderView let title = Section(indexPath.section).title switch Section(indexPath.section) { case .highlights, .highlightIntro: view.title = title return view case .pocket: view.title = title view.moreButton.isHidden = false view.moreButton.addTarget(self, action: #selector(ActivityStreamPanel.showMorePocketStories), for: .touchUpInside) return view case .topSites: return UICollectionReusableView() } case UICollectionElementKindSectionFooter: let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "Footer", for: indexPath) as! ASFooterView switch Section(indexPath.section) { case .highlights, .highlightIntro: return UICollectionReusableView() case .topSites, .pocket: return view } default: return UICollectionReusableView() } } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.longPressRecognizer.isEnabled = false selectItemAtIndex(indexPath.item, inSection: Section(indexPath.section)) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let cellSize = Section(indexPath.section).cellSize(for: self.traitCollection, frameWidth: self.view.frame.width) switch Section(indexPath.section) { case .highlights: if highlights.isEmpty { return CGSize.zero } return cellSize case .topSites: // Create a temporary cell so we can calculate the height. let layout = topSiteCell.collectionView.collectionViewLayout as! HorizontalFlowLayout let estimatedLayout = layout.calculateLayout(for: CGSize(width: cellSize.width, height: 0)) return CGSize(width: cellSize.width, height: estimatedLayout.size.height) case .highlightIntro, .pocket: return cellSize } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { switch Section(section) { case .highlights: return highlights.isEmpty ? CGSize.zero : CGSize(width: self.view.frame.size.width, height: Section(section).headerHeight.height) case .highlightIntro: return !highlights.isEmpty ? CGSize.zero : CGSize(width: self.view.frame.size.width, height: Section(section).headerHeight.height) case .pocket: return pocketStories.isEmpty ? CGSize.zero : Section(section).headerHeight case .topSites: return Section(section).headerHeight } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { switch Section(section) { case .highlights, .highlightIntro, .pocket: return CGSize.zero case .topSites: return Section(section).footerHeight } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return ASPanelUX.rowSpacing } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { let insets = Section(section).sectionInsets(self.traitCollection, frameWidth: self.view.frame.width) return UIEdgeInsets(top: 0, left: insets, bottom: 0, right: insets) } fileprivate func showSiteWithURLHandler(_ url: URL) { let visitType = VisitType.bookmark homePanelDelegate?.homePanel(self, didSelectURL: url, visitType: visitType) } } // MARK: - Tableview Data Source extension ActivityStreamPanel { override func numberOfSections(in collectionView: UICollectionView) -> Int { return 4 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { var numItems: CGFloat = ASPanelUX.numberOfItemsPerRowForSizeClassIpad[self.traitCollection.horizontalSizeClass] if UIInterfaceOrientationIsPortrait(UIApplication.shared.statusBarOrientation) { numItems = numItems - 1 } if self.traitCollection.horizontalSizeClass == .compact && UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) { numItems = numItems - 1 } switch Section(section) { case .topSites: return topSitesManager.content.isEmpty ? 0 : 1 case .highlights: return self.highlights.count case .pocket: return pocketStories.isEmpty ? 0 : Int(numItems) case .highlightIntro: return self.highlights.isEmpty && showHighlightIntro && isHighlightsEnabled() ? 1 : 0 } } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let identifier = Section(indexPath.section).cellIdentifier let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) switch Section(indexPath.section) { case .topSites: return configureTopSitesCell(cell, forIndexPath: indexPath) case .highlights: return configureHistoryItemCell(cell, forIndexPath: indexPath) case .pocket: return configurePocketItemCell(cell, forIndexPath: indexPath) case .highlightIntro: return configureHighlightIntroCell(cell, forIndexPath: indexPath) } } //should all be collectionview func configureTopSitesCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell { let topSiteCell = cell as! ASHorizontalScrollCell topSiteCell.delegate = self.topSitesManager topSiteCell.setNeedsLayout() topSiteCell.collectionView.reloadData() return cell } func configureHistoryItemCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell { let site = highlights[indexPath.row] let simpleHighlightCell = cell as! ActivityStreamHighlightCell simpleHighlightCell.configureWithSite(site) return simpleHighlightCell } func configurePocketItemCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell { let pocketStory = pocketStories[indexPath.row] let pocketItemCell = cell as! ActivityStreamHighlightCell pocketItemCell.configureWithPocketStory(pocketStory) return pocketItemCell } func configureHighlightIntroCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell { let introCell = cell as! HighlightIntroCell //The cell is configured on creation. No need to configure. But leave this here in case we need it. return introCell } } // MARK: - Data Management extension ActivityStreamPanel: DataObserverDelegate { fileprivate func reportMissingData(sites: [Site], source: ASPingSource) { let missingImagePings: [[String: Any]] = sites.flatMap { site in if site.metadata?.mediaURL == nil { return self.telemetry.pingFor(badState: .MissingMetadataImage, source: source) } return nil } let missingFaviconPings: [[String: Any]] = sites.flatMap { site in if site.icon == nil { return self.telemetry.pingFor(badState: .MissingFavicon, source: source) } return nil } let badPings = missingImagePings + missingFaviconPings self.telemetry.eventsTracker.sendBatch(badPings, validate: true) } // Reloads both highlights and top sites data from their respective caches. Does not invalidate the cache. // See ActivityStreamDataObserver for invalidation logic. func reloadAll() { // If the pocket stories are not availible for the Locale the PocketAPI will return nil // So it is okay if the default here is true self.getPocketSites().uponQueue(.main) { _ in if !self.pocketStories.isEmpty { self.collectionView?.reloadData() } } accumulate([self.getHighlights, self.getTopSites]).uponQueue(.main) { _ in // If there is no pending cache update and highlights are empty. Show the onboarding screen self.showHighlightIntro = self.highlights.isEmpty self.collectionView?.reloadData() // Refresh the AS data in the background so we'll have fresh data next time we show. self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceHighlights: false, forceTopSites: false) } } func getBookmarksForHighlights() -> Deferred<Maybe<Cursor<Site>>> { let count = ASPanelUX.BookmarkHighlights // Fetch 2 bookmarks return self.profile.recommendations.getRecentBookmarks(count) } // Used to check if the entire section is turned off // when it is we shouldnt show the emtpy state func isHighlightsEnabled() -> Bool { let bookmarks = profile.prefs.boolForKey(PrefsKeys.ASBookmarkHighlightsVisible) ?? false let history = profile.prefs.boolForKey(PrefsKeys.ASRecentHighlightsVisible) ?? false return history && bookmarks } func getHighlights() -> Success { var queries: [() -> Deferred<Maybe<Cursor<Site>>>] = [] if profile.prefs.boolForKey(PrefsKeys.ASBookmarkHighlightsVisible) ?? true { queries.append(getBookmarksForHighlights) } if profile.prefs.boolForKey(PrefsKeys.ASRecentHighlightsVisible) ?? true { queries.append(self.profile.recommendations.getHighlights) } guard !queries.isEmpty else { self.highlights = [] return succeed() } return accumulate(queries).bindQueue(.main) { result in guard let resultArr = result.successValue else { return succeed() } let sites = resultArr.reduce([]) { $0 + $1.asArray() } // Scan through the fetched highlights and report on anything that might be missing. self.reportMissingData(sites: sites, source: .Highlights) self.highlights = sites return succeed() } } func getPocketSites() -> Success { let showPocket = (profile.prefs.boolForKey(PrefsKeys.ASPocketStoriesVisible) ?? Pocket.IslocaleSupported(Locale.current.identifier)) && AppConstants.MOZ_POCKET_STORIES guard showPocket else { self.pocketStories = [] return succeed() } return pocketAPI.globalFeed(items: 4).bindQueue(.main) { pStory in self.pocketStories = pStory return succeed() } } @objc func showMorePocketStories() { showSiteWithURLHandler(Pocket.MoreStoriesURL) } func getTopSites() -> Success { return self.profile.history.getTopSitesWithLimit(16).both(self.profile.history.getPinnedTopSites()).bindQueue(.main) { (topsites, pinnedSites) in guard let mySites = topsites.successValue?.asArray(), let pinned = pinnedSites.successValue?.asArray() else { return succeed() } // How sites are merged together. We compare against the urls second level domain. example m.youtube.com is compared against `youtube` let unionOnURL = { (site: Site) -> String in return URL(string: site.url)?.hostSLD ?? "" } // Fetch the default sites let defaultSites = self.defaultTopSites() // create PinnedSite objects. used by the view layer to tell topsites apart let pinnedSites: [Site] = pinned.map({ PinnedSite(site: $0) }) // Merge default topsites with a user's topsites. let mergedSites = mySites.union(defaultSites, f: unionOnURL) // Merge pinnedSites with sites from the previous step let allSites = pinnedSites.union(mergedSites, f: unionOnURL) // Favour topsites from defaultSites as they have better favicons. But keep PinnedSites let newSites = allSites.map { site -> Site in if let _ = site as? PinnedSite { return site } let domain = URL(string: site.url)?.hostSLD return defaultSites.find { $0.title.lowercased() == domain } ?? site } // Don't report bad states for default sites we provide self.reportMissingData(sites: mySites, source: .TopSites) self.topSitesManager.currentTraits = self.view.traitCollection if newSites.count > Int(ActivityStreamTopSiteCacheSize) { self.topSitesManager.content = Array(newSites[0..<Int(ActivityStreamTopSiteCacheSize)]) } else { self.topSitesManager.content = newSites } self.topSitesManager.urlPressedHandler = { [unowned self] url, indexPath in self.longPressRecognizer.isEnabled = false self.telemetry.reportEvent(.Click, source: .TopSites, position: indexPath.item) self.showSiteWithURLHandler(url as URL) } return succeed() } } // Invoked by the ActivityStreamDataObserver when highlights/top sites invalidation is complete. func didInvalidateDataSources(refresh forced: Bool, highlightsRefreshed: Bool, topSitesRefreshed: Bool) { // Do not reload panel unless we're currently showing the highlight intro or if we // force-reloaded the highlights or top sites. This should prevent reloading the // panel after we've invalidated in the background on the first load. if showHighlightIntro || forced { reloadAll() } } func hideURLFromTopSites(_ site: Site) { guard let host = site.tileURL.normalizedHost else { return } let url = site.tileURL.absoluteString // if the default top sites contains the siteurl. also wipe it from default suggested sites. if defaultTopSites().filter({$0.url == url}).isEmpty == false { deleteTileForSuggestedSite(url) } profile.history.removeHostFromTopSites(host).uponQueue(.main) { result in guard result.isSuccess else { return } self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceHighlights: false, forceTopSites: true) } } func pinTopSite(_ site: Site) { profile.history.addPinnedTopSite(site).uponQueue(.main) { result in guard result.isSuccess else { return } self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceHighlights: false, forceTopSites: true) } } func removePinTopSite(_ site: Site) { profile.history.removeFromPinnedTopSites(site).uponQueue(.main) { result in guard result.isSuccess else { return } self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceHighlights: false, forceTopSites: true) } } func hideFromHighlights(_ site: Site) { profile.recommendations.removeHighlightForURL(site.url).uponQueue(.main) { result in guard result.isSuccess else { return } self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceHighlights: true, forceTopSites: false) } } fileprivate func deleteTileForSuggestedSite(_ siteURL: String) { var deletedSuggestedSites = profile.prefs.arrayForKey(DefaultSuggestedSitesKey) as? [String] ?? [] deletedSuggestedSites.append(siteURL) profile.prefs.setObject(deletedSuggestedSites, forKey: DefaultSuggestedSitesKey) } func defaultTopSites() -> [Site] { let suggested = SuggestedSites.asArray() let deleted = profile.prefs.arrayForKey(DefaultSuggestedSitesKey) as? [String] ?? [] return suggested.filter({deleted.index(of: $0.url) == .none}) } @objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == UIGestureRecognizerState.began else { return } let point = longPressGestureRecognizer.location(in: self.collectionView) guard let indexPath = self.collectionView?.indexPathForItem(at: point) else { return } switch Section(indexPath.section) { case .highlights, .pocket: presentContextMenu(for: indexPath) case .topSites: let topSiteCell = self.collectionView?.cellForItem(at: indexPath) as! ASHorizontalScrollCell let pointInTopSite = longPressGestureRecognizer.location(in: topSiteCell.collectionView) guard let topSiteIndexPath = topSiteCell.collectionView.indexPathForItem(at: pointInTopSite) else { return } presentContextMenu(for: topSiteIndexPath) case .highlightIntro: break } } fileprivate func fetchBookmarkStatus(for site: Site, with indexPath: IndexPath, forSection section: Section, completionHandler: @escaping () -> Void) { profile.bookmarks.modelFactory >>== { $0.isBookmarked(site.url).uponQueue(.main) { result in guard let isBookmarked = result.successValue else { log.error("Error getting bookmark status: \(result.failureValue ??? "nil").") return } site.setBookmarked(isBookmarked) completionHandler() } } } func selectItemAtIndex(_ index: Int, inSection section: Section) { let site: Site? switch section { case .highlights: site = self.highlights[index] telemetry.reportEvent(.Click, source: .Highlights, position: index) case .pocket: site = Site(url: pocketStories[index].url.absoluteString, title: pocketStories[index].title) telemetry.reportEvent(.Click, source: .Pocket, position: index) LeanplumIntegration.sharedInstance.track(eventName: .openedPocketStory, withParameters: ["Source": "Activity Stream" as AnyObject]) case .topSites, .highlightIntro: return } if let site = site { showSiteWithURLHandler(URL(string: site.url)!) } } } extension ActivityStreamPanel: HomePanelContextMenu { func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) { fetchBookmarkStatus(for: site, with: indexPath, forSection: Section(indexPath.section)) { guard let contextMenu = completionHandler() else { return } self.present(contextMenu, animated: true, completion: nil) } } func getSiteDetails(for indexPath: IndexPath) -> Site? { let site: Site switch Section(indexPath.section) { case .highlights: site = highlights[indexPath.row] case .pocket: site = Site(url: pocketStories[indexPath.row].dedupeURL.absoluteString, title: pocketStories[indexPath.row].title) case .topSites: site = topSitesManager.content[indexPath.item] case .highlightIntro: return nil } return site } func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? { guard let siteURL = URL(string: site.url) else { return nil } let pingSource: ASPingSource let index: Int var sourceView: UIView? switch Section(indexPath.section) { case .topSites: pingSource = .TopSites index = indexPath.item if let topSiteCell = self.collectionView?.cellForItem(at: IndexPath(row: 0, section: 0)) as? ASHorizontalScrollCell { sourceView = topSiteCell.collectionView.cellForItem(at: indexPath) } case .highlights: pingSource = .Highlights index = indexPath.row sourceView = self.collectionView?.cellForItem(at: indexPath) case .pocket: pingSource = .Pocket index = indexPath.item sourceView = self.collectionView?.cellForItem(at: indexPath) case .highlightIntro: return nil } let openInNewTabAction = PhotonActionSheetItem(title: Strings.OpenInNewTabContextMenuTitle, iconString: "quick_action_new_tab") { action in self.homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: false) self.telemetry.reportEvent(.NewTab, source: pingSource, position: index) let source = ["Source": "Activity Stream Long Press Context Menu" as AnyObject] LeanplumIntegration.sharedInstance.track(eventName: .openedNewTab, withParameters: source) if Section(indexPath.section) == .pocket { LeanplumIntegration.sharedInstance.track(eventName: .openedPocketStory, withParameters: source) } } let openInNewPrivateTabAction = PhotonActionSheetItem(title: Strings.OpenInNewPrivateTabContextMenuTitle, iconString: "quick_action_new_private_tab") { action in self.homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: true) } let bookmarkAction: PhotonActionSheetItem if site.bookmarked ?? false { bookmarkAction = PhotonActionSheetItem(title: Strings.RemoveBookmarkContextMenuTitle, iconString: "action_bookmark_remove", handler: { action in self.profile.bookmarks.modelFactory >>== { $0.removeByURL(siteURL.absoluteString).uponQueue(.main) {_ in self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceHighlights: true, forceTopSites: false) } site.setBookmarked(false) } self.telemetry.reportEvent(.RemoveBookmark, source: pingSource, position: index) }) } else { bookmarkAction = PhotonActionSheetItem(title: Strings.BookmarkContextMenuTitle, iconString: "action_bookmark", handler: { action in let shareItem = ShareItem(url: site.url, title: site.title, favicon: site.icon) _ = self.profile.bookmarks.shareItem(shareItem) var userData = [QuickActions.TabURLKey: shareItem.url] if let title = shareItem.title { userData[QuickActions.TabTitleKey] = title } QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark, withUserData: userData, toApplication: UIApplication.shared) site.setBookmarked(true) self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceHighlights: true, forceTopSites: true) self.telemetry.reportEvent(.AddBookmark, source: pingSource, position: index) LeanplumIntegration.sharedInstance.track(eventName: .savedBookmark) }) } let deleteFromHistoryAction = PhotonActionSheetItem(title: Strings.DeleteFromHistoryContextMenuTitle, iconString: "action_delete", handler: { action in self.telemetry.reportEvent(.Delete, source: pingSource, position: index) self.profile.history.removeHistoryForURL(site.url).uponQueue(.main) { result in guard result.isSuccess else { return } self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceHighlights: true, forceTopSites: true) } }) let shareAction = PhotonActionSheetItem(title: Strings.ShareContextMenuTitle, iconString: "action_share", handler: { action in let helper = ShareExtensionHelper(url: siteURL, tab: nil) let controller = helper.createActivityViewController { completed, activityType in self.telemetry.reportEvent(.Share, source: pingSource, position: index, shareProvider: activityType) } if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad, let popoverController = controller.popoverPresentationController { let cellRect = sourceView?.frame ?? CGRect.zero let cellFrameInSuperview = self.collectionView?.convert(cellRect, to: self.collectionView) ?? CGRect.zero popoverController.sourceView = sourceView popoverController.sourceRect = CGRect(origin: CGPoint(x: cellFrameInSuperview.size.width/2, y: cellFrameInSuperview.height/2), size: .zero) popoverController.permittedArrowDirections = [.up, .down, .left] popoverController.delegate = self } self.present(controller, animated: true, completion: nil) }) let removeTopSiteAction = PhotonActionSheetItem(title: Strings.RemoveContextMenuTitle, iconString: "action_remove", handler: { action in self.telemetry.reportEvent(.Remove, source: pingSource, position: index) self.hideURLFromTopSites(site) }) let dismissHighlightAction = PhotonActionSheetItem(title: Strings.RemoveContextMenuTitle, iconString: "action_remove", handler: { action in self.telemetry.reportEvent(.Dismiss, source: pingSource, position: index) self.hideFromHighlights(site) }) let pinTopSite = PhotonActionSheetItem(title: Strings.PinTopsiteActionTitle, iconString: "action_pin", handler: { action in self.pinTopSite(site) }) let removePinTopSite = PhotonActionSheetItem(title: Strings.RemovePinTopsiteActionTitle, iconString: "action_unpin", handler: { action in self.removePinTopSite(site) }) let topSiteActions: [PhotonActionSheetItem] if let _ = site as? PinnedSite { topSiteActions = [removePinTopSite] } else { topSiteActions = [pinTopSite, removeTopSiteAction] } var actions = [openInNewTabAction, openInNewPrivateTabAction, bookmarkAction, shareAction] switch Section(indexPath.section) { case .highlights: actions.append(contentsOf: [dismissHighlightAction, deleteFromHistoryAction]) case .pocket: break case .topSites: actions.append(contentsOf: topSiteActions) case .highlightIntro: break } return actions } } extension ActivityStreamPanel: UIPopoverPresentationControllerDelegate { // Dismiss the popover if the device is being rotated. // This is used by the Share UIActivityViewController action sheet on iPad func popoverPresentationController(_ popoverPresentationController: UIPopoverPresentationController, willRepositionPopoverTo rect: UnsafeMutablePointer<CGRect>, in view: AutoreleasingUnsafeMutablePointer<UIView>) { popoverPresentationController.presentedViewController.dismiss(animated: false, completion: nil) } } // MARK: Telemetry enum ASPingEvent: String { case Click = "CLICK" case Delete = "DELETE" case Dismiss = "DISMISS" case Share = "SHARE" case NewTab = "NEW_TAB" case AddBookmark = "ADD_BOOKMARK" case RemoveBookmark = "REMOVE_BOOKMARK" case Remove = "REMOVE" } enum ASPingBadStateEvent: String { case MissingMetadataImage = "MISSING_METADATA_IMAGE" case MissingFavicon = "MISSING_FAVICON" } enum ASPingSource: String { case Highlights = "HIGHLIGHTS" case TopSites = "TOP_SITES" case HighlightsIntro = "HIGHLIGHTS_INTRO" case Pocket = "POCKET" } struct ActivityStreamTracker { let eventsTracker: PingCentreClient let sessionsTracker: PingCentreClient private var baseASPing: [String: Any] { return [ "app_version": AppInfo.appVersion, "build": AppInfo.buildNumber, "locale": Locale.current.identifier, "release_channel": AppConstants.BuildChannel.rawValue ] } func pingFor(badState: ASPingBadStateEvent, source: ASPingSource) -> [String: Any] { var eventPing: [String: Any] = [ "event": badState.rawValue, "page": "NEW_TAB", "source": source.rawValue, ] eventPing.merge(with: baseASPing) return eventPing } func reportEvent(_ event: ASPingEvent, source: ASPingSource, position: Int, shareProvider: String? = nil) { var eventPing: [String: Any] = [ "event": event.rawValue, "page": "NEW_TAB", "source": source.rawValue, "action_position": position, ] if let provider = shareProvider { eventPing["share_provider"] = provider } eventPing.merge(with: baseASPing) eventsTracker.sendPing(eventPing as [String : AnyObject], validate: true) } func reportSessionStop(_ duration: UInt64) { sessionsTracker.sendPing([ "session_duration": NSNumber(value: duration), "app_version": AppInfo.appVersion, "build": AppInfo.buildNumber, "locale": Locale.current.identifier, "release_channel": AppConstants.BuildChannel.rawValue ] as [String: Any], validate: true) } } // MARK: - Section Header View struct ASHeaderViewUX { static let SeperatorColor = UIColor(rgb: 0xedecea) static let TextFont = DynamicFontHelper.defaultHelper.MediumSizeBoldFontAS static let SeperatorHeight = 1 static let Insets: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? ASPanelUX.SectionInsetsForIpad + ASPanelUX.MinimumInsets : ASPanelUX.MinimumInsets static let TitleTopInset: CGFloat = 5 } class ASFooterView: UICollectionReusableView { override init(frame: CGRect) { super.init(frame: frame) let seperatorLine = UIView() seperatorLine.backgroundColor = ASHeaderViewUX.SeperatorColor self.backgroundColor = UIColor.clear addSubview(seperatorLine) seperatorLine.snp.makeConstraints { make in make.height.equalTo(ASHeaderViewUX.SeperatorHeight) make.leading.equalTo(self.snp.leading) make.trailing.equalTo(self.snp.trailing) make.top.equalTo(self.snp.top) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class ASHeaderView: UICollectionReusableView { lazy fileprivate var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.text = self.title titleLabel.textColor = UIColor.gray titleLabel.font = ASHeaderViewUX.TextFont titleLabel.minimumScaleFactor = 0.6 titleLabel.numberOfLines = 1 titleLabel.adjustsFontSizeToFitWidth = true return titleLabel }() lazy var moreButton: UIButton = { let button = UIButton() button.setTitle("More", for: .normal) button.isHidden = true button.titleLabel?.font = ASHeaderViewUX.TextFont button.contentHorizontalAlignment = .right button.setTitleColor(UIConstants.SystemBlueColor, for: .normal) button.setTitleColor(.gray, for: UIControlState.highlighted) return button }() var title: String? { willSet(newTitle) { titleLabel.text = newTitle } } var leftConstraint: Constraint? var rightConstraint: Constraint? var titleInsets: CGFloat { get { return UIScreen.main.bounds.size.width == self.frame.size.width && UIDevice.current.userInterfaceIdiom == .pad ? ASHeaderViewUX.Insets : ASPanelUX.MinimumInsets } } override func prepareForReuse() { super.prepareForReuse() moreButton.isHidden = true moreButton.removeTarget(nil, action: nil, for: .allEvents) } override init(frame: CGRect) { super.init(frame: frame) addSubview(titleLabel) addSubview(moreButton) moreButton.snp.makeConstraints { make in make.top.equalTo(self).inset(ASHeaderViewUX.TitleTopInset) make.bottom.equalTo(self) self.rightConstraint = make.trailing.equalTo(self).inset(-titleInsets).constraint } moreButton.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: UILayoutConstraintAxis.horizontal) titleLabel.snp.makeConstraints { make in self.leftConstraint = make.leading.equalTo(self).inset(titleInsets).constraint make.trailing.equalTo(moreButton.snp.leading).inset(-ASHeaderViewUX.TitleTopInset) make.top.equalTo(self).inset(ASHeaderViewUX.TitleTopInset) make.bottom.equalTo(self) } } override func layoutSubviews() { super.layoutSubviews() leftConstraint?.update(offset: titleInsets) rightConstraint?.update(offset: -titleInsets) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } open class PinnedSite: Site { let isPinnedSite = true init(site: Site) { super.init(url: site.url, title: site.title, bookmarked: site.bookmarked) self.icon = site.icon self.metadata = site.metadata } }
mpl-2.0
b550eaccc40277b7b7bf297c334131f8
42.329599
249
0.657049
5.241247
false
false
false
false
apple/swift-llbuild
lib/Analysis/IdentifierFactory.swift
1
1973
// This source file is part of the Swift.org open source project // // Copyright 2019 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 Swift project authors /// IdentifierFactory creates unique identifiers for given elements. /// It provides an API to map between identifiers and elements and can be used /// for fast lookups. public final class IdentifierFactory<T: Hashable> { public typealias Identifier = Array<T>.Index public let elements: [T] private var identifiers: [T: Identifier] /// Initializes a new factory using a collection of elements. /// - Parameter elements: Contains all elements which will become valid input for calling `identifier(element:)`. public init<C>(_ elements: C) where C: Collection, C.Element == T { self.elements = Array(elements) var identifierLookup = [T: Identifier](minimumCapacity: self.elements.count) for (index, element) in elements.enumerated() { identifierLookup[element] = index } self.identifiers = identifierLookup } public var count: Int { return elements.count } /// Returns the element for a provided identifier. /// - Parameter id: An identifier created using `identifier(element:)` public func element(id: Identifier) -> T { return elements[id] } /// Returns a unique identifier for a given element. /// - Parameter element: The element must have been part of the collection used in the initialization. public func identifier(element: T) -> Identifier { guard let identifier = self.identifiers[element] else { preconditionFailure("Could not get identifier for \(element) because it was not initially added to the IdentifierFactory.") } return identifier } }
apache-2.0
4c9f39a06a625e660096ebd290c28506
41.891304
135
0.691333
4.823961
false
false
false
false