repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
railsdog/CleanroomLogger
Code/LogSeverity.swift
3
2732
// // LogSeverity.swift // Cleanroom Project // // Created by Evan Maloney on 3/18/15. // Copyright (c) 2015 Gilt Groupe. All rights reserved. // /** Used to indicate the *severity*, or importance, of a log message. Severity is a continuum, from `.Verbose` being least severe to `.Error` being most severe. The logging system may be configured so that messages lower than a given severity are ignored. */ public enum LogSeverity: Int { /** The lowest severity, used for detailed or frequently occurring debugging and diagnostic information. Not intended for use in production code. */ case Verbose = 1 /** Used for debugging and diagnostic information. Not intended for use in production code. */ case Debug = 2 /** Used to indicate something of interest that is not problematic. */ case Info = 3 /** Used to indicate that something appears amiss and potentially problematic. The situation bears looking into before a larger problem arises. */ case Warning = 4 /** The highest severity, used to indicate that something has gone wrong; a fatal error may be imminent. */ case Error = 5 /** A convenience function to determine the minimum `LogSeverity` value to use by default, based on whether or not the application was compiled with debugging turned on. :param: minimumForDebugMode The `LogSeverity` value to return when `isInDebugMode` is `true`. :param: isInDebugMode Defaults to `false`. Pass the value `(DEBUG != 0)` to ensure the correct value for your build. */ public static func defaultMinimumSeverity(minimumForDebugMode: LogSeverity = .Debug, isInDebugMode: Bool = false) -> LogSeverity { if isInDebugMode { return minimumForDebugMode } else { return .Info } } } /// :nodoc: extension LogSeverity: Comparable {} /// :nodoc: public func <(lhs: LogSeverity, rhs: LogSeverity) -> Bool { return lhs.rawValue < rhs.rawValue } /// :nodoc: extension LogSeverity // DebugPrintableEnum { // /// :nodoc: // public var description: String { return EnumPrinter.description(self) } // // /// :nodoc: // public var debugDescription: String { return EnumPrinter.debugDescription(self) } /// :nodoc: public var printableEnumName: String { return "LogSeverity" } /// :nodoc: public var printableValueName: String { switch self { case Verbose: return "Verbose" case Debug: return "Debug" case Info: return "Info" case Warning: return "Warning" case Error: return "Error" } } }
mit
7aea1d45a435d5fb7040732924048654
28.06383
117
0.648243
4.478689
false
false
false
false
sessionm/ios-smp-example
Rewards/OffersTableViewController.swift
1
3119
// // OffersTableViewController.swift // SMPExample // // Copyright © 2018 SessionM. All rights reserved. // import SessionMRewardsKit import UIKit class OfferCell: UITableViewCell { @IBOutlet var details: UILabel! @IBOutlet var header: UILabel! @IBOutlet var offerImage: UIImageView! @IBOutlet var imageWidth: NSLayoutConstraint! @IBOutlet var points: UILabel! } class OffersTableViewController: UITableViewController { private var rewardsManager = SMRewardsManager.instance() private var offers: [SMOffer] = [] @IBAction private func onRefresh(_ sender: UIRefreshControl) { fetchOffers() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) fetchOffers() } private func fetchOffers() { self.refreshControl?.beginRefreshing() rewardsManager.fetchOffers(completionHandler: { (offers: [SMOffer]?, error: SMError?) in if let err = error { Util.failed(self, message: err.message) } else if let newOffers = offers { self.offers = newOffers self.tableView.reloadData() } self.refreshControl?.endRefreshing() }) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return offers.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let offer = offers[indexPath.row] if offer.logoURL != nil { return 240.0 } else { return 96.0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let offer = offers[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "OfferCell", for: indexPath) as? OfferCell if let c = cell { c.details.text = offer.details c.header.text = offer.type c.points.text = "\(offer.points) pts" c.tag = indexPath.row if let img = offer.logoURL { Util.loadFrom(img, callback: { (image) in c.offerImage.image = image c.imageWidth.constant = min(c.bounds.size.width, ((c.offerImage.frame.size.height / image.size.height) * image.size.width)) }) } } return cell! } @IBAction private func logout(_ sender: AnyObject) { if let provider = SessionM.authenticationProvider() as? SessionMOAuthProvider { provider.logOutUser { (authState, error) in LoginViewController.loginIfNeeded(self.tabBarController!) } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let placeOrder = segue.destination as! PlaceOrderViewController let cell = sender as! OfferCell placeOrder.offer = offers[cell.tag] } }
mit
0fd4e3cb775c54c0e7105cf5947bc357
31.479167
143
0.623156
4.782209
false
false
false
false
kysonyangs/ysbilibili
ysbilibili/Classes/Home/Recommend/ViewModel/YSRecommendURLHelper.swift
1
1616
// // YSRecommendURLHelper.swift // ysbilibili // // Created by MOLBASE on 2017/8/7. // Copyright © 2017年 YangShen. All rights reserved. // import UIKit class YSRecommendURLHelper: NSObject { class func createSectionReloadURLStr(type: HomeStatustype, tid:Int) -> String { // 我也不想这么猥琐啊,没办法这些接口都加密过的只能用这种猥琐方法了 😭😭 // 并且这些接口还是稍微有点问题的,不能像bilibili那样无限拿到新数据,这个接口基本一段时间内拿到的数据都是一样的,你点击刷新的时候感觉没刷其实是刷了的只是数据都是一样的 // 番剧和活动没有刷新的功能 // 1.热门推荐 if type == .recommend { return "http://app.bilibili.com/x/v2/show/change?actionKey=appkey&appkey=27eb53fc9058f8c3&build=3970&channel=appstore&device=phone&mobi_app=iphone&plat=1&platform=ios&rand=1&sign=a0e33e296110ce58cbb555699d9a1e52&ts=1480054195" } // 2.推荐直播 if type == .live { return "http://app.bilibili.com/x/show/live?actionKey=appkey&appkey=27eb53fc9058f8c3&build=3970&channel=appstore&device=phone&mobi_app=iphone&plat=1&platform=ios&rand=0&sign=291a3e19abc4f90f4064b0cf0e8f698d&ts=1480054280" } // 3. 其他的普通情况 return "http://www.bilibili.com/index/ding/23.json?actionKey=appkey&appkey=27eb53fc9058f8c3&build=3970&device=phone&mobi_app=iphone&pagesize=20&platform=ios&sign=a5c8fc83d48a1f60a0f69bd3b8d77b5d&tid=\(tid)&ts=1480054781" } }
mit
402bd652f0d12220c9126a1261b7d184
40.71875
238
0.701873
2.538023
false
false
false
false
RomeRock/ios-colortheme
SchemaColor/SchemaColor/CustomExtentions.swift
1
2786
// // CustomExtentions.swift // SchemaColor // // Created by Rome Rock on 2/22/17. // Copyright © 2017 Rome Rock. All rights reserved. // import Foundation import UIKit 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:String) { var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if (cString.hasPrefix("#")) { cString.remove(at: cString.startIndex) } var rgbValue:UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) self.init( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } convenience init(hex:String, alpha:CGFloat) { var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if (cString.hasPrefix("#")) { cString.remove(at: cString.startIndex) } var rgbValue:UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) self.init( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: alpha ) } } extension UIView { func makeCircular() { self.layer.cornerRadius = min(self.frame.size.height, self.frame.size.width) / 2.0 self.clipsToBounds = true } @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { return UIColor(cgColor: layer.borderColor!) } set { layer.borderColor = newValue?.cgColor } } } extension Notification.Name { static let updateTheme = NSNotification.Name("updateTheme") static let fullVersion = NSNotification.Name("fullVersion") }
mit
3dde8bfa7a03eff111044e51df474ddd
27.71134
116
0.558707
4.311146
false
false
false
false
coach-plus/ios
Pods/Eureka/Source/Core/NavigationAccessoryView.swift
1
4361
// NavigationAccessoryView.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.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 Foundation import UIKit public protocol NavigationAccessory { var doneClosure: (() -> ())? { get set } var nextClosure: (() -> ())? { get set } var previousClosure: (() -> ())? { get set } var previousEnabled: Bool { get set } var nextEnabled: Bool { get set } } /// Class for the navigation accessory view used in FormViewController open class NavigationAccessoryView: UIToolbar, NavigationAccessory { open var previousButton: UIBarButtonItem! open var nextButton: UIBarButtonItem! open var doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(didTapDone)) private var fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) private var flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) public override init(frame: CGRect) { super.init(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: 44.0)) autoresizingMask = .flexibleWidth fixedSpace.width = 22.0 initializeChevrons() setItems([previousButton, fixedSpace, nextButton, flexibleSpace, doneButton], animated: false) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private func initializeChevrons() { var bundle = Bundle(for: NavigationAccessoryView.classForCoder()) if let resourcePath = bundle.path(forResource: "Eureka", ofType: "bundle") { if let resourcesBundle = Bundle(path: resourcePath) { bundle = resourcesBundle } } var imageLeftChevron = UIImage(named: "back-chevron", in: bundle, compatibleWith: nil) var imageRightChevron = UIImage(named: "forward-chevron", in: bundle, compatibleWith: nil) // RTL language support if #available(iOS 9.0, *) { imageLeftChevron = imageLeftChevron?.imageFlippedForRightToLeftLayoutDirection() imageRightChevron = imageRightChevron?.imageFlippedForRightToLeftLayoutDirection() } previousButton = UIBarButtonItem(image: imageLeftChevron, style: .plain, target: self, action: #selector(didTapPrevious)) nextButton = UIBarButtonItem(image: imageRightChevron, style: .plain, target: self, action: #selector(didTapNext)) } open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {} public var doneClosure: (() -> ())? public var nextClosure: (() -> ())? public var previousClosure: (() -> ())? @objc private func didTapDone() { doneClosure?() } @objc private func didTapNext() { nextClosure?() } @objc private func didTapPrevious() { previousClosure?() } public var previousEnabled: Bool { get { return previousButton.isEnabled } set { previousButton.isEnabled = previousEnabled } } public var nextEnabled: Bool { get { return nextButton.isEnabled } set { nextButton.isEnabled = nextEnabled } } }
mit
76d7e8fc875293f88592b8bccbf0b258
37.9375
129
0.681266
4.802863
false
false
false
false
rbailoni/SOSHospital
SOSHospital/SOSHospital/FilterTableViewController.swift
1
6314
// // FilterTableViewController.swift // SOSHospital // // Created by William kwong huang on 11/3/15. // Copyright © 2015 Quaddro. All rights reserved. // import UIKit import CoreData import CoreLocation class FilterTableViewController: UITableViewController, UITextFieldDelegate, CLLocationManagerDelegate { var hospitals = [Hospital]() @IBOutlet var searchTextField: UITextField! private var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext private var hospitalData = Hospital() var locationManager = CLLocationManager() private var lastLocation = CLLocation(latitude: 0, longitude: 0) override func viewDidLoad() { super.viewDidLoad() self.searchTextField.delegate = self self.locationManager.delegate = self print("bem vindo filtro") } override func viewDidAppear(animated: Bool) { if !self.locationManager.requestAuthorization() { presentViewController(self.locationManager.showNegativeAlert(), animated: true, completion: nil) } } // MARK: UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { let text = textField.text print(text) loadTableView(text) self.searchTextField.resignFirstResponder() return true } private func loadTableView(searchString: String? = nil) { // Localização do usuário guard let userLocation = locationManager.location else { return } // Limpa o array de hospitais self.hospitals.removeAll() self.hospitals = hospitalData.findHospitals(self.context, origin: userLocation, maxDistance: 5_000) if searchString != nil { if let search = searchString { let searchHospital = hospitals.filter { (item) -> Bool in item.name!.containsString("\(search)") } self.hospitals = searchHospital } } // Ordena por distancia self.hospitals.sortInPlace({$0.distance < $1.distance}) self.tableView.reloadData() } @IBAction func showOptions(sender: UIBarButtonItem) { let alerta = UIAlertController( title: "Filtro", message: "Selecione o filtro", preferredStyle: UIAlertControllerStyle.ActionSheet ) // adicionar ações let cancelAction = UIAlertAction( title: "Cancelar", style: UIAlertActionStyle.Cancel) { (action) -> Void in } let filterPerDistance = UIAlertAction( title: "Filtrar por distância", style: UIAlertActionStyle.Default) { (action) -> Void in self.hospitals.sortInPlace({$0.distance < $1.distance}) self.tableView.reloadData() } let filterPerNameAction = UIAlertAction( title: "Filtrar por nome", style: UIAlertActionStyle.Default) { (action) -> Void in self.hospitals.sortInPlace({$0.name < $1.name}) self.tableView.reloadData() } alerta.addAction(cancelAction) alerta.addAction(filterPerDistance) alerta.addAction(filterPerNameAction) // exibir alerta presentViewController(alerta, animated: true, completion: nil) } // MARK LocationManager func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print(error) } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let coordinate = locations.last!.coordinate print("Filter --> \(NSDate()) lat:\(coordinate.latitude), long:\(coordinate.longitude)") if let loc = locationManager.location { if lastLocation.distanceFromLocation(loc) > 100 { lastLocation = locationManager.location! loadTableView() } } // para a atualizacao da localizacao locationManager.stopUpdatingLocation() } // MARK: TableView override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.hospitals.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(FilterCell.Identifier, forIndexPath: indexPath) as! FilterCell let hospital = self.hospitals[indexPath.row] cell.hospitalLabel.text = hospital.name cell.distanceLabel.text = "distância: \(hospital.distance)m" cell.imagemView.image = UIImage(named: FilterCell.HospitalNameImage) return cell } @IBAction func refreshTableView(sender: UIRefreshControl) { self.searchTextField.text = "" locationManager.startUpdatingLocation() sender.endRefreshing() } override func scrollViewWillBeginDragging(scrollView: UIScrollView) { self.searchTextField.resignFirstResponder() } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController].+ // Pass the selected object to the new view controller. let viewController = segue.destinationViewController as! DetailViewController if let indexPathSelecionado = tableView.indexPathForSelectedRow { viewController.hospital = hospitals[indexPathSelecionado.row] viewController.originLocation = locationManager.location?.coordinate } } }
mit
ca9a21e0d23259eb875f4f37bccb5610
30.688442
125
0.617983
5.541301
false
false
false
false
mozilla-mobile/focus
Blockzilla/Modules/WebView/WebViewController.swift
1
19260
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import WebKit import Telemetry import OnePasswordExtension import PassKit protocol BrowserState { var url: URL? { get } var isLoading: Bool { get } var canGoBack: Bool { get } var canGoForward: Bool { get } var estimatedProgress: Double { get } } protocol WebController { var delegate: WebControllerDelegate? { get set } var canGoBack: Bool { get } var canGoForward: Bool { get } func load(_ request: URLRequest) } protocol WebControllerDelegate: class { func webControllerDidStartProvisionalNavigation(_ controller: WebController) func webControllerDidStartNavigation(_ controller: WebController) func webControllerDidFinishNavigation(_ controller: WebController) func webControllerDidNavigateBack(_ controller: WebController) func webControllerDidNavigateForward(_ controller: WebController) func webControllerDidReload(_ controller: WebController) func webControllerURLDidChange(_ controller: WebController, url: URL) func webController(_ controller: WebController, didFailNavigationWithError error: Error) func webController(_ controller: WebController, didUpdateCanGoBack canGoBack: Bool) func webController(_ controller: WebController, didUpdateCanGoForward canGoForward: Bool) func webController(_ controller: WebController, didUpdateEstimatedProgress estimatedProgress: Double) func webController(_ controller: WebController, scrollViewWillBeginDragging scrollView: UIScrollView) func webController(_ controller: WebController, scrollViewDidEndDragging scrollView: UIScrollView) func webController(_ controller: WebController, scrollViewDidScroll scrollView: UIScrollView) func webController(_ controller: WebController, stateDidChange state: BrowserState) func webControllerShouldScrollToTop(_ controller: WebController) -> Bool func webController(_ controller: WebController, didUpdateTrackingProtectionStatus trackingStatus: TrackingProtectionStatus) func webController(_ controller: WebController, didUpdateFindInPageResults currentResult: Int?, totalResults: Int?) } class WebViewController: UIViewController, WebController { private enum ScriptHandlers: String { case focusTrackingProtection case focusTrackingProtectionPostLoad case findInPageHandler static var allValues: [ScriptHandlers] { return [.focusTrackingProtection, .focusTrackingProtectionPostLoad, .findInPageHandler] } } private enum KVOConstants: String, CaseIterable { case URL = "URL" case canGoBack = "canGoBack" case canGoForward = "canGoForward" } weak var delegate: WebControllerDelegate? private var browserView: WKWebView! var onePasswordExtensionItem: NSExtensionItem! private var progressObserver: NSKeyValueObservation? private var urlObserver: NSKeyValueObservation? private var currentBackForwardItem: WKBackForwardListItem? private var userAgent: UserAgent? private var trackingProtectionStatus = TrackingProtectionStatus.on(TPPageStats()) { didSet { delegate?.webController(self, didUpdateTrackingProtectionStatus: trackingProtectionStatus) } } private var trackingInformation = TPPageStats() { didSet { if case .on = trackingProtectionStatus { trackingProtectionStatus = .on(trackingInformation) } } } var pageTitle: String? { return browserView.title } var userAgentString: String? { return self.userAgent?.getUserAgent() } var printFormatter: UIPrintFormatter { return browserView.viewPrintFormatter() } var scrollView: UIScrollView { return browserView.scrollView } convenience init(userAgent: UserAgent = UserAgent.shared) { self.init(nibName: nil, bundle: nil) self.userAgent = userAgent setupWebview() ContentBlockerHelper.shared.handler = reloadBlockers(_:) } func reset() { userAgent?.setup() browserView.load(URLRequest(url: URL(string: "about:blank")!)) browserView.navigationDelegate = nil browserView.removeFromSuperview() trackingProtectionStatus = .on(TPPageStats()) setupWebview() self.browserView.addObserver(self, forKeyPath: "URL", options: .new, context: nil) } // Browser proxy methods func load(_ request: URLRequest) { browserView.load(request) } func goBack() { browserView.goBack() } func goForward() { browserView.goForward() } func reload() { browserView.reload() } @available(iOS 9, *) func requestUserAgentChange() { guard let currentItem = browserView.backForwardList.currentItem else { return } userAgent?.changeUserAgent() browserView.customUserAgent = userAgent?.getUserAgent() if currentItem.url != currentItem.initialURL { // Reload the initial URL to avoid UA specific redirection browserView.load(URLRequest(url: currentItem.initialURL, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60)) } else { reload() // Reload the current URL. We cannot use loadRequest in this case because it seems to leverage caching. } UserDefaults.standard.set(false, forKey: TipManager.TipKey.requestDesktopTip) } func resetUA() { browserView.customUserAgent = userAgent?.browserUserAgent } func stop() { browserView.stopLoading() } private func setupWebview() { let wvConfig = WKWebViewConfiguration() wvConfig.websiteDataStore = WKWebsiteDataStore.nonPersistent() wvConfig.allowsInlineMediaPlayback = true browserView = WKWebView(frame: .zero, configuration: wvConfig) browserView.allowsBackForwardNavigationGestures = true browserView.allowsLinkPreview = false browserView.scrollView.clipsToBounds = false browserView.scrollView.delegate = self browserView.navigationDelegate = self browserView.uiDelegate = self browserView.allowsLinkPreview = true progressObserver = browserView.observe(\WKWebView.estimatedProgress) { (webView, value) in self.delegate?.webController(self, didUpdateEstimatedProgress: webView.estimatedProgress) } setupBlockLists() setupTrackingProtectionScripts() setupFindInPageScripts() view.addSubview(browserView) browserView.snp.makeConstraints { make in make.edges.equalTo(view.snp.edges) } KVOConstants.allCases.forEach { browserView.addObserver(self, forKeyPath: $0.rawValue, options: .new, context: nil) } } @objc private func reloadBlockers(_ blockLists: [WKContentRuleList]) { DispatchQueue.main.async { self.browserView.configuration.userContentController.removeAllContentRuleLists() blockLists.forEach(self.browserView.configuration.userContentController.add) } } private func setupBlockLists() { ContentBlockerHelper.shared.getBlockLists { lists in self.reloadBlockers(lists) } } private func addScript(forResource resource: String, injectionTime: WKUserScriptInjectionTime, forMainFrameOnly mainFrameOnly: Bool) { let source = try! String(contentsOf: Bundle.main.url(forResource: resource, withExtension: "js")!) let script = WKUserScript(source: source, injectionTime: injectionTime, forMainFrameOnly: mainFrameOnly) browserView.configuration.userContentController.addUserScript(script) } private func setupTrackingProtectionScripts() { browserView.configuration.userContentController.add(self, name: ScriptHandlers.focusTrackingProtection.rawValue) addScript(forResource: "preload", injectionTime: .atDocumentStart, forMainFrameOnly: true) browserView.configuration.userContentController.add(self, name: ScriptHandlers.focusTrackingProtectionPostLoad.rawValue) addScript(forResource: "postload", injectionTime: .atDocumentEnd, forMainFrameOnly: false) } private func setupFindInPageScripts() { browserView.configuration.userContentController.add(self, name: ScriptHandlers.findInPageHandler.rawValue) addScript(forResource: "FindInPage", injectionTime: .atDocumentEnd, forMainFrameOnly: true) } func disableTrackingProtection() { guard case .on = trackingProtectionStatus else { return } ScriptHandlers.allValues.forEach { browserView.configuration.userContentController.removeScriptMessageHandler(forName: $0.rawValue) } browserView.configuration.userContentController.removeAllUserScripts() browserView.configuration.userContentController.removeAllContentRuleLists() setupFindInPageScripts() trackingProtectionStatus = .off } func enableTrackingProtection() { guard case .off = trackingProtectionStatus else { return } setupBlockLists() setupTrackingProtectionScripts() trackingProtectionStatus = .on(TPPageStats()) } func evaluate(_ javascript: String, completion: ((Any?, Error?) -> Void)?) { browserView.evaluateJavaScript(javascript, completionHandler: completion) } override func viewDidLoad() { self.browserView.addObserver(self, forKeyPath: "URL", options: .new, context: nil) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { guard let kp = keyPath, let path = KVOConstants(rawValue: kp) else { assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")") return } switch path { case .URL: guard let url = browserView.url else { break } delegate?.webControllerURLDidChange(self, url: url) case .canGoBack: guard let canGoBack = change?[.newKey] as? Bool else { break } delegate?.webController(self, didUpdateCanGoBack: canGoBack) case .canGoForward: guard let canGoForward = change?[.newKey] as? Bool else { break } delegate?.webController(self, didUpdateCanGoForward: canGoForward) } } } extension WebViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { delegate?.webController(self, scrollViewDidScroll: scrollView) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { delegate?.webController(self, scrollViewWillBeginDragging: scrollView) } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { delegate?.webController(self, scrollViewDidEndDragging: scrollView) } func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool { return delegate?.webControllerShouldScrollToTop(self) ?? true } } extension WebViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { delegate?.webControllerDidStartNavigation(self) if case .on = trackingProtectionStatus { trackingInformation = TPPageStats() } } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { delegate?.webControllerDidFinishNavigation(self) self.resetUA() } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { delegate?.webController(self, didFailNavigationWithError: error) } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { let error = error as NSError guard error.code != Int(CFNetworkErrors.cfurlErrorCancelled.rawValue), let errorUrl = error.userInfo[NSURLErrorFailingURLErrorKey] as? URL else { return } let errorPageData = ErrorPage(error: error).data webView.load(errorPageData, mimeType: "", characterEncodingName: UIConstants.strings.encodingNameUTF8, baseURL: errorUrl) } func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { let response = navigationResponse.response guard let responseMimeType = response.mimeType else { decisionHandler(.allow) return } // Check for passbook response if responseMimeType == "application/vnd.apple.pkpass" { decisionHandler(.allow) browserView.load(URLRequest(url: URL(string: "about:blank")!)) func presentPassErrorAlert() { let passErrorAlert = UIAlertController(title: UIConstants.strings.addPassErrorAlertTitle, message: UIConstants.strings.addPassErrorAlertMessage, preferredStyle: .alert) let passErrorDismissAction = UIAlertAction(title: UIConstants.strings.addPassErrorAlertDismiss, style: .default) { (UIAlertAction) in passErrorAlert.dismiss(animated: true, completion: nil) } passErrorAlert.addAction(passErrorDismissAction) self.present(passErrorAlert, animated: true, completion: nil) } guard let responseURL = response.url else { presentPassErrorAlert() return } guard let passData = try? Data(contentsOf: responseURL) else { presentPassErrorAlert() return } guard let pass = try? PKPass(data: passData) else { // Alert user to add pass failure presentPassErrorAlert() return } // Present pass let passLibrary = PKPassLibrary() if passLibrary.containsPass(pass) { UIApplication.shared.open(pass.passURL!, options: [:]) } else { guard let addController = PKAddPassesViewController(pass: pass) else { presentPassErrorAlert() return } self.present(addController, animated: true, completion: nil) } return } decisionHandler(.allow) } func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { let present: (UIViewController) -> Void = { self.present($0, animated: true, completion: nil) } switch navigationAction.navigationType { case .backForward: let navigatingBack = webView.backForwardList.backList.filter { $0 == currentBackForwardItem }.count == 0 if navigatingBack { delegate?.webControllerDidNavigateBack(self) } else { delegate?.webControllerDidNavigateForward(self) } case .reload: delegate?.webControllerDidReload(self) default: break } currentBackForwardItem = webView.backForwardList.currentItem // prevent Focus from opening universal links // https://stackoverflow.com/questions/38450586/prevent-universal-links-from-opening-in-wkwebview-uiwebview let allowDecision = WKNavigationActionPolicy(rawValue: WKNavigationActionPolicy.allow.rawValue + 2) ?? .allow let decision: WKNavigationActionPolicy = RequestHandler().handle(request: navigationAction.request, alertCallback: present) ? allowDecision : .cancel if navigationAction.navigationType == .linkActivated && browserView.url != navigationAction.request.url { Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.click, object: TelemetryEventObject.websiteLink) } decisionHandler(decision) } func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { delegate?.webControllerDidStartProvisionalNavigation(self) } } extension WebViewController: BrowserState { var canGoBack: Bool { return browserView.canGoBack } var canGoForward: Bool { return browserView.canGoForward } var estimatedProgress: Double { return browserView.estimatedProgress } var isLoading: Bool { return browserView.isLoading } var url: URL? { return browserView.url } } extension WebViewController: WKUIDelegate { func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { if navigationAction.targetFrame == nil { browserView.load(navigationAction.request) } return nil } } extension WebViewController: WKScriptMessageHandler { func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if message.name == "findInPageHandler" { let data = message.body as! [String: Int] // We pass these separately as they're sent in different messages to the userContentController if let currentResult = data["currentResult"] { delegate?.webController(self, didUpdateFindInPageResults: currentResult, totalResults: nil) } if let totalResults = data["totalResults"] { delegate?.webController(self, didUpdateFindInPageResults: nil, totalResults: totalResults) } return } guard let body = message.body as? [String: String], let urlString = body["url"], var components = URLComponents(string: urlString) else { return } components.scheme = "http" guard let url = components.url else { return } let enabled = Utils.getEnabledLists().compactMap { BlocklistName(rawValue: $0) } TPStatsBlocklistChecker.shared.isBlocked(url: url, enabledLists: enabled).uponQueue(.main) { listItem in if let listItem = listItem { self.trackingInformation = self.trackingInformation.create(byAddingListItem: listItem) } } } } extension WebViewController { func createPasswordManagerExtensionItem() { OnePasswordExtension.shared().createExtensionItem(forWebView: browserView, completion: {(extensionItem, error) -> Void in if extensionItem == nil { return } // Set the 1Password extension item property self.onePasswordExtensionItem = extensionItem }) } func fillPasswords(returnedItems: [AnyObject]) { OnePasswordExtension.shared().fillReturnedItems(returnedItems, intoWebView: browserView, completion: { (success, returnedItemsError) -> Void in if !success { return } }) } }
mpl-2.0
81ce6fc8489b9c9ba1a211b19c4e75e3
41.422907
187
0.690966
5.495007
false
false
false
false
nkirby/Humber
_lib/HMGithub/_src/Sync/SyncController+OverviewEdit.swift
1
5607
// ======================================================= // HMGithub // Nathaniel Kirby // ======================================================= import Foundation import ReactiveCocoa import Result import HMCore // ======================================================= public protocol GithubOverviewSyncProviding { var didChangeOverviewNotification: String { get } func addOverviewItem(type type: String) -> SignalProducer<Void, SyncError> func deleteOverviewItem(itemID itemID: String) -> SignalProducer<Void, SyncError> func moveOverviewItem(itemID itemID: String, toPosition position: Int) -> SignalProducer<Void, SyncError> func editOverviewItem(itemID itemID: String, title: String) -> SignalProducer<Void, SyncError> func editOverviewItem(itemID itemID: String, title: String, repoName: String, repoOwner: String, type: String, threshold: Int) -> SignalProducer<Void, SyncError> func syncOverviewItem(itemID itemID: String) -> SignalProducer<Void, SyncError> } // ======================================================= extension SyncController: GithubOverviewSyncProviding { public var didChangeOverviewNotification: String { return "HMDidChangeOverviewNotification" } public func addOverviewItem(type type: String) -> SignalProducer<Void, SyncError> { return SignalProducer { observer, _ in guard let data = ServiceController.component(GithubOverviewDataProviding.self) else { observer.sendFailed(SyncError.Unknown) return } data.newOverviewItem(type: type, write: true) NSNotificationCenter.defaultCenter().postNotificationName(self.didChangeOverviewNotification, object: nil) observer.sendNext() observer.sendCompleted() } } public func deleteOverviewItem(itemID itemID: String) -> SignalProducer<Void, SyncError> { return SignalProducer { observer, _ in guard let data = ServiceController.component(GithubOverviewDataProviding.self) else { observer.sendFailed(SyncError.Unknown) return } data.removeOverviewItem(itemID: itemID, write: true) NSNotificationCenter.defaultCenter().postNotificationName(self.didChangeOverviewNotification, object: nil) observer.sendNext() observer.sendCompleted() } } public func moveOverviewItem(itemID itemID: String, toPosition position: Int) -> SignalProducer<Void, SyncError> { return SignalProducer { observer, _ in guard let data = ServiceController.component(GithubOverviewDataProviding.self) else { observer.sendFailed(.Unknown) return } data.moveOverviewItem(itemID: itemID, toPosition: position, write: true) NSNotificationCenter.defaultCenter().postNotificationName(self.didChangeOverviewNotification, object: nil) observer.sendNext() observer.sendCompleted() } } public func editOverviewItem(itemID itemID: String, title: String) -> SignalProducer<Void, SyncError> { return SignalProducer { observer, _ in guard let data = ServiceController.component(GithubOverviewDataProviding.self) else { observer.sendFailed(.Unknown) return } data.editOverviewItem(itemID: itemID, title: title, write: true) NSNotificationCenter.defaultCenter().postNotificationName(self.didChangeOverviewNotification, object: nil) observer.sendNext() observer.sendCompleted() } } public func editOverviewItem(itemID itemID: String, title: String, repoName: String, repoOwner: String, type: String, threshold: Int) -> SignalProducer<Void, SyncError> { return SignalProducer { observer, _ in guard let data = ServiceController.component(GithubOverviewDataProviding.self) else { observer.sendFailed(.Unknown) return } data.editOverviewItem(itemID: itemID, title: title, repoName: repoName, repoOwner: repoOwner, type: type, threshold: threshold, write: true) NSNotificationCenter.defaultCenter().postNotificationName(self.didChangeOverviewNotification, object: nil) observer.sendNext() observer.sendCompleted() } } public func syncOverviewItem(itemID itemID: String) -> SignalProducer<Void, SyncError> { return SignalProducer { observer, disposable in guard let api = ServiceController.component(GithubAPIQueryCountsProviding.self), let data = ServiceController.component(GithubOverviewDataProviding.self), let item = data.overviewItem(itemID: itemID) else { observer.sendFailed(SyncError.Unknown) return } let disp = api.getCounts(query: item.query) .on(failed: { _ in observer.sendFailed(.Unknown) }) .startWithNext { count in data.editOverviewItem(itemID: item.itemID, value: count, write: true) observer.sendNext() observer.sendCompleted() } disposable.addDisposable(disp) } } }
mit
8dcbe923af15672bcec9015a3e157b35
40.843284
174
0.606385
5.709776
false
false
false
false
GPWiOS/DouYuLive
DouYuTV/DouYuTV/Classes/Home/Controller/RecommendViewController.swift
1
4429
// // RecommendViewController.swift // DouYuTV // // Created by GaiPengwei on 2017/5/11. // Copyright © 2017年 GaiPengwei. All rights reserved. // import UIKit private let kItemMargin : CGFloat = 10 private let kHeaderViewH : CGFloat = 50 private let kNormalCellID = "kNormalCellID" private let kHeaderViewID = "kHeaderViewID" let kPrettyCellID = "kPrettyCellID" let kNormalItemW = (kScreenW - 3 * kItemMargin) / 2 let kNormalItemH = kNormalItemW * 3 / 4 let kPrettyItemH = kNormalItemW * 4 / 3 // 推荐分组的数量 private let kSectionCount : Int = 12 class RecommendViewController: UIViewController { // MARK - 懒加载 fileprivate lazy var collectionView : UICollectionView = { [unowned self] in // 1.创建布局 let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH) // 设置headerView的大小 layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin) // 2.创建collectionview let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.dataSource = self collectionView.delegate = self // 跟随父控件的fram collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID) collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID) // 注册headerView collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) return collectionView }() override func viewDidLoad() { super.viewDidLoad() // 设置UI界面 setupUI() } } // MARK - 设置UI界面 extension RecommendViewController{ fileprivate func setupUI(){ // 1.添加到collectionView view.addSubview(collectionView) } } // MARK - 遵守UIcollectionDataSource extension RecommendViewController : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{ func numberOfSections(in collectionView: UICollectionView) -> Int { return kSectionCount } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == 0 { return 8 } return 4 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.创建cell var cell : UICollectionViewCell if indexPath.section == 1 { cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) } else { cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) } // 2.设置内容 return cell } // 设置headerView的内容 func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // 1.取出section的headerView let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID, for: indexPath) // 2.设置内容 return headerView } // 重新设置item的size func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{ if indexPath.section == 1{ return CGSize(width: kNormalItemW, height: kPrettyItemH) } return CGSize(width: kNormalItemW, height: kNormalItemH) } } // MARK - 遵守UICollectionViewDelegate extension RecommendViewController : UICollectionViewDelegate{ }
mit
4641f5b6d4c5b60a2dacf51fdd467c18
32.271318
186
0.68849
5.863388
false
false
false
false
paulfreeman/Macroscope
nhspatientsafety/ViewController2.swift
1
4992
// // ViewController.swift // MonitoringExample-Swift // // Created by Marcin Klimek on 09/01/15. // Copyright (c) 2015 Estimote. All rights reserved. // import UIKit class ESTTableViewCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, ESTNearableManagerDelegate { var nearables:Array<ESTNearable>! var nearableManager:ESTNearableManager! var tableView:UITableView! override func viewDidLoad() { super.viewDidLoad() self.title = "Pick Nearable to monitor for:"; tableView = UITableView(frame: self.view.frame) tableView.delegate = self tableView.dataSource = self self.view.addSubview(tableView) tableView.registerClass(ESTTableViewCell.classForCoder(), forCellReuseIdentifier: "CellIdentifier") nearables = [] nearableManager = ESTNearableManager() nearableManager.delegate = self //nearableManager.startRangingForIdentifier("86eb8442e43ce463") //nearableManager.startRangingForIdentifier("dc5ee2afa360fb9c") nearableManager.startRangingForType(ESTNearableType.All) // nearableManager.startRangingForType(ESTNearableType.Bike) // nearableManager.startRangingForType(ESTNearableType.Car) // nearableManager.startRangingForType(ESTNearableType.Fridge) // nearableManager.startRangingForType(ESTNearableType.Bed) // nearableManager.startRangingForType(ESTNearableType.Chair) //nearableManager.startRangingForType(ESTNearableType.Shoe) // nearableManager.startRangingForType(ESTNearableType.Door) //nearableManager.startRangingForType(ESTNearableType.Dog) } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return nearables.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as! ESTTableViewCell let nearable = nearables[indexPath.row] as ESTNearable var details:NSString = NSString(format:"Type: %@ RSSI: %zd", ESTNearableDefinitions.nameForType(nearable.type), nearable.rssi); cell.textLabel?.text = NSString(format:"Identifier: %@", nearable.identifier) as? String cell.detailTextLabel?.text = details as? String; if let imageView = cell.viewWithTag(1001) as? UIImageView { imageView.image = self.imageForNearableType(nearable.type) } else { let imageView = UIImageView(frame: CGRectMake(self.view.frame.size.width - 60, 30, 30, 30)) imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.image = self.imageForNearableType(nearable.type) imageView.tag = 1001 cell.contentView.addSubview(imageView) } return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 80 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.performSegueWithIdentifier("details", sender: indexPath) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "details") { var monitVC:MonitoringDetailsViewController = segue.destinationViewController as! MonitoringDetailsViewController monitVC.nearable = self.nearables[(sender as! NSIndexPath).row] } } // MARK: - ESTNearableManager delegate func nearableManager(manager: ESTNearableManager!, didRangeNearables nearables: [AnyObject]!, withType type: ESTNearableType) { self.nearables = nearables as! Array<ESTNearable> self.nearables = self.nearables.filter({$0.identifier == "86eb8442e43ce463" || $0.identifier == "dc5ee2afa360fb9c"}) self.tableView.reloadData() } func imageForNearableType(type: ESTNearableType) -> UIImage? { switch (type) { case ESTNearableType.Bag: return UIImage(named: "trolley") case ESTNearableType.Fridge: return UIImage(named: "patient") default: return UIImage(named: "sticker_grey") } } }
mit
4ea85a98a1cd5e226425259ff6ba12b7
33.191781
135
0.666667
5.083503
false
false
false
false
ccrama/Slide-iOS
Slide for Reddit/CodeDisplayView.swift
1
3868
// // CodeDisplayView.swift // Slide for Reddit // // Created by Carlos Crane on 7/10/18. // Copyright © 2018 Haptic Apps. All rights reserved. // import Anchorage import DTCoreText import reddift import SDWebImage import Then import UIKit import YYText class CodeDisplayView: UIScrollView { var baseData = [NSAttributedString]() var scrollView: UIScrollView! var widths = [CGFloat]() var baseColor: UIColor var baseLabel: UILabel var globalHeight: CGFloat var linksCallback: ((URL) -> Void)? var indexCallback: (() -> Int)? init(baseHtml: String, color: UIColor, linksCallback: ((URL) -> Void)?, indexCallback: (() -> Int)?) { self.linksCallback = linksCallback self.indexCallback = indexCallback self.baseColor = color globalHeight = CGFloat(0) baseLabel = UILabel() baseLabel.numberOfLines = 0 super.init(frame: CGRect.zero) parseText(baseHtml.removingPercentEncoding ?? baseHtml) self.bounces = true self.isUserInteractionEnabled = true self.isScrollEnabled = true doData() } func parseText(_ text: String) { for string in text.split("\n") { if string.trimmed().isEmpty() { continue } let baseHtml = DTHTMLAttributedStringBuilder.init(html: string.trimmed().data(using: .unicode)!, options: [DTUseiOS6Attributes: true, DTDefaultTextColor: baseColor, DTDefaultFontFamily: "Courier", DTDefaultFontSize: FontGenerator.fontOfSize(size: 16, submission: false).pointSize, DTDefaultFontName: "Courier"], documentAttributes: nil).generatedAttributedString()! let attr = NSMutableAttributedString(attributedString: baseHtml) let cell = LinkParser.parse(attr, baseColor, font: UIFont(name: "Courier", size: 16)!, fontColor: ColorUtil.theme.fontColor, linksCallback: linksCallback, indexCallback: indexCallback) baseData.append(cell) } } func doData() { widths.removeAll() for row in baseData { let framesetter = CTFramesetterCreateWithAttributedString(row) let textSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRange(), nil, CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: CGFloat(40)), nil) let length = textSize.width + 25 widths.append(length) } addSubviews() } func addSubviews() { let finalString = NSMutableAttributedString.init() var index = 0 for row in baseData { finalString.append(row) if index != baseData.count - 1 { finalString.append(NSAttributedString.init(string: "\n")) } index += 1 } baseLabel.attributedText = finalString let size = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) let layout = YYTextLayout(containerSize: size, text: finalString)! let textSizeB = layout.textBoundingSize addSubview(baseLabel) contentInset = UIEdgeInsets.init(top: 8, left: 8, bottom: 0, right: 8) baseLabel.widthAnchor == getWidestCell() globalHeight = textSizeB.height + 16 baseLabel.heightAnchor == textSizeB.height baseLabel.leftAnchor == leftAnchor baseLabel.topAnchor == topAnchor contentSize = CGSize.init(width: getWidestCell() + 16, height: textSizeB.height) } func getWidestCell() -> CGFloat { var widest = CGFloat(0) for row in widths { if row > widest { widest = row } } return widest } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
6c7a2d89e96cf9ec1802e305b9129eae
35.481132
377
0.635376
4.894937
false
false
false
false
kousun12/RxSwift
Rx.playground/Pages/Combining_Observables.xcplaygroundpage/Contents.swift
4
5312
//: [<< Previous](@previous) - [Index](Index) import RxSwift /*: ## Combination operators Operators that work with multiple source Observables to create a single Observable. */ /*: ### `startWith` emit a specified sequence of items before beginning to emit the items from the source Observable ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/startwith.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/startwith.html ) */ example("startWith") { let subscription = sequenceOf(4, 5, 6, 7, 8, 9) .startWith(3) .startWith(2) .startWith(1) .startWith(0) .subscribe { print($0) } } /*: ### `combineLatest` when an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/combinelatest.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/combinelatest.html ) */ example("combineLatest 1") { let intOb1 = PublishSubject<String>() let intOb2 = PublishSubject<Int>() _ = combineLatest(intOb1, intOb2) { "\($0) \($1)" } .subscribe { print($0) } intOb1.on(.Next("A")) intOb2.on(.Next(1)) intOb1.on(.Next("B")) intOb2.on(.Next(2)) } //: To produce output, at least one element has to be received from each sequence in arguements. example("combineLatest 2") { let intOb1 = just(2) let intOb2 = sequenceOf(0, 1, 2, 3, 4) _ = combineLatest(intOb1, intOb2) { $0 * $1 } .subscribe { print($0) } } //: Combine latest has versions with more than 2 arguments. example("combineLatest 3") { let intOb1 = just(2) let intOb2 = sequenceOf(0, 1, 2, 3) let intOb3 = sequenceOf(0, 1, 2, 3, 4) _ = combineLatest(intOb1, intOb2, intOb3) { ($0 + $1) * $2 } .subscribe { print($0) } } /*: ### `zip` combine the emissions of multiple Observables together via a specified function and emit single items for each combination based on the results of this function ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/zip.png) [More info in reactive.io website](http://reactivex.io/documentation/operators/zip.html) */ example("zip 1") { let intOb1 = PublishSubject<String>() let intOb2 = PublishSubject<Int>() _ = zip(intOb1, intOb2) { "\($0) \($1)" } .subscribe { print($0) } intOb1.on(.Next("A")) intOb2.on(.Next(1)) intOb1.on(.Next("B")) intOb1.on(.Next("C")) intOb2.on(.Next(2)) } example("zip 2") { let intOb1 = just(2) let intOb2 = sequenceOf(0, 1, 2, 3, 4) _ = zip(intOb1, intOb2) { $0 * $1 } .subscribe { print($0) } } example("zip 3") { let intOb1 = sequenceOf(0, 1) let intOb2 = sequenceOf(0, 1, 2, 3) let intOb3 = sequenceOf(0, 1, 2, 3, 4) _ = zip(intOb1, intOb2, intOb3) { ($0 + $1) * $2 } .subscribe { print($0) } } /*: ### `merge` combine multiple Observables into one by merging their emissions ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/merge.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/merge.html ) */ example("merge 1") { let subject1 = PublishSubject<Int>() let subject2 = PublishSubject<Int>() _ = sequenceOf(subject1, subject2) .merge() .subscribeNext { int in print(int) } subject1.on(.Next(20)) subject1.on(.Next(40)) subject1.on(.Next(60)) subject2.on(.Next(1)) subject1.on(.Next(80)) subject1.on(.Next(100)) subject2.on(.Next(1)) } example("merge 2") { let subject1 = PublishSubject<Int>() let subject2 = PublishSubject<Int>() _ = sequenceOf(subject1, subject2) .merge(maxConcurrent: 2) .subscribe { print($0) } subject1.on(.Next(20)) subject1.on(.Next(40)) subject1.on(.Next(60)) subject2.on(.Next(1)) subject1.on(.Next(80)) subject1.on(.Next(100)) subject2.on(.Next(1)) } /*: ### `switchLatest` convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently-emitted of those Observables ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/switch.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/switch.html ) */ example("switchLatest") { let var1 = Variable(0) let var2 = Variable(200) // var3 is like an Observable<Observable<Int>> let var3 = Variable(var1) let d = var3 .switchLatest() .subscribe { print($0) } var1.value = 1 var1.value = 2 var1.value = 3 var1.value = 4 var3.value = var2 var2.value = 201 var1.value = 5 var1.value = 6 var1.value = 7 } //: [Index](Index) - [Next >>](@next)
mit
4ea775f46b066748926f611f5a3ffeb3
20.506073
182
0.606551
3.581929
false
true
false
false
damicreabox/Git2Swift
Sources/Git2Swift/branch/Branches.swift
1
4737
// // Branches.swift // Git2Swift // // Created by Damien Giron on 01/08/2016. // // import Foundation import CLibgit2 /// Branches manager public class Branches { /// Repository public let repository: Repository /// Constructor with repository /// /// - parameter repository: Git2Swift repository /// /// - returns: Branches init(repository: Repository) { self.repository = repository } /// All branch names public func names(type: BranchType = .local) throws -> [String] { var strs = [String]() for branch in try all(type: type) { strs.append(branch.name) } return strs } /// Get branch with full reference name /// /// - parameter name: Branch name /// /// - throws: GitError (notFound, invalidSpec) /// /// - returns: Branch public func get(spec: String) throws -> Branch { let specInfo = try Branch.getSpecInfo(spec: spec) return try get(name: specInfo.name, type: specInfo.type) } /// Get branch by name /// /// - parameter name: Branch name /// - parameter type: Branch type /// /// - throws: GitError (notFound, invalidSpec) /// /// - returns: Branch public func get(name: String, type: BranchType = .local) throws -> Branch { // Find reference pointer let reference = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1) // Lookup reference let error = git_branch_lookup(reference, repository.pointer.pointee, name, git_convert_branch_type(type)) if (error != 0) { reference.deinitialize() reference.deallocate(capacity: 1) // 0 on success, GIT_ENOTFOUND, GIT_EINVALIDSPEC or an error code. switch (error) { case GIT_ENOTFOUND.rawValue : throw GitError.notFound(ref: name) case GIT_EINVALIDSPEC.rawValue: throw GitError.invalidSpec(spec: name) default: throw gitUnknownError("Unable to lookup reference \(name)", code: error) } } return try Branch(repository: repository, name:name, pointer: reference) } /// Create a new branch /// /// - parameter name: New branch name /// - parameter force: Force creation /// /// - throws: GitError /// /// - returns: Branch public func create(name: String, force: Bool = false) throws -> Branch { // Find last commit guard let lastCommit = try repository.head().targetCommit().pointer.pointee else { throw GitError.notFound(ref: "HEAD") } // new_branch let new_branch = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1) // Create branch let error = git_branch_create(new_branch, repository.pointer.pointee, name, lastCommit, force ? 1 : 0) if (error == 0) { return try Branch(repository: repository, name: name, pointer: new_branch) } else { throw gitUnknownError("Unable to create branch", code: error) } } /// Remove a branch by name and type /// /// - parameter name: Branch name /// - parameter type: Branch type /// /// - throws: GitError public func remove(name: String, type: BranchType = .local) throws { // branch let lookup_branch = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1) defer { if (lookup_branch.pointee != nil) { git_reference_free(lookup_branch.pointee) } lookup_branch.deinitialize() lookup_branch.deallocate(capacity: 1) } // Find type let branchType : git_branch_t if (type == .remote) { branchType = GIT_BRANCH_REMOTE } else { branchType = GIT_BRANCH_LOCAL } let error = git_branch_lookup(lookup_branch, repository.pointer.pointee, name, branchType) if (error == 0 && lookup_branch.pointee != nil) { git_branch_delete(lookup_branch.pointee) } else { throw gitUnknownError("Unable to delete branch", code: error) } } /// Find all branches /// /// - parameter type: Filter by types /// /// - throws: GitError /// /// - returns: Branch iterator public func all(type: BranchType = .local) throws -> BranchIterator { return BranchIterator(repository: repository, type: type) } }
apache-2.0
9d9a771e195be0f401d6d1023646b7f2
28.981013
113
0.557948
4.581238
false
false
false
false
astralbodies/Swift4NowWithTaterTots
Swift 4 Playground.playground/Pages/Collections.xcplaygroundpage/Contents.swift
1
633
//: [Previous](@previous) import Foundation let totBrands = ["Ore Ida", "Great Value", "Roundys"] totBrands.count for brand in totBrands { print(brand) } //totBrands.append("Kroger") // won't compile; change to var or create new var totBrands2 = totBrands totBrands2.append("Kroger") //let oreIda = [ "name": "Ore Ida", "founded": 1952, "hq_location": "Pittsburgh, PA" ] // explicit to any let oreIda:[String: Any] = [ "name": "Ore Ida", "founded": 1952, "hq_location": "Pittsburgh, PA" ] let brandsInFreezer: Set<String> = ["Ore Ida", "Kroger", "Ore Ida"] totBrands.forEach { brand in print(brand) } //: [Next](@next)
mit
648282dce72b14ccc4900938cf5bf481
26.521739
105
0.663507
2.705128
false
false
false
false
bamurph/FeedKit
Sources/Model/RSS/RSSFeedCloud.swift
2
4758
// // RSSFeedCloud.swift // // Copyright (c) 2016 Nuno Manuel Dias // // 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 /** Allows processes to register with a cloud to be notified of updates to the channel, implementing a lightweight publish-subscribe protocol for RSS feeds. Example: <cloud domain="rpc.sys.com" port="80" path="/RPC2" registerProcedure="pingMe" protocol="soap"/> <cloud> is an optional sub-element of <channel>. It specifies a web service that supports the rssCloud interface which can be implemented in HTTP-POST, XML-RPC or SOAP 1.1. Its purpose is to allow processes to register with a cloud to be notified of updates to the channel, implementing a lightweight publish-subscribe protocol for RSS feeds. <cloud domain="rpc.sys.com" port="80" path="/RPC2" registerProcedure="myCloud.rssPleaseNotify" protocol="xml-rpc" /> In this example, to request notification on the channel it appears in, you would send an XML-RPC message to rpc.sys.com on port 80, with a path of /RPC2. The procedure to call is myCloud.rssPleaseNotify. A full explanation of this element and the rssCloud interface is here: http://cyber.law.harvard.edu/rss/soapMeetsRss.html#rsscloudInterface */ open class RSSFeedCloud { /** The attributes of the `<channel>`'s `<cloud>` element */ open class Attributes { /** The domain to register notification to. */ open var domain: String? /** The port to connect to. */ open var port: Int? /** The path to the RPC service. e.g. "/RPC2" */ open var path: String? /** The procedure to call. e.g. "myCloud.rssPleaseNotify" */ open var registerProcedure: String? /** The `protocol` specification. Can be HTTP-POST, XML-RPC or SOAP 1.1 - Note: "protocol" is a reserved keyword, so `protocolSpecification` is used instead and refers to the `protocol` attribute of the `cloud` element. */ open var protocolSpecification: String? } /** The element's attributes */ open var attributes: Attributes? } // MARK: - Initializers extension RSSFeedCloud { /** Initializes the `RSSFeedCloud` with the attributes of the `<cloud>` element - parameter attributeDict: A dictionary with the attributes of the `<cloud>` element - returns: A `RSSFeedCloud` instance */ convenience init(attributes attributeDict: [String : String]) { self.init() self.attributes = RSSFeedCloud.Attributes(attributes: attributeDict) } } extension RSSFeedCloud.Attributes { /** Initializes the `Attributes` of the `RSSFeedCloud` - parameter: A dictionary with the attributes of the `<cloud>` element - returns: A `RSSFeedCloud.Attributes` instance */ convenience init?(attributes attributeDict: [String : String]) { if attributeDict.isEmpty { return nil } self.init() self.domain = attributeDict["domain"] self.port = Int(attributeDict["port"] ?? "") self.path = attributeDict["path"] self.registerProcedure = attributeDict["registerProcedure"] self.protocolSpecification = attributeDict["protocol"] } }
mit
794e83653a3447d2a0a717b2eb1832db
28.924528
117
0.629466
4.683071
false
false
false
false
hooman/swift
test/attr/require_explicit_availability.swift
6
7315
// Test the -require-explicit-availability flag // REQUIRES: OS=macosx // RUN: %swiftc_driver -typecheck -parse-as-library -target %target-cpu-apple-macosx10.10 -Xfrontend -verify -require-explicit-availability -require-explicit-availability-target "macOS 10.10" %s public struct S { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} public func method() { } } public func foo() { bar() } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @usableFromInline func bar() { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @available(macOS 10.1, *) public func ok() { } @available(macOS, unavailable) public func unavailableOk() { } @available(macOS, deprecated: 10.10) public func missingIntro() { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @available(iOS 9.0, *) public func missingTargetPlatform() { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} func privateFunc() { } @_alwaysEmitIntoClient public func alwaysEmitted() { } @available(macOS 10.1, *) struct SOk { public func okMethod() { } } precedencegroup MediumPrecedence {} infix operator + : MediumPrecedence public func +(lhs: S, rhs: S) -> S { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} public enum E { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} public class C { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} public protocol P { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} private protocol PrivateProto { } extension S { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} public func warnForPublicMembers() { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{3-3=@available(macOS 10.10, *)\n }} } @available(macOS 10.1, *) extension S { public func okWhenTheExtensionHasAttribute() { } } extension S { internal func dontWarnWithoutPublicMembers() { } private func dontWarnWithoutPublicMembers1() { } } extension S : P { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} } extension S : PrivateProto { } open class OpenClass { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} private class PrivateClass { } extension PrivateClass { } @available(macOS 10.1, *) public protocol PublicProtocol { } @available(macOS 10.1, *) extension S : PublicProtocol { } @_spi(SPIsAreOK) public func spiFunc() { } @_spi(SPIsAreOK) public struct spiStruct { public func spiMethod() {} } extension spiStruct { public func spiExtensionMethod() {} } public var publicVar = S() // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @available(macOS 10.10, *) public var publicVarOk = S() public var (a, b) = (S(), S()) // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @available(macOS 10.10, *) public var (c, d) = (S(), S()) public var _ = S() // expected-error {{global variable declaration does not bind any variables}} public var implicitGet: S { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} return S() } @available(macOS 10.10, *) public var implicitGetOk: S { return S() } public var computed: S { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} get { return S() } set { } } public var computedHalf: S { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @available(macOS 10.10, *) get { return S() } set { } } // FIXME the following warning is not needed. public var computedOk: S { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @available(macOS 10.10, *) get { return S() } @available(macOS 10.10, *) set { } } @available(macOS 10.10, *) public var computedOk1: S { get { return S() } set { } } public class SomeClass { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} public init () {} public subscript(index: String) -> Int { get { return 42; } set(newValue) { } } } extension SomeClass { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} public convenience init(s : S) {} // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{3-3=@available(macOS 10.10, *)\n }} @available(macOS 10.10, *) public convenience init(s : SomeClass) {} public subscript(index: Int) -> Int { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{3-3=@available(macOS 10.10, *)\n }} get { return 42; } set(newValue) { } } @available(macOS 10.10, *) public subscript(index: S) -> Int { get { return 42; } set(newValue) { } } } @available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *) public struct StructWithImplicitMembers { } extension StructWithImplicitMembers: Hashable { } // expected-note @-1 {{add @available attribute to enclosing extension}} // expected-warning @-2 {{public declarations should have an availability attribute when building with -require-explicit-availability}} // expected-error @-3 {{'StructWithImplicitMembers' is only available in macOS 10.15 or newer}}
apache-2.0
4dec988bcff663bd97f60f7afdff39a8
41.04023
211
0.725769
3.945523
false
false
false
false
col/iReSign
iReSignKit/Tasks/VerifyCodeSignTask.swift
1
1035
// // VerifyCodeSignTask.swift // iReSign // // Created by Colin Harris on 4/10/15. // Copyright © 2015 Colin Harris. All rights reserved. // import Foundation class VerifyCodeSignTask: IROperation { let task: NSTask let path: String init(path: String) { self.path = path task = NSTask() super.init() state = .Ready } override func start() { if cancelled { return } state = .Executing task.launchPath = "/usr/bin/codesign" task.arguments = ["-v", path] let pipe = NSPipe() task.standardOutput = pipe task.standardError = pipe let handle = pipe.fileHandleForReading task.launch() let _ = NSString(data: handle.readDataToEndOfFile(), encoding: NSASCIIStringEncoding) while(task.running) { NSThread.sleepForTimeInterval(1.0) } state = .Finished } }
mit
35eebf1b3933f77c0a042be7257b46f0
20.122449
93
0.531915
4.657658
false
false
false
false
diversario/bitfountain-ios-foundations
iOS/Shoe Converter/Shoe Converter/ViewController.swift
1
1487
// // ViewController.swift // Shoe Converter // // Created by Ilya Shaisultanov on 1/2/16. // Copyright © 2016 Ilya Shaisultanov. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var mensConvertedShoeSizeLabel: UILabel! @IBOutlet weak var womensConvertedShoeSizeLabel: UILabel! @IBOutlet weak var mensShoeSizeTextField: UITextField! @IBOutlet weak var womensShoeSizeTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. view.backgroundColor = UIColor(patternImage: UIImage(named: "background")!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func convertMensShoeSizePressed(sender: UIButton) { let size = Int(mensShoeSizeTextField.text!)! let conversionConstant = 30 let convertedSize = conversionConstant + size mensConvertedShoeSizeLabel.text = "\(convertedSize) is \(size) in EU" } @IBAction func convertWomensShoeSizePressed(sender: UIButton) { let size = Double(womensShoeSizeTextField.text!)! let conversionConstant = 30.5 let convertedSize = conversionConstant + size womensConvertedShoeSizeLabel.text = "\(convertedSize) is \(size) in EU" } }
mit
3d394ce1768b2c8d6b33e07f92cfbd29
29.958333
83
0.685061
4.558282
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Helpers/UIView+Constraints.swift
1
3450
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit import WireSystem struct EdgeInsets { let top, leading, bottom, trailing: CGFloat static let zero = EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0) init(top: CGFloat, leading: CGFloat, bottom: CGFloat, trailing: CGFloat) { self.top = top self.leading = leading self.bottom = bottom self.trailing = trailing } init(margin: CGFloat) { self = EdgeInsets(top: margin, leading: margin, bottom: margin, trailing: margin) } init(edgeInsets: UIEdgeInsets) { top = edgeInsets.top leading = edgeInsets.leading bottom = edgeInsets.bottom trailing = edgeInsets.trailing } } enum Anchor { case top case bottom case leading case trailing } enum AxisAnchor { case centerX case centerY } enum LengthAnchor { case width case height } struct LengthConstraints { let constraints: [LengthAnchor: NSLayoutConstraint] subscript(anchor: LengthAnchor) -> NSLayoutConstraint? { return constraints[anchor] } var array: [NSLayoutConstraint] { return constraints.values.map { $0 } } } extension UIView { /// fit self in a container view /// - Parameters: /// - view: the container view to fit in /// - inset: inset of self func fitIn(view: UIView, inset: CGFloat) { fitIn(view: view, insets: UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)) } /// fit self in a container view /// notice bottom and right inset no need to set to negative of top/left, e.g. if you want to add inset to self with 2 pt: /// /// self.fitIn(view: container, insets: UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)) /// /// - Parameters: /// - view: the container view to fit in /// - insets: a UIEdgeInsets for inset of self. func fitIn(view: UIView, insets: UIEdgeInsets = .zero) { NSLayoutConstraint.activate(fitInConstraints(view: view, insets: insets)) } func fitInConstraints(view: UIView, inset: CGFloat) -> [NSLayoutConstraint] { return fitInConstraints(view: view, insets: UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)) } func fitInConstraints(view: UIView, insets: UIEdgeInsets = .zero) -> [NSLayoutConstraint] { return [ leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: insets.leading), trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -insets.trailing), topAnchor.constraint(equalTo: view.topAnchor, constant: insets.top), bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -insets.bottom) ] } }
gpl-3.0
5a8187faaf5b4b9aebfba36159521878
30.363636
126
0.662899
4.259259
false
false
false
false
kfarst/alarm
alarm/RawTime.swift
1
1313
// // RawTime.swift // alarm // // Created by Michael Lewis on 3/15/15. // Copyright (c) 2015 Kevin Farst. All rights reserved. // import Foundation // RawTime is a helper class that contains an hour/minute pair // It provides some _very_ basic logic for converting between // 24-hour and 12-hour time. It stores in 24-hour time. struct RawTime: Comparable, Hashable { enum AmPm { case AM case PM } // Only `hour24` and `minute` are required var hour24: Int var minute: Int // All other variables are derived // `hour12` is the hours, as it would be displayed on a 12-hour // clock. var hour12: Int { get { if hour24 == 0 { return 12 } else if hour24 < 13 { return hour24 } else { return hour24 - 12 } } } var amOrPm: AmPm { if hour24 < 12 { return .AM } else { return .PM } } var hashValue: Int { get { return hour24.hashValue ^ minute.hashValue } } } // Comparison operators for RawTime func <(left: RawTime, right: RawTime) -> Bool { return ( left.hour24 < right.hour24 || (left.hour24 == right.hour24 && left.minute < right.minute) ) } func ==(left: RawTime, right: RawTime) -> Bool { return left.hour24 == right.hour24 && left.minute == right.minute }
mit
a16b289551329cb0df460122fb0b7b8a
19.515625
67
0.610053
3.41039
false
false
false
false
ZekeSnider/Jared
Jared/WebHookManager.swift
1
3762
// // WebHookManager.swift // Jared // // Created by Zeke Snider on 2/2/19. // Copyright © 2019 Zeke Snider. All rights reserved. // import Foundation import JaredFramework class WebHookManager: MessageDelegate, RoutingModule { var urlSession: URLSession var webhooks = [Webhook]() var routes = [Route]() var sender: MessageSender var description = "Routes provided by webhooks" public init(webhooks: [Webhook]?, session: URLSessionConfiguration = URLSessionConfiguration.ephemeral, sender: MessageSender) { session.timeoutIntervalForResource = 10.0 self.sender = sender urlSession = URLSession(configuration: session) updateHooks(to: webhooks) } required convenience init(sender: MessageSender) { self.init(webhooks: nil, session: URLSessionConfiguration.ephemeral, sender: sender) } public func didProcess(message: Message) { // loop over all webhooks, if the list is null, do nothing. for webhook in webhooks { // if a webhook has routes, we shouldn't call it for every message guard webhook.routes?.count == 0 else { break } notifyRoute(message, url: webhook.url) } } public func notifyRoute(_ message: Message, url: String) { NSLog("Notifying \(url) of new message event") guard let parsedUrl = URL(string: url) else { NSLog("Unable to parse URL for webhook \(url)") return } let webhookBody = WebHookManager.createWebhookBody(message) var request = URLRequest(url: parsedUrl) request.httpMethod = "POST" request.httpBody = webhookBody request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") urlSession.dataTask(with: request) { data, response, error in guard error == nil, let data = data, let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { NSLog("Received error while requesting webhook \(error.debugDescription)") return } guard let decoded = try? JSONDecoder().decode(WebhookResponse.self, from: data) else { NSLog("Unable to parse response from webhook") return } if (decoded.success) { if let decodedBody = decoded.body?.message { self.sender.send(decodedBody, to: message.RespondTo()) } } else { if let decodedError = decoded.error { NSLog("Got back error from webhook. \(decodedError)") return } } }.resume() } public func updateHooks(to hooks: [Webhook]?) { // Change all routes to have a callback that calls the webhook manager's // notify route method self.webhooks = (hooks ?? []).map({ (hook) -> Webhook in var newHook = hook newHook.routes = (newHook.routes ?? []).map({ (route) -> Route in var newRoute = route newRoute.call = {[weak self] in self?.notifyRoute($0, url: newHook.url) } return newRoute }) return newHook }) self.routes = self.webhooks.flatMap({ $0.routes ?? [] }) NSLog("Webhooks updated to: \(self.webhooks.map{ $0.url }.joined(separator: ", "))") } static private func createWebhookBody(_ message: Message) -> Data? { return try? JSONEncoder().encode(message) } }
apache-2.0
f59cef68c92b31740b0db62440122101
35.163462
132
0.570061
4.884416
false
false
false
false
wowiwj/Yeep
Yeep/Yeep/ViewControllers/Register/RegisterPickNameViewController.swift
1
5552
// // RegisterPickNameViewController.swift // Yeep // // Created by wangju on 16/7/18. // Copyright © 2016年 wangju. All rights reserved. // import UIKit import Ruler class RegisterPickNameViewController: BaseViewController { var mobile: String? var areaCode: String? @IBOutlet private weak var pickNamePromptLabel: UILabel! @IBOutlet private weak var pickNamePromptLabelTopConstraint: NSLayoutConstraint! @IBOutlet private weak var promptTermsLabel: UILabel! @IBOutlet private weak var nameTextField: BorderTextField! @IBOutlet private weak var nameTextFieldTopConstraint: NSLayoutConstraint! private lazy var nextButton:UIBarButtonItem = { let button = UIBarButtonItem(title: NSLocalizedString("Next", comment: ""), style: .Plain, target: self, action: #selector(next(_:))) return button }() private var isDirty = false { willSet { nextButton.enabled = newValue promptTermsLabel.alpha = newValue ? 1.0 : 0.5 } } override func viewDidLoad() { super.viewDidLoad() animatedOnNavigationBar = false view.backgroundColor = UIColor.yeepViewBackgroundColor() navigationItem.titleView = NavigationTitleLabel(title: NSLocalizedString("Sign up", comment: "")) navigationItem.rightBarButtonItem = nextButton pickNamePromptLabel.text = NSLocalizedString("What's your name?", comment: "") let text = NSLocalizedString("By tapping Next you agree to our terms.", comment: "") let textAttributes: [String: AnyObject] = [ NSFontAttributeName: UIFont.systemFontOfSize(14), NSForegroundColorAttributeName: UIColor.grayColor(), ] let attributedText = NSMutableAttributedString(string: text, attributes: textAttributes) let termsAttributes: [String: AnyObject] = [ NSForegroundColorAttributeName: UIColor.yeepTintColor(), NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue, ] let tapRange = (text as NSString).rangeOfString(NSLocalizedString("terms", comment: "")) attributedText.addAttributes(termsAttributes, range: tapRange) promptTermsLabel.attributedText = attributedText promptTermsLabel.textAlignment = .Center promptTermsLabel.alpha = 0.5 promptTermsLabel.userInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(RegisterPickNameViewController.tapTerms(_:))) promptTermsLabel.addGestureRecognizer(tap) nameTextField.backgroundColor = UIColor.whiteColor() nameTextField.textColor = UIColor.yeepInputTextColor() nameTextField.placeholder = " "//NSLocalizedString("Nickname", comment: "") nameTextField.delegate = self nameTextField.addTarget(self, action: #selector(RegisterPickNameViewController.textFieldDidChange(_:)), forControlEvents: .EditingChanged) pickNamePromptLabelTopConstraint.constant = Ruler.iPhoneVertical(30, 50, 60, 60).value nameTextFieldTopConstraint.constant = Ruler.iPhoneVertical(30, 40, 50, 50).value nextButton.enabled = false } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) nameTextField.becomeFirstResponder() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { nameTextField.endEditing(true) } // MARK : - 动作的监听 @objc private func tapTerms(sender: UITapGestureRecognizer) { print("tap") if let url = NSURL(string: YeepConfig.termsURLString) { yeep_openUrl(url) } } @objc private func next(sender: UIBarButtonItem) { showRegisterPickMobie() } private func showRegisterPickMobie() { guard let text = nameTextField.text else { return } let nickName = text.trimming(.WhitespaceAndNewline) YeepUserDefaults.nickname.value = nickName performSegueWithIdentifier("showRegisterPickMobile", sender: nil) } @objc private func textFieldDidChange(textField: UITextField) { guard let text = textField.text else { return } isDirty = !text.isEmpty } // MARK: Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { guard let identifier = segue.identifier else { return } switch identifier { case "showRegisterPickMobile": let vc = segue.destinationViewController as! RegisterPickMobileViewController vc.mobile = mobile vc.areaCode = areaCode default: break } } } extension RegisterPickNameViewController: UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { guard let text = textField.text else { return true } if !text.isEmpty { showRegisterPickMobie() print("showRegisterPickMobile") } return true } }
mit
c21ebb10f2932116d91d094175e5be5f
30.117978
146
0.633688
5.669396
false
false
false
false
borglab/SwiftFusion
Tests/SwiftFusionTests/Core/FixedSizeMatrixTests.swift
1
8879
// Copyright 2020 The SwiftFusion 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 _Differentiation import XCTest import PenguinStructures import SwiftFusion /// A 3x2 matrix, where each row is a `Vector2`. fileprivate typealias Matrix3x2 = FixedSizeMatrix<Array3<Vector2>> /// A 3x5 matrix, where each row is a `Tuple2<Vector2, Vector3>` fileprivate typealias Matrix3x2_3x3 = FixedSizeMatrix<Array3<Tuple2<Vector2, Vector3>>> class FixedSizeMatrixTests: XCTestCase { func testVectorConformance() { let s1 = (0..<6).lazy.map { Double($0) } let v1 = Matrix3x2(s1) v1.checkVectorSemantics(expectingScalars: s1, writingScalars: (6..<12).lazy.map { Double($0) }) v1.scalars.checkRandomAccessCollectionSemantics(expecting: s1) let s2 = (0..<9).lazy.map { Double($0) } let v2 = Matrix3(s2) v2.checkVectorSemantics(expectingScalars: s2, writingScalars: (9..<18).lazy.map { Double($0) }) v2.scalars.checkRandomAccessCollectionSemantics(expecting: s2) } func testShape() { XCTAssertEqual(Matrix3.shape, Array2(3, 3)) XCTAssertEqual(Matrix3x2.shape, Array2(3, 2)) XCTAssertEqual(Matrix3x2_3x3.shape, Array2(3, 5)) } func testInitElements() { let m1 = Matrix3x2([ 1, 2, 10, 20, 100, 200 ]) XCTAssertEqual(m1[0, 0], 1) XCTAssertEqual(m1[0, 1], 2) XCTAssertEqual(m1[1, 0], 10) XCTAssertEqual(m1[1, 1], 20) XCTAssertEqual(m1[2, 0], 100) XCTAssertEqual(m1[2, 1], 200) } func testInitRows() { let m1 = Matrix3x2(rows: Vector2(1, 2), Vector2(10, 20), Vector2(100, 200)) XCTAssertEqual(m1[0, 0], 1) XCTAssertEqual(m1[0, 1], 2) XCTAssertEqual(m1[1, 0], 10) XCTAssertEqual(m1[1, 1], 20) XCTAssertEqual(m1[2, 0], 100) XCTAssertEqual(m1[2, 1], 200) let (m2, pb) = valueWithPullback(at: 1) { x in Matrix3x2(rows: Vector2(1 * x, 2 * x), Vector2(10 * x, 20 * x), Vector2(100 * x, 200 * x)) } XCTAssertEqual(m2[0, 0], 1) XCTAssertEqual(m2[0, 1], 2) XCTAssertEqual(m2[1, 0], 10) XCTAssertEqual(m2[1, 1], 20) XCTAssertEqual(m2[2, 0], 100) XCTAssertEqual(m2[2, 1], 200) XCTAssertEqual(pb(Matrix3x2([1, 0, 0, 0, 0, 0])), 1) XCTAssertEqual(pb(Matrix3x2([0, 1, 0, 0, 0, 0])), 2) XCTAssertEqual(pb(Matrix3x2([0, 0, 1, 0, 0, 0])), 10) XCTAssertEqual(pb(Matrix3x2([0, 0, 0, 1, 0, 0])), 20) XCTAssertEqual(pb(Matrix3x2([0, 0, 0, 0, 1, 0])), 100) XCTAssertEqual(pb(Matrix3x2([0, 0, 0, 0, 0, 1])), 200) } func testIdentity() { let m1 = Matrix3.identity for i in 0..<3 { for j in 0..<3 { XCTAssertEqual(m1[i, j], i == j ? 1 : 0) } } } func testInitMatrix3Helper() { let m1 = Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9) XCTAssertEqual(m1[0, 0], 1) XCTAssertEqual(m1[0, 1], 2) XCTAssertEqual(m1[0, 2], 3) XCTAssertEqual(m1[1, 0], 4) XCTAssertEqual(m1[1, 1], 5) XCTAssertEqual(m1[1, 2], 6) XCTAssertEqual(m1[2, 0], 7) XCTAssertEqual(m1[2, 1], 8) XCTAssertEqual(m1[2, 2], 9) } func testZero() { let m1 = Matrix3x2.zero for i in 0..<3 { for j in 0..<2 { XCTAssertEqual(m1[i, j], 0) } } let m2 = Matrix3x2_3x3.zero for i in 0..<3 { for j in 0..<5 { XCTAssertEqual(m2[i, j], 0) } } } func testAdd() { let m1 = Matrix3x2([0, 1, 2, 3, 4, 5]) let m2 = Matrix3x2([0, 10, 20, 30, 40, 50]) let expected = Matrix3x2([0, 11, 22, 33, 44, 55]) XCTAssertEqual(m1 + m2, expected) let (value, pb) = valueWithPullback(at: m1, m2) { $0 + $1 } XCTAssertEqual(value, expected) for b in Matrix3x2.standardBasis { XCTAssertEqual(pb(b).0, b) XCTAssertEqual(pb(b).1, b) } } func testSubtract() { let m1 = Matrix3x2([0, 11, 22, 33, 44, 55]) let m2 = Matrix3x2([0, 1, 2, 3, 4, 5]) let expected = Matrix3x2([0, 10, 20, 30, 40, 50]) XCTAssertEqual(m1 - m2, expected) let (value, pb) = valueWithPullback(at: m1, m2) { $0 - $1 } XCTAssertEqual(value, expected) for b in Matrix3x2.standardBasis { XCTAssertEqual(pb(b).0, b) XCTAssertEqual(pb(b).1, -b) } } func testMultiply() { let m = Matrix3x2([0, 1, 2, 3, 4, 5]) let s: Double = 10 let expected = Matrix3x2([0, 10, 20, 30, 40, 50]) XCTAssertEqual(s * m, expected) let (value, pb) = valueWithPullback(at: s, m) { $0 * $1 } XCTAssertEqual(value, expected) for (i, b) in Matrix3x2.standardBasis.enumerated() { XCTAssertEqual(pb(b).0, Double(i)) XCTAssertEqual(pb(b).1, s * b) } } func testDivide() { let m = Matrix3x2([0, 10, 20, 30, 40, 50]) let s: Double = 10 let expected = Matrix3x2([0, 1, 2, 3, 4, 5]) XCTAssertEqual(m / s, expected) let (value, pb) = valueWithPullback(at: m, s) { $0 / $1 } XCTAssertEqual(value, expected) for (i, b) in Matrix3x2.standardBasis.enumerated() { XCTAssertEqual(pb(b).0, b / s) XCTAssertEqual(pb(b).1, -Double(i) / 10, accuracy: 1e-10) } } func testDot() { let m1 = Matrix2([1, 2, 3, 4]) let m2 = Matrix2([1, 10, 100, 1000]) XCTAssertEqual(m1.dot(m2), 4321) let (value, grad) = valueWithGradient(at: m1, m2) { $0.dot($1) } XCTAssertEqual(value, 4321) XCTAssertEqual(grad.0, m2) XCTAssertEqual(grad.1, m1) } func testDimension() { XCTAssertEqual(Matrix3.dimension, 9) XCTAssertEqual(Matrix3x2.dimension, 6) XCTAssertEqual(Matrix3x2_3x3.dimension, 15) } func testIsSquare() { XCTAssertEqual(Matrix3.isSquare, true) XCTAssertEqual(Matrix3x2.isSquare, false) XCTAssertEqual(Matrix3x2_3x3.isSquare, false) } func testOuterProduct() { let v1 = Vector2(1, 2) let v2 = Vector2(10, 100) XCTAssertEqual( Matrix2(outerProduct: v1, v2), Matrix2([ 10, 100, 20, 200 ]) ) } func testTransposed() { let m = Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ) let expected = Matrix3( 0, 3, 6, 1, 4, 7, 2, 5, 8 ) XCTAssertEqual(m.transposed(), expected) let (value, pb) = valueWithPullback(at: m) { $0.transposed() } XCTAssertEqual(value, expected) for b in Matrix3.standardBasis { XCTAssertEqual(pb(b), b.transposed()) } } func testMatVec() { let m = Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ) let v = Vector3(1, 10, 100) let expected = Vector3(210, 543, 876) XCTAssertEqual(matvec(m, v), expected) let (value, pb) = valueWithPullback(at: m, v) { matvec($0, $1) } XCTAssertEqual(value, expected) XCTAssertEqual( pb(Vector3(1, 0, 0)).0, Matrix3( 1, 10, 100, 0, 0, 0, 0, 0, 0 ) ) XCTAssertEqual( pb(Vector3(0, 1, 0)).0, Matrix3( 0, 0, 0, 1, 10, 100, 0, 0, 0 ) ) XCTAssertEqual( pb(Vector3(0, 0, 1)).0, Matrix3( 0, 0, 0, 0, 0, 0, 1, 10, 100 ) ) XCTAssertEqual(pb(Vector3(1, 0, 0)).1, Vector3(0, 1, 2)) XCTAssertEqual(pb(Vector3(0, 1, 0)).1, Vector3(3, 4, 5)) XCTAssertEqual(pb(Vector3(0, 0, 1)).1, Vector3(6, 7, 8)) } func testMatMul() { let m1 = Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ) let m2 = Matrix3( 1, 10, 100, 10, 100, 1, 100, 1, 10 ) let expected = Matrix3( 210, 102, 021, 543, 435, 354, 876, 768, 687 ) XCTAssertEqual(matmul(m1, m2), expected) let (value, pb) = valueWithPullback(at: m1, m2) { matmul($0, $1) } XCTAssertEqual(value, expected) XCTAssertEqual( pb(Matrix3( 1, 0, 0, 0, 0, 0, 0, 0, 0 )).0, Matrix3( 1, 10, 100, 0, 0, 0, 0, 0, 0 ) ) XCTAssertEqual( pb(Matrix3( 1, 0, 0, 0, 0, 0, 0, 0, 0 )).1, Matrix3( 0, 0, 0, 1, 0, 0, 2, 0, 0 ) ) } func testKeyPathIterable() { let m1 = Matrix3x2([0, 1, 2, 3, 4, 5]) XCTAssertEqual( m1.allKeyPaths(to: Double.self).map { m1[keyPath: $0] }, [0, 1, 2, 3, 4, 5] ) } func testCustomStringConvertible() { XCTAssertEqual( Matrix2([1, 2, 3, 4]).description, "Matrix(Vector2(x: 1.0, y: 2.0), Vector2(x: 3.0, y: 4.0))" ) } }
apache-2.0
9d0d470e77c79c3bdb92329ac6262a07
25.114706
99
0.573375
2.960654
false
true
false
false
ray3132138/TestKitchen_1606
TestKitchen/TestKitchen/classes/cookbook/recommend/model/CBRecommendModel.swift
1
4530
// // CBRecommendModel.swift // TestKitchen // // Created by qianfeng on 16/8/16. // Copyright © 2016年 ray. All rights reserved. // import UIKit import SwiftyJSON class CBRecommendModel: NSObject { var code: NSNumber? var msg: Bool? var version: String? var timestamp: NSNumber? var data: CBRecommendDataModel? //解析 class func parseModel(data: NSData)->CBRecommendModel{ let model = CBRecommendModel() let jsonData = JSON(data:data) model.code = jsonData["code"].number model.msg = jsonData["msg"].bool model.version = jsonData["version"].string model.timestamp = jsonData["timestamp"].number let dataDict = jsonData["data"] model.data = CBRecommendDataModel.parseModel(dataDict) return model } } class CBRecommendDataModel: NSObject { var banner: Array<CBRecommendBannerModel>? var widgetList: Array<CBRecommendWidgetListModel>? class func parseModel(jsonData: JSON)->CBRecommendDataModel{ let model = CBRecommendDataModel() let bannerArray = jsonData["banner"] var bArray = Array<CBRecommendBannerModel>() for (_, subjson) in bannerArray{ //subjson 是转换成CBRecommendBannerModel类型对象 let bannerModel = CBRecommendBannerModel.parseModel(subjson) bArray.append(bannerModel) } model.banner = bArray let listArray = jsonData["widgetList"] var wlArray = Array<CBRecommendWidgetListModel>() for (_, subjson) in listArray{ //sunjson解析成CBRecommendWidgetListModel类型的对象 let wlModel = CBRecommendWidgetListModel.parseModel(subjson) wlArray.append(wlModel) } model.widgetList = wlArray return model } } class CBRecommendBannerModel: NSObject { var banner_id: NSNumber? var banner_title: String? var banner_picture: String? var banner_link: String? var is_link: NSNumber? var refer_key: NSNumber? var type_id: NSNumber? class func parseModel(jsonData: JSON)->CBRecommendBannerModel{ let model = CBRecommendBannerModel() model.banner_id = jsonData["banner_id"].number model.banner_title = jsonData["banner_title"].string model.banner_picture = jsonData["banner_picture"].string model.banner_link = jsonData["banner_link"].string model.is_link = jsonData["is_link"].number model.refer_key = jsonData["refer_key"].number model.type_id = jsonData["type_id"].number return model } } class CBRecommendWidgetListModel: NSObject { var widget_id: NSNumber? var widget_type: NSNumber? var title: String? var title_link: String? var desc: String? var widget_data: Array<CBRecommendWidgetDataModel>? class func parseModel(jsonData: JSON) -> CBRecommendWidgetListModel{ let model = CBRecommendWidgetListModel() model.widget_id = jsonData["widget_id"].number model.widget_type = jsonData["widget_type"].number model.title = jsonData["title"].string model.title_link = jsonData["title_link"].string model.desc = jsonData["desc"].string let dataArray = jsonData["widget_data"] var wdArray = Array<CBRecommendWidgetDataModel>() for (_, subjson) in dataArray{ //subjson let wdModel = CBRecommendWidgetDataModel.parseModel(subjson) wdArray.append(wdModel) } model.widget_data = wdArray return model } } class CBRecommendWidgetDataModel: NSObject { var id: NSNumber? var type: String? var content: String? var link: String? class func parseModel(jsonData: JSON)->CBRecommendWidgetDataModel{ let model = CBRecommendWidgetDataModel() model.id = jsonData["id"].number model.type = jsonData["type"].string model.content = jsonData["content"].string model.link = jsonData["link"].string return model } }
mit
2ce47d51740ff386882cf491775e276b
23.145161
72
0.586284
4.962431
false
false
false
false
karstengresch/rw_studies
Countidon/Countidon/CounterView.swift
1
2622
// // CounterView.swift // Countidon // // Created by Karsten Gresch on 19.09.15. // Copyright © 2015 Closure One. All rights reserved. // import UIKit let NumberOfGlasses = 8 let π: CGFloat = CGFloat(M_PI) @IBDesignable class CounterView: UIView { @IBInspectable var counter: Int = 0 { didSet { if counter <= NumberOfGlasses { setNeedsDisplay() } } } @IBInspectable var outlineColor: UIColor = UIColor.blue @IBInspectable var counterColor: UIColor = UIColor.orange /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. */ override func draw(_ rect: CGRect) { // center let center = CGPoint(x: bounds.width/2, y: bounds.height/2) let radius: CGFloat = max(bounds.width/2, bounds.height/2) let arcWidth: CGFloat = 50 let startAngle: CGFloat = 3 * π / 4 let endAngle: CGFloat = π / 4 let path = UIBezierPath(arcCenter: center, radius: radius/2, startAngle: startAngle, endAngle: endAngle, clockwise: true) path.lineWidth = arcWidth counterColor.setStroke() path.stroke() // Outline let angleDifference: CGFloat = 2 * π - startAngle + endAngle let arcLengthPerGlass = angleDifference / CGFloat(NumberOfGlasses) let outlineEndAngle = arcLengthPerGlass * CGFloat(counter) + startAngle let outlinePath = UIBezierPath(arcCenter: center, radius: bounds.width/2.79, startAngle: startAngle, endAngle: outlineEndAngle, clockwise: true) outlinePath.addArc(withCenter: center, radius: bounds.width/2 - arcWidth*1.69 + 2.5, startAngle: outlineEndAngle, endAngle: startAngle, clockwise: false) outlinePath.close() outlineColor.setStroke() outlinePath.lineWidth = 2.0 outlinePath.stroke() // glasses drunken markers let context = UIGraphicsGetCurrentContext() // 1 save state context?.saveGState() outlineColor.setFill() let markerWidth: CGFloat = 5.0 let markerSize: CGFloat = 10.0 // marker top left let markerPath = UIBezierPath(rect: CGRect(x: -markerWidth/2, y: -10.5*π, width: markerWidth, height: markerSize)) context?.translateBy(x: rect.width/2, y: rect.height/2) for i in 1...NumberOfGlasses { context?.saveGState() let angle = arcLengthPerGlass * CGFloat(i) + startAngle - π/2 context?.rotate(by: angle) context?.translateBy(x: 0, y: rect.height/2 - markerSize) markerPath.fill() context?.restoreGState() } context?.restoreGState() } }
unlicense
57b096c14f26670279b36fb95de4e311
29.057471
157
0.671128
4.21095
false
false
false
false
tripleCC/GanHuoCode
GanHuo/Controllers/Category/TPCSubCategoryViewController.swift
1
4306
// // TPCSubCategoryViewController.swift // GanHuo // // Created by tripleCC on 16/3/1. // Copyright © 2016年 tripleCC. All rights reserved. // import UIKit import CoreData class TPCSubCategoryViewController: UIViewController { var collectionView: TPCCollectionView! var dataSource: TPCCategoryDataSource! var categoryTitle: String? override func viewDidLoad() { super.viewDidLoad() setupSubviews() } override func loadView() { let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 0 view = TPCCollectionView(frame: UIScreen.mainScreen().bounds, collectionViewLayout: layout) } private func setupSubviews() { let reuseIdentifier = "GanHuoCategoryCell" collectionView = view as! TPCCollectionView collectionView.registerNib(UINib(nibName: String(TPCCategoryViewCell.self), bundle: nil), forCellWithReuseIdentifier: reuseIdentifier) collectionView.registerNib(UINib(nibName: String(TPCLoadMoreReusableView.self), bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: String(TPCLoadMoreReusableView.self)) collectionView.delegate = self dataSource = TPCCategoryDataSource(collectionView: collectionView, reuseIdentifier: reuseIdentifier) dataSource.delegate = self dataSource.categoryTitle = categoryTitle collectionView.dataSource = dataSource } } extension TPCSubCategoryViewController: TPCCategoryDataSourceDelegate { func renderCell(cell: UIView, withObject object: AnyObject?) { // 这种后台上下文队列中的实体在主队列中访问是不可取的,需要通过objectID传递,但是暂时没问题,先这么用着吧。。。 if let o = object as? GanHuoObject { let cell = cell as! TPCCategoryViewCell cell.ganhuo = o } } } extension TPCSubCategoryViewController: UICollectionViewDelegateFlowLayout { func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { dataSource.fetchGanHuoByIndexPath(indexPath) { (ganhuo) -> () in ganhuo.read = true let url = ganhuo.url dispatchAMain { if let url = url { self.pushToBrowserViewControllerWithURLString(url, ganhuo: ganhuo) } self.collectionView.reloadItemsAtIndexPaths([indexPath]) } TPCCoreDataManager.shareInstance.saveContext() } } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { if let height = dataSource.technicals[indexPath.row].cellHeight { return CGSize(width: view.bounds.width, height: CGFloat(height.floatValue)) } return CGSize(width: view.bounds.width, height: TPCCategoryViewCell.cellHeightWithGanHuo(dataSource.technicals[indexPath.row])) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { return CGSize(width: view.bounds.width, height: TPCConfiguration.technicalFooterViewHeight) } } extension TPCSubCategoryViewController: UIScrollViewDelegate { func scrollViewDidScroll(scrollView: UIScrollView) { if scrollView.contentOffset.y < 0 { let scale = (abs(scrollView.contentOffset.y)) / TPCRefreshControlOriginHeight collectionView.adjustRefreshViewWithScale(scale) } } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { if collectionView.refreshing() { dataSource.loadNewData() } } func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if let indexPath = collectionView.indexPathForItemAtPoint(CGPoint(x: 1, y: targetContentOffset.memory.y)) { if Double(indexPath.row) >= Double(dataSource.technicals.count) - Double(TPCLoadGanHuoDataOnce) * 0.7 { dataSource.loadMoreData() } } } }
mit
0b2023469f51c1ee7813af7c57e3b7a8
41.908163
226
0.708442
5.309343
false
false
false
false
natecook1000/swift
test/SILGen/metatypes.swift
2
4284
// RUN: %target-swift-emit-silgen -parse-stdlib -enable-sil-ownership %s | %FileCheck %s import Swift protocol SomeProtocol { func method() func static_method() } protocol A {} struct SomeStruct : A {} class SomeClass : SomeProtocol { func method() {} func static_method() {} } class SomeSubclass : SomeClass {} // CHECK-LABEL: sil hidden @$S9metatypes07static_A0{{[_0-9a-zA-Z]*}}F func static_metatypes() -> (SomeStruct.Type, SomeClass.Type, SomeClass.Type) { // CHECK: [[STRUCT:%[0-9]+]] = metatype $@thin SomeStruct.Type // CHECK: [[CLASS:%[0-9]+]] = metatype $@thick SomeClass.Type // CHECK: [[SUBCLASS:%[0-9]+]] = metatype $@thick SomeSubclass.Type // CHECK: [[SUBCLASS_UPCAST:%[0-9]+]] = upcast [[SUBCLASS]] : ${{.*}} to $@thick SomeClass.Type // CHECK: tuple ([[STRUCT]] : {{.*}}, [[CLASS]] : {{.*}}, [[SUBCLASS_UPCAST]] : {{.*}}) return (SomeStruct.self, SomeClass.self, SomeSubclass.self) } // CHECK-LABEL: sil hidden @$S9metatypes07struct_A0{{[_0-9a-zA-Z]*}}F func struct_metatypes(s: SomeStruct) -> (SomeStruct.Type, SomeStruct.Type) { // CHECK: [[STRUCT1:%[0-9]+]] = metatype $@thin SomeStruct.Type // CHECK: [[STRUCT2:%[0-9]+]] = metatype $@thin SomeStruct.Type // CHECK: tuple ([[STRUCT1]] : {{.*}}, [[STRUCT2]] : {{.*}}) return (type(of: s), SomeStruct.self) } // CHECK-LABEL: sil hidden @$S9metatypes06class_A0{{[_0-9a-zA-Z]*}}F func class_metatypes(c: SomeClass, s: SomeSubclass) -> (SomeClass.Type, SomeClass.Type) { // CHECK: [[CLASS:%[0-9]+]] = value_metatype $@thick SomeClass.Type, // CHECK: [[SUBCLASS:%[0-9]+]] = value_metatype $@thick SomeSubclass.Type, // CHECK: [[SUBCLASS_UPCAST:%[0-9]+]] = upcast [[SUBCLASS]] : ${{.*}} to $@thick SomeClass.Type // CHECK: tuple ([[CLASS]] : {{.*}}, [[SUBCLASS_UPCAST]] : {{.*}}) return (type(of: c), type(of: s)) } // CHECK-LABEL: sil hidden @$S9metatypes010archetype_A0{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*T): func archetype_metatypes<T>(t: T) -> (T.Type, T.Type) { // CHECK: [[STATIC_T:%[0-9]+]] = metatype $@thick T.Type // CHECK: [[DYN_T:%[0-9]+]] = value_metatype $@thick T.Type, %0 // CHECK: tuple ([[STATIC_T]] : {{.*}}, [[DYN_T]] : {{.*}}) return (T.self, type(of: t)) } // CHECK-LABEL: sil hidden @$S9metatypes012existential_A0{{[_0-9a-zA-Z]*}}F func existential_metatypes(p: SomeProtocol) -> SomeProtocol.Type { // CHECK: existential_metatype $@thick SomeProtocol.Type return type(of: p) } struct SomeGenericStruct<T> {} func generic_metatypes<T>(x: T) -> (SomeGenericStruct<T>.Type, SomeGenericStruct<SomeStruct>.Type) { // CHECK: metatype $@thin SomeGenericStruct<T> // CHECK: metatype $@thin SomeGenericStruct<SomeStruct> return (SomeGenericStruct<T>.self, SomeGenericStruct<SomeStruct>.self) } // rdar://16610078 // CHECK-LABEL: sil hidden @$S9metatypes30existential_metatype_from_thinypXpyF : $@convention(thin) () -> @thick Any.Type // CHECK: [[T0:%.*]] = metatype $@thin SomeStruct.Type // CHECK-NEXT: [[T1:%.*]] = metatype $@thick SomeStruct.Type // CHECK-NEXT: [[T2:%.*]] = init_existential_metatype [[T1]] : $@thick SomeStruct.Type, $@thick Any.Type // CHECK-NEXT: return [[T2]] : $@thick Any.Type func existential_metatype_from_thin() -> Any.Type { return SomeStruct.self } // CHECK-LABEL: sil hidden @$S9metatypes36existential_metatype_from_thin_valueypXpyF : $@convention(thin) () -> @thick Any.Type // CHECK: [[T1:%.*]] = metatype $@thin SomeStruct.Type // CHECK: [[T0:%.*]] = function_ref @$S9metatypes10SomeStructV{{[_0-9a-zA-Z]*}}fC // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: debug_value [[T2]] : $SomeStruct, let, name "s" // CHECK-NEXT: [[T0:%.*]] = metatype $@thin SomeStruct.Type // CHECK-NEXT: [[T1:%.*]] = metatype $@thick SomeStruct.Type // CHECK-NEXT: [[T2:%.*]] = init_existential_metatype [[T1]] : $@thick SomeStruct.Type, $@thick Any.Type // CHECK-NEXT: return [[T2]] : $@thick Any.Type func existential_metatype_from_thin_value() -> Any.Type { let s = SomeStruct() return type(of: s) } // CHECK-LABEL: sil hidden @$S9metatypes20specialized_metatypeSDySSSiGyF // CHECK: metatype $@thin Dictionary<String, Int>.Type func specialized_metatype() -> Dictionary<String, Int> { let dict = Swift.Dictionary<Swift.String, Int>() return dict }
apache-2.0
291ace41d56b3e68eebd8481f736085f
37.945455
127
0.640289
3.326087
false
false
false
false
endpress/PopNetwork
PopNetwork/Source/SessionDelegate.swift
1
16568
// // SessionDelegate.swift // PopNetwork // // Created by apple on 12/8/16. // Copyright © 2016 zsc. All rights reserved. // import Foundation /// handling all delegate callbacks. class SessionDelegate: NSObject { /// A default instance of `SessionDelegate`. static let `default` = SessionDelegate() fileprivate var responses = [Int: Response]() private let lock = NSLock() subscript(task: URLSessionTask) -> Response? { get { lock.lock(); defer { lock.unlock() } return responses[task.taskIdentifier] } set { lock.lock(); defer { lock.unlock() } responses[task.taskIdentifier] = newValue } } } // MARK: - URLSessionDelegate extension SessionDelegate: URLSessionDelegate { /// Tells the delegate that the session has been invalidated. /// /// - parameter session: The session object that was invalidated. /// - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { } /// Requests credentials from the delegate in response to a session-level authentication request from the /// remote server. /// /// - parameter session: The session containing the task that requested authentication. /// - parameter challenge: An object that contains the request for authentication. /// - parameter completionHandler: A handler that your delegate method must call providing the disposition /// and credential. public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling var credential: URLCredential? if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { if let serverTrust = challenge.protectionSpace.serverTrust { disposition = .useCredential credential = URLCredential(trust: serverTrust) } else { disposition = .cancelAuthenticationChallenge } } completionHandler(disposition, credential) } #if !os(macOS) /// Tells the delegate that all messages enqueued for a session have been delivered. /// /// - parameter session: The session that no longer has any outstanding requests. public func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { } #endif } //MARK: - URLSessionTaskDelegate extension SessionDelegate: URLSessionTaskDelegate { /// Tells the delegate that the remote server requested an HTTP redirect. /// /// - parameter session: The session containing the task whose request resulted in a redirect. /// - parameter task: The task whose request resulted in a redirect. /// - parameter response: An object containing the server’s response to the original request. /// - parameter request: A URL request object filled out with the new location. /// - parameter completionHandler: A closure that your handler should call with either the value of the request /// parameter, a modified URL request object, or NULL to refuse the redirect and /// return the body of the redirect response. open func urlSession( _ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(nil) } /// Requests credentials from the delegate in response to an authentication request from the remote server. /// /// - parameter session: The session containing the task whose request requires authentication. /// - parameter task: The task whose request requires authentication. /// - parameter challenge: An object that contains the request for authentication. /// - parameter completionHandler: A handler that your delegate method must call providing the disposition /// and credential. open func urlSession( _ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling var credential: URLCredential? if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { if let serverTrust = challenge.protectionSpace.serverTrust { disposition = .useCredential credential = URLCredential(trust: serverTrust) } else { disposition = .cancelAuthenticationChallenge } } completionHandler(disposition, credential) } /// Tells the delegate when a task requires a new request body stream to send to the remote server. /// /// - parameter session: The session containing the task that needs a new body stream. /// - parameter task: The task that needs a new body stream. /// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. open func urlSession( _ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { } /// Periodically informs the delegate of the progress of sending body content to the server. /// /// - parameter session: The session containing the data task. /// - parameter task: The data task. /// - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. /// - parameter totalBytesSent: The total number of bytes sent so far. /// - parameter totalBytesExpectedToSend: The expected length of the body data. open func urlSession( _ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { } #if !os(watchOS) /// Tells the delegate that the session finished collecting metrics for the task. /// /// - parameter session: The session collecting the metrics. /// - parameter task: The task whose metrics have been collected. /// - parameter metrics: The collected metrics. @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { } #endif /// Tells the delegate that the task finished transferring data. /// /// - parameter session: The session containing the task whose request finished transferring data. /// - parameter task: The task whose request finished transferring data. /// - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let response = self[task], let dataHandler = response.dataHandler { if let _ = error { dataHandler(Result.Faliure(error: PopError.error(reason: "faliure"))) return } dataHandler(Result.Success(result: response.data!)) } } } //MARK: - URLSessionDataDelegate extension SessionDelegate: URLSessionDataDelegate { /// Tells the delegate that the data task received the initial reply (headers) from the server. /// /// - parameter session: The session containing the data task that received an initial reply. /// - parameter dataTask: The data task that received an initial reply. /// - parameter response: A URL response object populated with headers. /// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a /// constant to indicate whether the transfer should continue as a data task or /// should become a download task. open func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { let disposition: URLSession.ResponseDisposition = .allow if var resp = self[dataTask] { resp.response = response as? HTTPURLResponse self[dataTask] = resp } completionHandler(disposition) } /// Tells the delegate that the data task was changed to a download task. /// /// - parameter session: The session containing the task that was replaced by a download task. /// - parameter dataTask: The data task that was replaced by a download task. /// - parameter downloadTask: The new download task that replaced the data task. open func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didBecome downloadTask: URLSessionDownloadTask) { } /// Tells the delegate that the data task has received some of the expected data. /// /// - parameter session: The session containing the data task that provided data. /// - parameter dataTask: The data task that provided data. /// - parameter data: A data object containing the transferred data. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { if var response = self[dataTask] { response.data?.append(data) self[dataTask] = response } } /// Asks the delegate whether the data (or upload) task should store the response in the cache. /// /// - parameter session: The session containing the data (or upload) task. /// - parameter dataTask: The data (or upload) task. /// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current /// caching policy and the values of certain received headers, such as the Pragma /// and Cache-Control headers. /// - parameter completionHandler: A block that your handler must call, providing either the original proposed /// response, a modified version of that response, or NULL to prevent caching the /// response. If your delegate implements this method, it must call this completion /// handler; otherwise, your app leaks memory. open func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) { completionHandler(proposedResponse) } } // MARK: - URLSessionDownloadDelegate extension SessionDelegate: URLSessionDownloadDelegate { /// Tells the delegate that a download task has finished downloading. /// /// - parameter session: The session containing the download task that finished. /// - parameter downloadTask: The download task that finished. /// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either /// open the file for reading or move it to a permanent location in your app’s sandbox /// container directory before returning from this delegate method. open func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { } /// Periodically informs the delegate about the download’s progress. /// /// - parameter session: The session containing the download task. /// - parameter downloadTask: The download task. /// - parameter bytesWritten: The number of bytes transferred since the last time this delegate /// method was called. /// - parameter totalBytesWritten: The total number of bytes transferred so far. /// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length /// header. If this header was not provided, the value is /// `NSURLSessionTransferSizeUnknown`. open func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { } /// Tells the delegate that the download task has resumed downloading. /// /// - parameter session: The session containing the download task that finished. /// - parameter downloadTask: The download task that resumed. See explanation in the discussion. /// - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the /// existing content, then this value is zero. Otherwise, this value is an /// integer representing the number of bytes on disk that do not need to be /// retrieved again. /// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. /// If this header was not provided, the value is NSURLSessionTransferSizeUnknown. open func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { } } // MARK: - URLSessionStreamDelegate #if !os(watchOS) @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) extension SessionDelegate: URLSessionStreamDelegate { /// Tells the delegate that the read side of the connection has been closed. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) { } /// Tells the delegate that the write side of the connection has been closed. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) { } /// Tells the delegate that the system has determined that a better route to the host is available. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) { } /// Tells the delegate that the stream task has been completed and provides the unopened stream objects. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. /// - parameter inputStream: The new input stream. /// - parameter outputStream: The new output stream. open func urlSession( _ session: URLSession, streamTask: URLSessionStreamTask, didBecome inputStream: InputStream, outputStream: OutputStream) { } } #endif
apache-2.0
2f142661230f18cf7adbc266dac0f63c
45.002778
146
0.631906
5.856082
false
false
false
false
Johennes/firefox-ios
Utils/NotificationConstants.swift
1
1265
/* 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/. */ public let NotificationDataLoginDidChange = "Data:Login:DidChange" // add a property to allow the observation of firefox accounts public let NotificationFirefoxAccountChanged = "FirefoxAccountChangedNotification" public let NotificationFirefoxAccountDeviceRegistrationUpdated = "FirefoxAccountDeviceRegistrationUpdated" public let NotificationPrivateDataClearedHistory = "PrivateDataClearedHistoryNotification" // Fired when the user finishes navigating to a page and the location has changed public let NotificationOnLocationChange = "OnLocationChange" // Fired when a the page metadata extraction script has completed and is being passed back to the native client public let NotificationOnPageMetadataFetched = "OnPageMetadataFetched" // Fired when the login synchronizer has finished applying remote changes public let NotificationDataRemoteLoginChangesWereApplied = "NotificationDataRemoteLoginChangesWereApplied" // MARK: Notification UserInfo Keys public let NotificationUserInfoKeyHasSyncableAccount = "NotificationUserInfoKeyHasSyncableAccount"
mpl-2.0
3f58134c7af0ea8259ef9b0145f00c38
51.75
111
0.837154
5.382979
false
false
false
false
huangboju/Moots
Examples/SwiftUI/Scrumdinger/Scrumdinger/Models/SpeechRecognizer.swift
1
4301
/* See LICENSE folder for this sample’s licensing information. */ import AVFoundation import Foundation import Speech import SwiftUI /// A helper for transcribing speech to text using AVAudioEngine. struct SpeechRecognizer { private class SpeechAssist { var audioEngine: AVAudioEngine? var recognitionRequest: SFSpeechAudioBufferRecognitionRequest? var recognitionTask: SFSpeechRecognitionTask? let speechRecognizer = SFSpeechRecognizer() deinit { reset() } func reset() { recognitionTask?.cancel() audioEngine?.stop() audioEngine = nil recognitionRequest = nil recognitionTask = nil } } private let assistant = SpeechAssist() /** Begin transcribing audio. Creates a `SFSpeechRecognitionTask` that transcribes speech to text until you call `stopRecording()`. The resulting transcription is continuously written to the provided text binding. - Parameters: - speech: A binding to a string where the transcription is written. */ func record(to speech: Binding<String>) { relay(speech, message: "Requesting access") canAccess { authorized in guard authorized else { relay(speech, message: "Access denied") return } relay(speech, message: "Access granted") assistant.audioEngine = AVAudioEngine() guard let audioEngine = assistant.audioEngine else { fatalError("Unable to create audio engine") } assistant.recognitionRequest = SFSpeechAudioBufferRecognitionRequest() guard let recognitionRequest = assistant.recognitionRequest else { fatalError("Unable to create request") } recognitionRequest.shouldReportPartialResults = true do { relay(speech, message: "Booting audio subsystem") let audioSession = AVAudioSession.sharedInstance() try audioSession.setCategory(.record, mode: .measurement, options: .duckOthers) try audioSession.setActive(true, options: .notifyOthersOnDeactivation) let inputNode = audioEngine.inputNode relay(speech, message: "Found input node") let recordingFormat = inputNode.outputFormat(forBus: 0) inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in recognitionRequest.append(buffer) } relay(speech, message: "Preparing audio engine") audioEngine.prepare() try audioEngine.start() assistant.recognitionTask = assistant.speechRecognizer?.recognitionTask(with: recognitionRequest) { (result, error) in var isFinal = false if let result = result { relay(speech, message: result.bestTranscription.formattedString) isFinal = result.isFinal } if error != nil || isFinal { audioEngine.stop() inputNode.removeTap(onBus: 0) self.assistant.recognitionRequest = nil } } } catch { print("Error transcibing audio: " + error.localizedDescription) assistant.reset() } } } /// Stop transcribing audio. func stopRecording() { assistant.reset() } private func canAccess(withHandler handler: @escaping (Bool) -> Void) { SFSpeechRecognizer.requestAuthorization { status in if status == .authorized { AVAudioSession.sharedInstance().requestRecordPermission { authorized in handler(authorized) } } else { handler(false) } } } private func relay(_ binding: Binding<String>, message: String) { DispatchQueue.main.async { binding.wrappedValue = message } } }
mit
c1a1a00f3c9c9cf2f7445430b9bf732d
34.825
140
0.577809
6.141429
false
false
false
false
flovouin/AsyncDisplayKit
examples_extra/ASDKgram-Swift/ASDKgram-Swift/PhotoFeedTableNodeController.swift
5
3905
// // PhotoFeedTableNodeController.swift // ASDKgram-Swift // // Created by Calum Harris on 06/01/2017. // // Copyright (c) 2014-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // 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 // FACEBOOK 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 AsyncDisplayKit class PhotoFeedTableNodeController: ASViewController<ASTableNode> { var activityIndicator: UIActivityIndicatorView! var photoFeed: PhotoFeedModel init() { photoFeed = PhotoFeedModel(initWithPhotoFeedModelType: .photoFeedModelTypePopular, requiredImageSize: screenSizeForWidth) super.init(node: ASTableNode()) self.navigationItem.title = "ASDK" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupActivityIndicator() node.allowsSelection = false node.view.separatorStyle = .none node.dataSource = self node.delegate = self node.view.leadingScreensForBatching = 2.5 navigationController?.hidesBarsOnSwipe = true } // helper functions func setupActivityIndicator() { let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) self.activityIndicator = activityIndicator let bounds = self.node.frame var refreshRect = activityIndicator.frame refreshRect.origin = CGPoint(x: (bounds.size.width - activityIndicator.frame.size.width) / 2.0, y: (bounds.size.height - activityIndicator.frame.size.height) / 2.0) activityIndicator.frame = refreshRect self.node.view.addSubview(activityIndicator) } var screenSizeForWidth: CGSize = { let screenRect = UIScreen.main.bounds let screenScale = UIScreen.main.scale return CGSize(width: screenRect.size.width * screenScale, height: screenRect.size.width * screenScale) }() func fetchNewBatchWithContext(_ context: ASBatchContext?) { activityIndicator.startAnimating() photoFeed.updateNewBatchOfPopularPhotos() { additions, connectionStatus in switch connectionStatus { case .connected: self.activityIndicator.stopAnimating() self.addRowsIntoTableNode(newPhotoCount: additions) context?.completeBatchFetching(true) case .noConnection: self.activityIndicator.stopAnimating() if context != nil { context!.completeBatchFetching(true) } break } } } func addRowsIntoTableNode(newPhotoCount newPhotos: Int) { let indexRange = (photoFeed.photos.count - newPhotos..<photoFeed.photos.count) let indexPaths = indexRange.map { IndexPath(row: $0, section: 0) } node.insertRows(at: indexPaths, with: .none) } } extension PhotoFeedTableNodeController: ASTableDataSource, ASTableDelegate { func tableNode(_ tableNode: ASTableNode, numberOfRowsInSection section: Int) -> Int { return photoFeed.numberOfItemsInFeed } func tableNode(_ tableNode: ASTableNode, nodeBlockForRowAt indexPath: IndexPath) -> ASCellNodeBlock { let photo = photoFeed.photos[indexPath.row] let nodeBlock: ASCellNodeBlock = { _ in return PhotoTableNodeCell(photoModel: photo) } return nodeBlock } func shouldBatchFetchForCollectionNode(collectionNode: ASCollectionNode) -> Bool { return true } func tableNode(_ tableNode: ASTableNode, willBeginBatchFetchWith context: ASBatchContext) { fetchNewBatchWithContext(context) } }
bsd-3-clause
824fd9d69972a9cb314220882ace9a23
33.866071
166
0.762356
4.034091
false
false
false
false
Salt7900/belly_codechallenge
belly_cc/Reachability.swift
1
1865
// The MIT License (MIT) // // Copyright (c) 2015 Isuru Nanayakkara // // 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 SystemConfiguration func connectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { return false } var flags : SCNetworkReachabilityFlags = [] if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { return false } let isReachable = flags.contains(.Reachable) let needsConnection = flags.contains(.ConnectionRequired) return (isReachable && !needsConnection) }
mit
7866aec58294ac70d4028af7fdb0473a
40.466667
81
0.738874
4.895013
false
false
false
false
KellenYangs/KLSwiftTest_05_05
CoreGraphicsTest/CoreGraphicsTest/ViewController.swift
1
3277
// // ViewController.swift // CoreGraphicsTest // // Created by bcmac3 on 16/5/26. // Copyright © 2016年 KellenYangs. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var medalView: MedalView! @IBOutlet weak var containerView: UIView! @IBOutlet weak var counterView: CounterView! @IBOutlet weak var counterLabel: UILabel! @IBOutlet weak var graphView: GraphView! @IBOutlet weak var averageWaterDrunk: UILabel! @IBOutlet weak var maxLabel: UILabel! var isGraphViewShowing: Bool = false func checkTotal() { if counterView.counter >= 8 { medalView.showMedal(true) } else { medalView.showMedal(false) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. counterLabel.text = "\(counterView.counter)" checkTotal() } @IBAction func btnPushButton(sender: PushButtonView) { if sender.isAddButton { if counterView.counter < NoOfGlasses { counterView.counter += 1 } } else { if counterView.counter > 0 { counterView.counter -= 1 } } counterLabel.text = "\(counterView.counter)" checkTotal() } @IBAction func containerViewTap(sender: UITapGestureRecognizer) { if isGraphViewShowing { UIView.transitionFromView(graphView, toView: counterView, duration: 1.0, options: [.TransitionFlipFromLeft, .ShowHideTransitionViews], completion: nil) } else { UIView.transitionFromView(counterView, toView: graphView, duration: 1.0, options: [.TransitionFlipFromRight, .ShowHideTransitionViews], completion: nil) setupGraphDisplay() } isGraphViewShowing = !isGraphViewShowing } func setupGraphDisplay() { graphView.graphPoints[graphView.graphPoints.count - 1] = counterView.counter graphView.setNeedsDisplay() maxLabel.text = "\(graphView.graphPoints.maxElement()!)" let average = graphView.graphPoints.reduce(0, combine: +) / graphView.graphPoints.count averageWaterDrunk.text = "\(average)" let calendar = NSCalendar.currentCalendar() let componentOptions: NSCalendarUnit = .Weekday let components = calendar.components(componentOptions, fromDate: NSDate()) var weekday = components.weekday let days = ["一", "二", "三", "四", "五", "六", "七"] for i in (1...days.count).reverse() { print("\(i) - \(weekday)") if let labelView = graphView.viewWithTag(i) as? UILabel { if weekday == 7 { weekday = 0 } labelView.text = days[weekday] weekday -= 1 if weekday < 0 { weekday = days.count - 1 } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
2086b470d0131d052765fabaeabd059a
30.047619
164
0.585583
4.917044
false
false
false
false
coolsamson7/inject
Inject/collections/IdentityMap.swift
1
1444
// // IdentityMap.swift // Inject // // Created by Andreas Ernst on 18.07.16. // Copyright © 2016 Andreas Ernst. All rights reserved. // import Foundation open class ObjectIdentityKey: Hashable { // MARK: instance data fileprivate var object: AnyObject fileprivate var hash: Int // init public init(object: AnyObject) { self.object = object self.hash = Unmanaged.passUnretained(object).toOpaque().hashValue } // Hashable open var hashValue: Int { get { return hash } } } public func ==(lhs: ObjectIdentityKey, rhs: ObjectIdentityKey) -> Bool { return lhs.object === rhs.object } open class IdentitySet<T:AnyObject> { // MARK: instance data fileprivate var set = Set<ObjectIdentityKey>() // MARK: public open func insert(_ object: T) -> Void { set.insert(ObjectIdentityKey(object: object)) } open func contains(_ object: T) -> Bool { return set.contains(ObjectIdentityKey(object: object)) } } open class IdentityMap<K:AnyObject, V:AnyObject> { // MARK: instance data fileprivate var map = [ObjectIdentityKey: V]() // MARK: public subscript(key: K) -> V? { get { return map[ObjectIdentityKey(object: key)] } set { map[ObjectIdentityKey(object: key)] = newValue } } }
mit
549cc328917260633a95f6dbafcbb600
19.913043
73
0.587665
4.320359
false
false
false
false
omarojo/MyC4FW
Pods/C4/C4/UI/Animation.swift
2
6501
// Copyright © 2014 C4 // // 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 private let AnimationCompletedEvent = "C4AnimationCompleted" private let AnimationCancelledEvent = "C4AnimationCancelled" /// Defines an object that handles the creation of animations for specific actions and keys. public class Animation { /// Specifies the supported animation curves. /// /// ```` /// animation.curve = .EaseIn /// ```` public enum Curve { /// A linear animation curve causes an animation to occur evenly over its duration. case Linear /// An ease-out curve causes the animation to begin quickly, and then slow down as it completes. case EaseOut /// An ease-in curve causes the animation to begin slowly, and then speed up as it progresses. case EaseIn /// An ease-in ease-out curve causes the animation to begin slowly, accelerate through the middle of its duration, and then slow again before completing. This is the default curve for most animations. case EaseInOut } /// Determines if the animation plays in the reverse upon completion. public var autoreverses = false /// Specifies the number of times the animation should repeat. public var repeatCount = 0.0 /// If `true` the animation will repeat indefinitely. public var repeats: Bool { get { return repeatCount > 0 } set { if newValue { repeatCount = DBL_MAX } else { repeatCount = 0 } } } /// The duration of the animation, measured in seconds. public var duration: TimeInterval = 1 /// The animation curve that the receiver will apply to the changes it is supposed to animate. public var curve: Curve = .EaseInOut private var completionObservers: [AnyObject] = [] private var cancelObservers: [AnyObject] = [] static var stack = [Animation]() static var currentAnimation: Animation? { return stack.last } ///Intializes an empty animation object. public init() { } deinit { let nc = NotificationCenter.default for observer in completionObservers { nc.removeObserver(observer) } for observer in cancelObservers { nc.removeObserver(observer) } } /// Run the animation func animate() {} /// Adds a completion observer to an animation. /// /// The completion observer listens for the end of the animation then executes a specified block of code. /// /// - parameter action: a block of code to be executed at the end of an animation. /// /// - returns: the observer object. public func addCompletionObserver(_ action: @escaping () -> Void) -> AnyObject { let nc = NotificationCenter.default let observer = nc.addObserver(forName: NSNotification.Name(rawValue: AnimationCompletedEvent), object: self, queue: OperationQueue.current, using: { _ in action() }) completionObservers.append(observer) return observer } /// Removes a specified observer from an animation. /// /// - parameter observer: the observer object to remove. public func removeCompletionObserver(_ observer: AnyObject) { let nc = NotificationCenter.default nc.removeObserver(observer, name: NSNotification.Name(rawValue: AnimationCompletedEvent), object: self) } /// Posts a completion event. /// /// This method is triggered when an animation completes. This can be used in place of `addCompletionObserver` for objects outside the scope of the context in which the animation is created. public func postCompletedEvent() { DispatchQueue.main.async { NotificationCenter.default.post(name: Notification.Name(rawValue: AnimationCompletedEvent), object: self) } } /// Adds a cancel observer to an animation. /// /// The cancel observer listens for when an animation is canceled then executes a specified block of code. /// /// - parameter action: a block of code to be executed when an animation is canceled. /// /// - returns: the observer object. public func addCancelObserver(_ action: @escaping () -> Void) -> AnyObject { let nc = NotificationCenter.default let observer = nc.addObserver(forName: NSNotification.Name(rawValue: AnimationCancelledEvent), object: self, queue: OperationQueue.current, using: { _ in action() }) cancelObservers.append(observer) return observer } /// Removes a specified cancel observer from an animation. /// /// - parameter observer: the cancel observer object to remove. public func removeCancelObserver(_ observer: AnyObject) { let nc = NotificationCenter.default nc.removeObserver(observer, name: NSNotification.Name(rawValue: AnimationCancelledEvent), object: self) } /// Posts a cancellation event. /// /// This method is triggered when an animation is canceled. This can be used in place of `addCancelObserver` for objects outside the scope of the context in which the animation is created. public func postCancelledEvent() { DispatchQueue.main.async { NotificationCenter.default.post(name: Notification.Name(rawValue: AnimationCancelledEvent), object: self) } } }
mit
5bc7458c7e676f41163c9dcdb2f2558b
39.625
208
0.679538
4.99232
false
false
false
false
dimakura/SwanKit
Tests/SwanKitTests/Tensor/StorageSpec.swift
1
3569
import SSpec import SwanKit private func spec_SWKStorage_elementSize() { describe("elementSize") { it("is 1 for byte storage") { expect(SWKByteStorage(100).elementSize).to.eq(1) } it("is 2 for short storage") { expect(SWKShortStorage(100).elementSize).to.eq(2) } it("is 4 for int storage") { expect(SWKIntStorage(100).elementSize).to.eq(4) } it("is 8 for long storage") { expect(SWKLongStorage(100).elementSize).to.eq(8) } it("is 4 for float storage") { expect(SWKFloatStorage(100).elementSize).to.eq(4) } it("is 8 for double storage") { expect(SWKDoubleStorage(100).elementSize).to.eq(8) } } } private func spec_SWKStorage_size() { describe("size") { context("when initialized with size = 100") { let storage = SWKIntStorage(100) it("is 100") { expect(storage.size).to.eq(100) } } context("when initialized with array of size = 4") { let storage = SWKShortStorage([1, 2, 3, 4]) it("is 4") { expect(storage.size).to.eq(4) expect(storage[0]).to.eq(1) expect(storage[1]).to.eq(2) expect(storage[2]).to.eq(3) expect(storage[3]).to.eq(4) } } } } private func spec_SWKStorage_device() { describe("device") { it("is default device") { expect(SWKIntStorage(10).device).to.eq(SWKConfig.currentDevice) } func testSettingDevice(device: SWKDevice) { context("when device is set to \(device)") { let storage = SWKIntStorage(10) storage.device = device it("is \(device)") { expect(storage.device).to.eq(device) } it("is \(device.isCPU ? "" : "not ")CPU") { expect(storage.isCPU).to.eq(device.isCPU) } it("is \(device.isGPU ? "" : "not ")GPU") { expect(storage.isGPU).to.eq(device.isGPU) } } } testSettingDevice(device: .CPU) testSettingDevice(device: .Metal) testSettingDevice(device: .CUDA) } } private func spec_SWKStorage_subscript() { describe("storage [1, 2, 3, 4, 5]") { var storage: SWKIntStorage! before { storage = SWKIntStorage([1, 2, 3, 4, 5]) } it("has size 5") { expect(storage.size).to.eq(5) } it("has initial values") { for i in 0..<storage.size { let expectedValue = SWKInt(truncatingIfNeeded: i + 1) expect(storage[i]).to.eq(expectedValue) } } it("can update values") { storage[0] = 42 expect(storage[0]).to.eq(42) } } } private func spec_SWKStorage_conversions() { describe("cpu") { it("can convert storage to CPU") } describe("gpu") { it("can convert storage to GPU") } } private func spec_SWKStorage_fill_operations() { context("when filling with zeros") { var storage: SWKFloatStorage! before { storage = SWKFloatStorage(5) storage.zeros() } it("contains all zeros") { for i in 0..<5 { expect(storage[i]).to.eq(0) } } } describe("when filling with ones") { var storage: SWKFloatStorage! before { storage = SWKFloatStorage(5) storage.ones() } it("contains all ones") { for i in 0..<5 { expect(storage[i]).to.eq(1) } } } } func spec_SWKStorage() { describe("SWKStorage") { spec_SWKStorage_elementSize() spec_SWKStorage_size() spec_SWKStorage_device() spec_SWKStorage_subscript() spec_SWKStorage_conversions() spec_SWKStorage_fill_operations() } }
mit
8c90515abbdd5a9f31b3a99fc29b7d01
20.5
69
0.581956
3.370161
false
false
false
false
jpush/jchat-swift
JChat/Src/Utilites/3rdParty/RecordVoice/JCRecordVoiceHelper.swift
1
7119
// // JCRecordVoiceHelper.swift // JChatSwift // // Created by oshumini on 16/2/22. // Copyright © 2016年 HXHG. All rights reserved. // import UIKit import AVFoundation @objc public protocol JCRecordVoiceHelperDelegate: NSObjectProtocol { @objc optional func beyondLimit(_ time: TimeInterval) } fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } let maxRecordTime = 60.0 typealias CompletionCallBack = () -> Void class JCRecordVoiceHelper: NSObject { weak var delegate: JCRecordVoiceHelperDelegate? var stopRecordCompletion: CompletionCallBack? var startRecordCompleted: CompletionCallBack? var cancelledDeleteCompletion: CompletionCallBack? var recorder: AVAudioRecorder? var recordPath: String? var recordDuration: String? var recordProgress: Float? var theTimer: Timer? var currentTimeInterval: TimeInterval? weak var updateMeterDelegate: JCRecordingView? override init() { super.init() } deinit { stopRecord() recordPath = nil } @objc func updateMeters() { if recorder == nil { return } currentTimeInterval = recorder?.currentTime recordProgress = recorder?.peakPower(forChannel: 0) updateMeterDelegate?.setPeakPower(recordProgress!) updateMeterDelegate?.setTime(currentTimeInterval!) if currentTimeInterval > maxRecordTime { stopRecord() delegate?.beyondLimit?(currentTimeInterval!) if stopRecordCompletion != nil { DispatchQueue.main.async(execute: stopRecordCompletion!) recorder?.updateMeters() } } } func getVoiceDuration(_ recordPath:String) { do { let player:AVAudioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: recordPath)) player.play() self.recordDuration = "\(player.duration)" } catch let error as NSError { print("get AVAudioPlayer is fail \(error)") } } func resetTimer() { if theTimer == nil { return } else { theTimer!.invalidate() theTimer = nil } } func cancelRecording() { if recorder == nil { return } if recorder?.isRecording != false { recorder?.stop() } recorder = nil } func stopRecord() { cancelRecording() resetTimer() } func startRecordingWithPath(_ path:String, startRecordCompleted:@escaping CompletionCallBack) { print("Action - startRecordingWithPath:") self.startRecordCompleted = startRecordCompleted self.recordPath = path let audioSession:AVAudioSession = AVAudioSession.sharedInstance() do { if #available(iOS 10.0, *) { try audioSession.setCategory(AVAudioSession.Category.playAndRecord, mode: AVAudioSession.Mode.default, options: AVAudioSession.CategoryOptions.defaultToSpeaker) } else { // Fallback on earlier versions } } catch let error as NSError { print("could not set session category") print(error.localizedDescription) } do { try audioSession.setActive(true) } catch let error as NSError { print("could not set session active") print(error.localizedDescription) } let recordSettings:[String : AnyObject] = [ AVFormatIDKey: NSNumber(value: kAudioFormatAppleIMA4 as UInt32), AVNumberOfChannelsKey: 1 as AnyObject, AVSampleRateKey : 16000.0 as AnyObject ] do { self.recorder = try AVAudioRecorder(url: URL(fileURLWithPath: self.recordPath!), settings: recordSettings) self.recorder!.delegate = self self.recorder!.isMeteringEnabled = true self.recorder!.prepareToRecord() self.recorder?.record(forDuration: 160.0) } catch let error as NSError { recorder = nil print(error.localizedDescription) } if ((self.recorder?.record()) != false) { self.resetTimer() self.theTimer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(JCRecordVoiceHelper.updateMeters), userInfo: nil, repeats: true) } else { print("fail record") } if self.startRecordCompleted != nil { DispatchQueue.main.async(execute: self.startRecordCompleted!) } } func finishRecordingCompletion() { stopRecord() getVoiceDuration(recordPath!) if stopRecordCompletion != nil { DispatchQueue.main.async(execute: stopRecordCompletion!) } } func cancelledDeleteWithCompletion() { stopRecord() if recordPath != nil { let fileManager:FileManager = FileManager.default if fileManager.fileExists(atPath: recordPath!) == true { do { try fileManager.removeItem(atPath: recordPath!) } catch let error as NSError { print("can no to remove the voice file \(error.localizedDescription)") } } else { if cancelledDeleteCompletion != nil { DispatchQueue.main.async(execute: cancelledDeleteCompletion!) } } } } // test player func playVoice(_ recordPath:String) { do { print("\(recordPath)") let player:AVAudioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: recordPath)) player.volume = 1 player.delegate = self player.numberOfLoops = -1 player.prepareToPlay() player.play() } catch let error as NSError { print("get AVAudioPlayer is fail \(error)") } } } extension JCRecordVoiceHelper : AVAudioPlayerDelegate { func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { print("finished playing \(flag)") } func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) { if let e = error { print("\(e.localizedDescription)") } } } extension JCRecordVoiceHelper : AVAudioRecorderDelegate { } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromAVAudioSessionCategory(_ input: AVAudioSession.Category) -> String { return input.rawValue }
mit
ec54da9b2f2b9c6d8f0ca5c47eca6d9d
28.65
176
0.586987
5.201754
false
false
false
false
Macostik/StreamView
Source/List.swift
1
2717
// // List.swift // StreamView // // Created by Yura Granchenko on 4/11/17. // Copyright © 2017 Yura Granchenko. All rights reserved. // import Foundation public class List<T: Equatable> { public var sorter: (_ lhs: T, _ rhs: T) -> Bool = { _,_ in return true } convenience public init(sorter: @escaping (_ lhs: T, _ rhs: T) -> Bool) { self.init() self.sorter = sorter } public var entries = [T]() internal func _add(entry: T) -> Bool { if !entries.contains(entry) { entries.append(entry) return true } else { return false } } public func add(entry: T) { if _add(entry: entry) { sort() } } public func addEntries<S: Sequence>(entries: S) where S.Iterator.Element == T { let count = self.entries.count for entry in entries { let _ = _add(entry: entry) } if count != self.entries.count { sort() } } public func sort(entry: T) { let _ = _add(entry: entry) sort() } public func sort() { entries = entries.sorted(by: sorter) } public func remove(entry: T) { if let index = entries.index(of: entry) { entries.remove(at: index) } } public subscript(index: Int) -> T? { return (index >= 0 && index < count) ? entries[index] : nil } } public protocol BaseOrderedContainer { associatedtype ElementType var count: Int { get } subscript (safe index: Int) -> ElementType? { get } } extension Array: BaseOrderedContainer {} extension List: BaseOrderedContainer { public var count: Int { return entries.count } public subscript (safe index: Int) -> T? { return entries[safe: index] } } extension Array { public subscript (safe index: Int) -> Element? { return (index >= 0 && index < count) ? self[index] : nil } } extension Array where Element: Equatable { public mutating func remove(_ element: Element) { if let index = index(of: element) { self.remove(at: index) } } } extension Collection { public func all(_ enumerator: (Iterator.Element) -> Void) { for element in self { enumerator(element) } } public subscript (includeElement: (Iterator.Element) -> Bool) -> Iterator.Element? { for element in self where includeElement(element) == true { return element } return nil } } extension Dictionary { public func get<T>(_ key: Key) -> T? { return self[key] as? T } }
mit
208c1d6d96377b8c13b8b42d77783a09
22.016949
88
0.546024
3.994118
false
false
false
false
soapyigu/Swift30Projects
Project 04 - TodoTDD/ToDo/ViewControllers/InputViewController.swift
1
3070
// // InputViewController.swift // ToDo // // Created by Yi Gu on 5/4/19. // Copyright © 2019 gu, yi. All rights reserved. // import UIKit import CoreLocation class InputViewController: UIViewController { @IBOutlet var titleTextField: UITextField! @IBOutlet var locationTextField: UITextField! @IBOutlet var descriptionTextField: UITextField! @IBOutlet var datePicker: UIDatePicker! @IBOutlet var cancelButton: UIButton! @IBOutlet var saveButton: UIButton! lazy var geocoder = CLGeocoder() var itemManager: ToDoItemManager? override func viewDidLoad() { super.viewDidLoad() titleTextField.delegate = self locationTextField.delegate = self descriptionTextField.delegate = self } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } @IBAction func save() { guard let titleString = titleTextField.text, titleString.count > 0 else { return } // datePicker could be nil if the view controller is init via code var date: Date? if datePicker != nil { date = datePicker.date } // descriptionTextField could be nil if the view controller is init via code var descriptionString: String? if descriptionTextField != nil { descriptionString = descriptionTextField.text } // locationTextField could be nil if the view controller is init via code var placeMark: CLPlacemark? var locationName: String? if locationTextField != nil { locationName = locationTextField.text if let locationName = locationName, locationName.count > 0 { geocoder.geocodeAddressString(locationName) { [weak self] placeMarks, _ in placeMark = placeMarks?.first let item = ToDoItem(title: titleString, itemDescription: descriptionString, timeStamp: date?.timeIntervalSince1970, location: Location(name: locationName, coordinate: placeMark?.location?.coordinate)) DispatchQueue.main.async { self?.itemManager?.add(item) self?.dismiss(animated: true) } } } else { let item = ToDoItem(title: titleString, itemDescription: descriptionString, timeStamp: date?.timeIntervalSince1970, location: nil) self.itemManager?.add(item) dismiss(animated: true) } } else { let item = ToDoItem( title: titleString, itemDescription: descriptionString, timeStamp: date?.timeIntervalSince1970) self.itemManager?.add(item) dismiss(animated: true) } } @IBAction func cancel() { dismiss(animated: true, completion: nil) } } extension InputViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { resignFirstResponder() view.endEditing(true) return false } }
apache-2.0
d7d4776da4dc49c79d2977a6beb3b2ef
28.228571
114
0.637667
5.318891
false
false
false
false
zacswolf/CompSciProjects
Swift/MyPlayGrounds/tutorials/SubClassPlayground.playground/Contents.swift
1
771
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" class Person { var Name:String = "Initial Name" init(){ } func Walk(){ print("I'm Walking") } } var a = Person() a.Name = "Zachery" a.Walk() class subHuman:Person{ var NickName:String = "Zac" override init(){ //super.Name = "Super Duper" //Does not work super.init() super.Name = "Super Duper" // now works } func Fly(){ print("I'm Flying") } override func Walk(){ print("I am a subHuman walking") super.Walk() } } var 😀 = subHuman() //you can use emojjis 😀.Name 😀.Walk() 😀.Fly() 😀.NickName
mit
6b35943f7ae99d362c805019556eb52c
12.745455
52
0.515873
3.516279
false
false
false
false
soapyigu/Swift30Projects
Project 08 - SimpleRSSReader/SimpleRSSReader/FeedParser.swift
1
2932
// // FeedParser.swift // SimpleRSSReader // // Copyright © 2017 AppCoda. All rights reserved. // import Foundation class FeedParser: NSObject, XMLParserDelegate { fileprivate var rssItems = [(title: String, description: String, pubDate: String)]() fileprivate var currentElement = "" fileprivate var currentTitle = "" { didSet { currentTitle = currentTitle.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } } fileprivate var currentDescription = "" { didSet { currentDescription = currentDescription.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } } fileprivate var currentPubDate = "" { didSet { currentPubDate = currentPubDate.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } } fileprivate var parserCompletionHandler: (([(title: String, description: String, pubDate: String)]) -> Void)? func parseFeed(feedURL: String, completionHandler: (([(title: String, description: String, pubDate: String)]) -> Void)?) -> Void { parserCompletionHandler = completionHandler guard let feedURL = URL(string:feedURL) else { print("feed URL is invalid") return } URLSession.shared.dataTask(with: feedURL, completionHandler: { data, response, error in if let error = error { print(error) return } guard let data = data else { print("No data fetched") return } let parser = XMLParser(data: data) parser.delegate = self parser.parse() }).resume() } // MARK: - XMLParser Delegate func parserDidStartDocument(_ parser: XMLParser) { rssItems.removeAll() } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { currentElement = elementName if currentElement == "item" { currentTitle = "" currentDescription = "" currentPubDate = "" } } func parser(_ parser: XMLParser, foundCharacters string: String) { /// Note: current string may only contain part of info. switch currentElement { case "title": currentTitle += string case "description": currentDescription += string case "pubDate": currentPubDate += string default: break } } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if elementName == "item" { let rssItem = (title: currentTitle, description: currentDescription, pubDate: currentPubDate) rssItems.append(rssItem) } } func parserDidEndDocument(_ parser: XMLParser) { parserCompletionHandler?(rssItems) } func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) { print(parseError.localizedDescription) } }
apache-2.0
1eb2f3e2680bea8880c954db43b597b4
27.182692
177
0.665302
4.976231
false
false
false
false
KevinCoble/AIToolbox
iOS Playgrounds/ConnectFourAlphaBeta.playground/Sources/AlphaBeta.swift
3
8863
// // AlphaBeta.swift // AIToolbox // // Created by Kevin Coble on 2/23/15. // Copyright (c) 2015 Kevin Coble. All rights reserved. // import Foundation /// The AlphaBetaNode protocol is used to provide move generation and static evaluation routines to your node public protocol AlphaBetaNode { func generateMoves(_ forMaximizer: Bool) -> [AlphaBetaNode] // Get the nodes for each move below this node func staticEvaluation() -> Double // Evaluate the worth of this node } open class AlphaBetaGraph { public init() { } open func startAlphaBetaWithNode(_ startNode: AlphaBetaNode, forDepth: Int, startingAsMaximizer : Bool = true) -> AlphaBetaNode? { // Start the recursion let α = -Double.infinity let β = Double.infinity return alphaBeta(startNode, remainingDepth: forDepth, alpha: α, beta : β, maximizer: startingAsMaximizer, topLevel: true).winningNode } func alphaBeta(_ currentNode: AlphaBetaNode, remainingDepth: Int, alpha : Double, beta : Double, maximizer: Bool, topLevel : Bool) -> (value: Double, winningNode: AlphaBetaNode?) { // if this is a leaf node, return the static evaluation if (remainingDepth == 0) { return (value: currentNode.staticEvaluation(), winningNode: currentNode) } let nextDepth = remainingDepth - 1 // Generate the child nodes let children = currentNode.generateMoves(maximizer) // If no children, return the static evaluation for this node if (children.count == 0) { return (value: currentNode.staticEvaluation(), winningNode: currentNode) } if (topLevel && children.count == 1) { // Only one move, so we must take it - no reason to evaluate actual values return (value: 0.0, winningNode: children[0]) } var winningNode : AlphaBetaNode? var α = alpha var β = beta // If the maximizer, maximize the alpha, and prune with the beta if (maximizer) { var value = -Double.infinity // Iterate through the child nodes for child in children { let childValue = alphaBeta(child, remainingDepth: nextDepth, alpha: α, beta: β, maximizer: false, topLevel: false).value if (childValue > value) { value = childValue winningNode = child } value = childValue > value ? childValue : value α = value > α ? value : α if (β <= α) { // β pruning break } } return (value: value, winningNode: winningNode) } // If the minimizer, maximize the beta, and prune with the alpha else { var value = Double.infinity // Iterate through the child nodes for child in children { let childValue = alphaBeta(child, remainingDepth: nextDepth, alpha: α, beta: β, maximizer: true, topLevel: false).value if (childValue < value) { value = childValue winningNode = child } β = value < β ? value : β if (β <= α) { // α pruning break } } return (value: value, winningNode: winningNode) } } open func startAlphaBetaConcurrentWithNode(_ startNode: AlphaBetaNode, forDepth: Int, startingAsMaximizer : Bool = true) -> AlphaBetaNode? { // Start the recursion let α = -Double.infinity let β = Double.infinity return alphaBetaConcurrent(startNode, remainingDepth: forDepth, alpha: α, beta : β, maximizer: startingAsMaximizer, topLevel: true).winningNode } func alphaBetaConcurrent(_ currentNode: AlphaBetaNode, remainingDepth: Int, alpha : Double, beta : Double, maximizer: Bool, topLevel : Bool) -> (value: Double, winningNode: AlphaBetaNode?) { // if this is a leaf node, return the static evaluation if (remainingDepth == 0) { return (value: currentNode.staticEvaluation(), winningNode: currentNode) } let nextDepth = remainingDepth - 1 // Generate the child nodes let children = currentNode.generateMoves(maximizer) // If no children, return the static evaluation for this node if (children.count == 0) { return (value: currentNode.staticEvaluation(), winningNode: currentNode) } if (topLevel && children.count == 1) { // Only one move, so we must take it - no reason to evaluate actual values return (value: 0.0, winningNode: children[0]) } // Create the value array var childValues : [Double] = Array(repeating: 0.0, count: children.count) // Get the concurrent queue and group let tQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.default) let tGroup = DispatchGroup() var winningNode : AlphaBetaNode? var α = alpha var β = beta // If the maximizer, maximize the alpha, and prune with the beta if (maximizer) { // Process the first child without concurrency - the alpha-beta range returned allows pruning of the other trees var value = alphaBetaConcurrent(children[0], remainingDepth: nextDepth, alpha: α, beta: β, maximizer: false, topLevel: false).value winningNode = children[0] α = value > α ? value : α if (β <= α) { // β pruning return (value: value, winningNode: winningNode) } // Iterate through the rest of the child nodes if (children.count > 1) { for index in 1..<children.count { tQueue.async(group: tGroup, execute: {() -> Void in childValues[index] = self.alphaBetaConcurrent(children[index], remainingDepth: nextDepth, alpha: α, beta: β, maximizer: false, topLevel: false).value }) } // Wait for the evaluations tGroup.wait() // Prune and find best for index in 1..<children.count { if (childValues[index] > value) { value = childValues[index] winningNode = children[index] } value = childValues[index] > value ? childValues[index] : value α = value > α ? value : α if (β <= α) { // β pruning break } } } return (value: value, winningNode: winningNode) } // If the minimizer, maximize the beta, and prune with the alpha else { // Process the first child without concurrency - the alpha-beta range returned allows pruning of the other trees var value = alphaBetaConcurrent(children[0], remainingDepth: nextDepth, alpha: α, beta: β, maximizer: true, topLevel: false).value winningNode = children[0] β = value < β ? value : β if (β <= α) { // α pruning return (value: value, winningNode: winningNode) } // Iterate through the rest of the child nodes if (children.count > 1) { for index in 1..<children.count { tQueue.async(group: tGroup, execute: {() -> Void in childValues[index] = self.alphaBetaConcurrent(children[index], remainingDepth: nextDepth, alpha: α, beta: β, maximizer: true, topLevel: false).value }) } // Wait for the evaluations tGroup.wait() // Prune and find best for index in 1..<children.count { if (childValues[index] < value) { value = childValues[index] winningNode = children[index] } β = value < β ? value : β if (β <= α) { // α pruning break } } } return (value: value, winningNode: winningNode) } } }
apache-2.0
afa78cad602bb637761768a5a346cde3
40.720379
195
0.529479
4.831504
false
false
false
false
CWFred/RainMaker
RainMaker/ViewController.swift
1
2552
// // ViewController.swift // RainMaker // // Created by Jean Piard on 11/4/16. // Copyright © 2016 Jean Piard. All rights reserved. // import UIKit import Alamofire import SwiftyJSON var accessToken = "" var devices = [device]() var userNameInfo = "" var passwordInfo = "" class ViewController: UIViewController { @IBOutlet weak var userName: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var signInButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func SignIn(_ sender: Any) { userNameInfo = userName.text! passwordInfo = password.text! let parameters: Parameters = [ "login":userNameInfo, "password":passwordInfo,] Alamofire.request("http://ec2-54-84-46-40.compute-1.amazonaws.com:9000/login", method: .post,parameters :parameters).responseJSON { response in switch response.result { case .success(let value): let json = JSON(value) accessToken = json["accessToken"].stringValue print(json); for i in 0...(json["devices"].array?.count)!-1 { let name: String = json["devices"][i]["name"].stringValue let connected : String = json["devices"][i]["connected"].stringValue let lastIp : String = json["devices"][i]["last_ip_address"].stringValue let id : String = json["devices"][i]["id"].stringValue devices.append(device.init(name: name, connected: connected, lastIP: lastIp, ID: id)) } self.performSegue(withIdentifier: "SignInComplete", sender: self) case .failure(let error): print(error) } } } }
mit
6302287ccb0fa6b1aba06802597a0b39
30.8875
151
0.482556
5.668889
false
false
false
false
elsucai/Hummingbird
Hummingbird/TimelineViewController.swift
1
2513
// // TimelineViewController.swift // Hummingbird // // Created by Xiang Cai on 12/14/16. // Copyright © 2016 Xiang Cai. All rights reserved. // import UIKit import TwitterKit class TimelineViewController: TWTRTimelineViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. titleButton.layer.borderWidth = 1 titleButton.layer.cornerRadius = 6 titleButton.layer.borderColor = self.view.tintColor.cgColor prepareView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func prepareView() { let store = Twitter.sharedInstance().sessionStore let twtrSession = store.session() as? TWTRSession self.userName = (twtrSession?.userName)! if listSlug.isEmpty { self.dataSource = TWTRUserTimelineDataSource(screenName: self.userName, apiClient: client) } else { self.dataSource = TWTRListTimelineDataSource(listSlug: self.listSlug, listOwnerScreenName: self.listOwnerName, apiClient: client) } self.showTweetActions = true } let client = TWTRAPIClient() var userName = "" var listSlug = "" var listOwnerName = "" @IBOutlet weak var titleButton: UIButton! @IBAction func logOutButtonTapped(_ sender: UIBarButtonItem) { let store = Twitter.sharedInstance().sessionStore if let userID = store.session()?.userID { store.logOutUserID(userID) /* let cookieStorage: HTTPCookieStorage = HTTPCookieStorage.shared let cookies = cookieStorage.cookies //(for: URL(string: "https://api.twitter.com")!) for cookie in cookies! { cookieStorage.deleteCookie(cookie as HTTPCookie) } */ performSegue(withIdentifier: "showSignInController", sender: nil) } } @IBAction func didSelectRow(_ segue: UIStoryboardSegue) { self.viewDidLoad() } /* // 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. } */ }
gpl-3.0
1bb329e7d941dc9e5c5a7f8d45ef8854
32.052632
141
0.648089
5.013972
false
false
false
false
material-motion/motion-animator-objc
examples/apps/Catalog/Catalog/AppDelegate.swift
2
1280
/* Copyright 2017-present The Material Motion 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 UIKit import CatalogByConvention @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { let window = UIWindow(frame: UIScreen.main.bounds) self.window = window let rootViewController = CBCNodeListViewController(node: CBCCreateNavigationTree()) rootViewController.title = "Motion Animator Catalog" window.rootViewController = UINavigationController(rootViewController: rootViewController) window.makeKeyAndVisible() return true } }
apache-2.0
df1a84d40acfc5687d1bff6bd939e924
34.555556
150
0.783594
5.03937
false
false
false
false
ryanspillsbury90/HaleMeditates
ios/Hale Meditates/Globals.swift
1
446
// // Globals.swift // Hale Meditates // // Created by Ryan Pillsbury on 9/4/15. // Copyright (c) 2015 koait. All rights reserved. // import Foundation class Globals { enum Environment: String { case DEV = "DEV" case PRODUCTION = "PRODUCTION" } static let environment: Environment = .PRODUCTION; static let API_ROOT = (environment == .DEV) ? "http://localhost:3000" : "http://localhost:3000" }
mit
af073e9e03bef1f852f112c2060385cf
20.285714
99
0.621076
3.596774
false
false
false
false
leotumwattana/WWC-Animations
WWC-Animations/InflatyCircle.swift
1
1392
// // InflatyCircle.swift // WWC-Animations // // Created by Leo Tumwattana on 28/5/15. // Copyright (c) 2015 Innovoso Ltd. All rights reserved. // import UIKit import pop class InflatyCircle: Circle { var inflated = false override func tapped(tap: UITapGestureRecognizer) { if inflated { deflate() } else { inflate() } inflated = !inflated } private func inflate() { let toValue = NSValue(CGSize: CGSizeMake(2, 2)) if let anim = pop_animationForKey("scale") as? POPSpringAnimation { anim.toValue = toValue } else { let inflate = POPSpringAnimation(propertyNamed: kPOPViewScaleXY) inflate.toValue = toValue inflate.springBounciness = 16 inflate.springSpeed = 20 pop_addAnimation(inflate, forKey: "scale") } } private func deflate() { let toValue = NSValue(CGSize: CGSizeMake(1, 1)) if let anim = pop_animationForKey("scale") as? POPSpringAnimation { anim.toValue = toValue } else { let deflate = POPSpringAnimation(propertyNamed: kPOPViewScaleXY) deflate.toValue = toValue deflate.springBounciness = 16 deflate.springSpeed = 20 pop_addAnimation(deflate, forKey: "scale") } } }
bsd-3-clause
60d0550fe59ac6dc758ad9f2bde706bc
26.294118
76
0.584052
4.734694
false
false
false
false
lanjing99/RxSwiftDemo
17-creating-custom-reactive-extension/final/iGif/ApiController.swift
2
1999
/* * Copyright (c) 2014-2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import Foundation import RxSwift import SwiftyJSON class ApiController { static let shared = ApiController() private let apiKey = "[YOUR KEY]" func search(text: String) -> Observable<[JSON]> { let url = URL(string: "http://api.giphy.com/v1/gifs/search")! var request = URLRequest(url: url) let keyQueryItem = URLQueryItem(name: "api_key", value: apiKey) let searchQueryItem = URLQueryItem(name: "q", value: text) let urlComponents = NSURLComponents(url: url, resolvingAgainstBaseURL: true)! urlComponents.queryItems = [searchQueryItem, keyQueryItem] request.url = urlComponents.url! request.httpMethod = "GET" request.setValue("application/json", forHTTPHeaderField: "Content-Type") return URLSession.shared.rx.json(request: request).map() { json in return json["data"].array ?? [] } } }
mit
d9b605f7b81b83790528927a3fdad658
38.196078
81
0.726363
4.412804
false
false
false
false
nathawes/swift
test/AutoDiff/SILGen/autodiff_builtins.swift
8
8637
// RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s | %FileCheck %s import _Differentiation import Swift @_silgen_name("f_direct_arity1") func f_direct_arity1(_ x: Float) -> Float { x } @_silgen_name("f_direct_arity1_jvp") func f_direct_arity1_jvp(_ x: Float) -> (Float, (Float) -> Float) { (x, { $0 }) } @_silgen_name("f_direct_arity1_vjp") func f_direct_arity1_vjp(_ x: Float) -> (Float, (Float) -> Float) { (x, { $0 }) } @_silgen_name("f_direct_arity2") func f_direct_arity2(_ x: Float, _ y: Float) -> Float { x } @_silgen_name("f_indirect_arity1") func f_indirect_arity1<T: AdditiveArithmetic & Differentiable>(_ x: T) -> T { x } // MARK: - applyDerivative @_silgen_name("applyDerivative_f_direct_arity1_jvp") func applyDerivative_f1_jvp(_ x: Float) -> (Float, (Float) -> Float) { return Builtin.applyDerivative_jvp(f_direct_arity1, x) } // CHECK-LABEL: sil{{.*}}@applyDerivative_f_direct_arity1_jvp // CHECK: bb0([[X:%.*]] : $Float): // CHECK: [[D:%.*]] = differentiable_function_extract [jvp] // CHECK: [[D_RESULT:%.*]] = apply [[D]]([[X]]) // CHECK: ([[D_RESULT_0:%.*]], [[D_RESULT_1:%.*]]) = destructure_tuple [[D_RESULT]] // CHECK: [[D_RESULT_RETUPLED:%.*]] = tuple ([[D_RESULT_0]] : {{.*}}, [[D_RESULT_1]] : {{.*}}) // CHECK: return [[D_RESULT_RETUPLED]] @_silgen_name("applyDerivative_f_direct_arity1_vjp") func applyDerivative_f1_vjp(_ x: Float) -> (Float, (Float) -> Float) { return Builtin.applyDerivative_vjp(f_direct_arity1, x) } // CHECK-LABEL: sil{{.*}}@applyDerivative_f_direct_arity1_vjp // CHECK: bb0([[X:%.*]] : $Float): // CHECK: [[D:%.*]] = differentiable_function_extract [vjp] // CHECK: [[D_RESULT:%.*]] = apply [[D]]([[X]]) // CHECK: ([[D_RESULT_0:%.*]], [[D_RESULT_1:%.*]]) = destructure_tuple [[D_RESULT]] // CHECK: [[D_RESULT_RETUPLED:%.*]] = tuple ([[D_RESULT_0]] : {{.*}}, [[D_RESULT_1]] : {{.*}}) // CHECK: return [[D_RESULT_RETUPLED]] @_silgen_name("applyDerivative_f_direct_arity2_vjp") func applyDerivative_f1_vjp(_ x: Float, _ y: Float) -> (Float, (Float) -> (Float, Float)) { return Builtin.applyDerivative_vjp_arity2(f_direct_arity2, x, y) } // CHECK-LABEL: sil{{.*}}@applyDerivative_f_direct_arity2_vjp // CHECK: bb0([[X:%.*]] : $Float, [[Y:%.*]] : $Float): // CHECK: [[D:%.*]] = differentiable_function_extract [vjp] // CHECK: [[D_RESULT:%.*]] = apply [[D]]([[X]], [[Y]]) // CHECK: ([[D_RESULT_0:%.*]], [[D_RESULT_1:%.*]]) = destructure_tuple [[D_RESULT]] // CHECK: [[D_RESULT_RETUPLED:%.*]] = tuple ([[D_RESULT_0]] : {{.*}}, [[D_RESULT_1]] : {{.*}}) // CHECK: return [[D_RESULT_RETUPLED]] @_silgen_name("applyDerivative_f_indirect_arity1_vjp") func applyDerivative_f1_vjp<T: AdditiveArithmetic & Differentiable>(t0: T) -> (T, (T.TangentVector) -> T.TangentVector) { return Builtin.applyDerivative_vjp(f_indirect_arity1, t0) } // CHECK-LABEL: sil{{.*}}@applyDerivative_f_indirect_arity1_vjp // CHECK: bb0([[ORIG_RESULT_OUT_PARAM:%.*]] : $*T, [[X:%.]] : $*T): // CHECK: [[D:%.*]] = differentiable_function_extract [vjp] // CHECK: [[D_RESULT_BUFFER:%.*]] = alloc_stack $(T, @callee_guaranteed @substituted <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0) -> @out τ_0_1 for <T.TangentVector, T.TangentVector>) // CHECK: [[D_RESULT_BUFFER_0_FOR_STORE:%.*]] = tuple_element_addr [[D_RESULT_BUFFER]] : ${{.*}}, 0 // CHECK: [[D_RESULT:%.*]] = apply [[D]]([[D_RESULT_BUFFER_0_FOR_STORE]], [[X]]) // CHECK: [[D_RESULT_BUFFER_1_FOR_STORE:%.*]] = tuple_element_addr [[D_RESULT_BUFFER]] : ${{.*}}, 1 // CHECK: store [[D_RESULT]] to [init] [[D_RESULT_BUFFER_1_FOR_STORE]] // CHECK: [[D_RESULT_BUFFER_0_FOR_LOAD:%.*]] = tuple_element_addr [[D_RESULT_BUFFER]] : ${{.*}}, 0 // CHECK: [[D_RESULT_BUFFER_1_FOR_LOAD:%.*]] = tuple_element_addr [[D_RESULT_BUFFER]] : ${{.*}}, 1 // CHECK: [[PULLBACK:%.*]] = load [take] [[D_RESULT_BUFFER_1_FOR_LOAD]] // CHECK: copy_addr [take] [[D_RESULT_BUFFER_0_FOR_LOAD]] to [initialization] [[ORIG_RESULT_OUT_PARAM]] // CHECK: return [[PULLBACK]] // MARK: - applyTranspose @_silgen_name("applyTranspose_f_direct_arity1") func applyTranspose_f_direct_arity1(_ x: Float) -> Float { return Builtin.applyTranspose_arity1(f_direct_arity1, x) } // CHECK-LABEL: sil{{.*}}@applyTranspose_f_direct_arity1 // CHECK: bb0([[X:%.*]] : $Float): // CHECK: [[ORIG:%.*]] = function_ref @f_direct_arity1 : $@convention(thin) (Float) -> Float // CHECK: [[THICK_ORIG:%.*]] = thin_to_thick_function [[ORIG]] : $@convention(thin) (Float) -> Float to $@callee_guaranteed (Float) -> Float // CHECK: [[LINEAR:%.*]] = linear_function [parameters 0] [[THICK_ORIG]] : $@callee_guaranteed (Float) -> Float // CHECK: [[NOESC_LINEAR:%.*]] = convert_escape_to_noescape [not_guaranteed] [[LINEAR]] : $@differentiable(linear) @callee_guaranteed (Float) -> Float to $@differentiable(linear) @noescape @callee_guaranteed (Float) -> Float // CHECK: [[TRANS:%.*]] = linear_function_extract [transpose] [[NOESC_LINEAR]] : $@differentiable(linear) @noescape @callee_guaranteed (Float) -> Float // CHECK: [[RESULT:%.*]] = apply [[TRANS]]([[X]]) : $@noescape @callee_guaranteed (Float) -> Float // CHECK: destroy_value [[LINEAR]] : $@differentiable(linear) @callee_guaranteed (Float) -> Float // CHECK: return [[RESULT]] : $Float @_silgen_name("applyTranspose_f_direct_arity2") func applyTranspose_f_direct_arity2(_ x: Float) -> (Float, Float) { return Builtin.applyTranspose_arity2(f_direct_arity2, x) } // CHECK-LABEL: sil{{.*}}@applyTranspose_f_direct_arity2 // CHECK: bb0([[X:%.*]] : $Float) // CHECK: [[ORIG:%.*]] = function_ref @f_direct_arity2 : $@convention(thin) (Float, Float) -> Float // CHECK: [[THICK_ORIG:%.*]] = thin_to_thick_function [[ORIG]] : $@convention(thin) (Float, Float) -> Float to $@callee_guaranteed (Float, Float) -> Float // CHECK: [[LINEAR:%.*]] = linear_function [parameters 0 1] [[THICK_ORIG]] : $@callee_guaranteed (Float, Float) -> Float // CHECK: [[NOESC_LINEAR:%.*]] = convert_escape_to_noescape [not_guaranteed] [[LINEAR]] : $@differentiable(linear) @callee_guaranteed (Float, Float) -> Float to $@differentiable(linear) @noescape @callee_guaranteed (Float, Float) -> Float // CHECK: [[TRANS:%.*]] = linear_function_extract [transpose] [[NOESC_LINEAR]] : $@differentiable(linear) @noescape @callee_guaranteed (Float, Float) -> Float // CHECK: [[RESULT:%.*]] = apply [[TRANS]]([[X]]) : $@noescape @callee_guaranteed (Float) -> (Float, Float) // CHECK: ([[RES1:%.*]], [[RES2:%.*]]) = destructure_tuple [[RESULT]] : $(Float, Float) // CHECK: destroy_value [[LINEAR]] : $@differentiable(linear) @callee_guaranteed (Float, Float) -> Float // CHECK: [[RESULT:%.*]] = tuple ([[RES1]] : $Float, [[RES2]] : $Float) // CHECK: return [[RESULT]] : $(Float, Float) @_silgen_name("applyTranspose_f_indirect_arity1") func applyTranspose_f_indirect_arity1<T: AdditiveArithmetic & Differentiable>(_ x: T) -> T { return Builtin.applyTranspose_arity1(f_indirect_arity1, x) } // CHECK-LABEL: sil{{.*}}@applyTranspose_f_indirect_arity1 // CHECK: bb0([[OUT_PARAM:%.*]] : $*T, [[X:%.*]] : $*T): // CHECK: [[RESULT:%.*]] = apply [[TRANSPOSE:%.*]]([[OUT_PARAM]], [[X]]) // MARK: - differentiableFunction @_silgen_name("differentiableFunction_f_direct_arity1") func differentiableFunction_f_direct_arity1() -> @differentiable (Float) -> Float { return Builtin.differentiableFunction_arity1(f_direct_arity1, f_direct_arity1_jvp, f_direct_arity1_vjp) } // CHECK-LABEL: sil{{.*}}@differentiableFunction_f_direct_arity1 // CHECK: [[DIFF_FN:%.*]] = differentiable_function // CHECK: return [[DIFF_FN]] // MARK: - linearFunction // TODO(TF-1142): Add linear_funcion to this test when it exists. @_silgen_name("linearFunction_f_direct_arity1") func linearFunction_f_direct_arity1() -> @differentiable(linear) (Float) -> Float { return Builtin.linearFunction_arity1(f_direct_arity1, f_direct_arity1) } // CHECK-LABEL: sil{{.*}}@linearFunction_f_direct_arity1 // CHECK: bb0: // CHECK: [[ORIG1:%.*]] = function_ref @f_direct_arity1 : $@convention(thin) (Float) -> Float // CHECK: [[THICK_ORIG1:%.*]] = thin_to_thick_function [[ORIG1]] : $@convention(thin) (Float) -> Float to $@callee_guaranteed (Float) -> Float // CHECK: [[ORIG2:%.*]] = function_ref @f_direct_arity1 : $@convention(thin) (Float) -> Float // CHECK: [[THICK_ORIG2:%.*]] = thin_to_thick_function [[ORIG2]] : $@convention(thin) (Float) -> Float to $@callee_guaranteed (Float) -> Float // CHECK: [[LINEAR:%.*]] = linear_function [parameters 0] [[THICK_ORIG1]] : $@callee_guaranteed (Float) -> Float with_transpose [[THICK_ORIG2]] : $@callee_guaranteed (Float) -> Float // CHECK: return [[LINEAR]] : $@differentiable(linear) @callee_guaranteed (Float) -> Float
apache-2.0
ef548e8eaac4fa5f361715281f05bd5e
55.424837
240
0.63431
3.140415
false
false
false
false
ngageoint/mage-ios
Mage/Mixins/FilteredUsersMap.swift
1
11114
// // FilteredUsersMap.swift // MAGE // // Created by Daniel Barela on 12/16/21. // Copyright © 2021 National Geospatial Intelligence Agency. All rights reserved. // import Foundation import MapKit protocol FilteredUsersMap { var mapView: MKMapView? { get set } var filteredUsersMapMixin: FilteredUsersMapMixin? { get set } func addFilteredUsers() } extension FilteredUsersMap { func addFilteredUsers() { filteredUsersMapMixin?.addFilteredUsers() } } class FilteredUsersMapMixin: NSObject, MapMixin { var mapAnnotationFocusedObserver: AnyObject? var filteredUsersMap: FilteredUsersMap? var mapView: MKMapView? var scheme: MDCContainerScheming? var enlargedLocationView: MKAnnotationView? var selectedUserAccuracy: MKOverlay? var locations: Locations? var user: User? init(filteredUsersMap: FilteredUsersMap, user: User? = nil, scheme: MDCContainerScheming?) { self.filteredUsersMap = filteredUsersMap self.mapView = filteredUsersMap.mapView self.user = user self.scheme = scheme } func cleanupMixin() { if let mapAnnotationFocusedObserver = mapAnnotationFocusedObserver { NotificationCenter.default.removeObserver(mapAnnotationFocusedObserver) } mapAnnotationFocusedObserver = nil UserDefaults.standard.removeObserver(self, forKeyPath: #keyPath(UserDefaults.locationTimeFilter)) UserDefaults.standard.removeObserver(self, forKeyPath: #keyPath(UserDefaults.locationTimeFilterUnit)) UserDefaults.standard.removeObserver(self, forKeyPath: #keyPath(UserDefaults.locationTimeFilterNumber)) UserDefaults.standard.removeObserver(self, forKeyPath: #keyPath(UserDefaults.hidePeople)) locations?.fetchedResultsController.delegate = nil locations = nil } func setupMixin() { UserDefaults.standard.addObserver(self, forKeyPath: #keyPath(UserDefaults.locationTimeFilter), options: [.new], context: nil) UserDefaults.standard.addObserver(self, forKeyPath: #keyPath(UserDefaults.locationTimeFilterUnit), options: [.new], context: nil) UserDefaults.standard.addObserver(self, forKeyPath: #keyPath(UserDefaults.locationTimeFilterNumber), options: [.new], context: nil) UserDefaults.standard.addObserver(self, forKeyPath: #keyPath(UserDefaults.hidePeople), options: [.new], context: nil) mapAnnotationFocusedObserver = NotificationCenter.default.addObserver(forName: .MapAnnotationFocused, object: nil, queue: .main) { [weak self] notification in if let notificationObject = (notification.object as? MapAnnotationFocusedNotification), notificationObject.mapView == self?.mapView { self?.focusAnnotation(annotation: notificationObject.annotation) } else if notification.object == nil { self?.focusAnnotation(annotation: nil) } } addFilteredUsers() } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { addFilteredUsers() NotificationCenter.default.post(name: .LocationFiltersChanged, object: nil) } func addFilteredUsers() { if let locations = locations, let fetchedLocations = locations.fetchedResultsController.fetchedObjects as? [Location] { for location in fetchedLocations { deleteLocation(location: location) } } if let user = user { locations = Locations(for: user) locations?.delegate = self } else if let locations = locations, let locationPredicates = Locations.getPredicatesForLocationsForMap() as? [NSPredicate] { locations.fetchedResultsController.fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: locationPredicates) } else { locations = Locations.forMap() locations?.delegate = self } if let locations = locations { do { try locations.fetchedResultsController.performFetch() updateLocations(locations: locations.fetchedResultsController?.fetchedObjects as? [Location]) } catch { NSLog("Failed to perform fetch in the MapDelegate for locations \(error), \((error as NSError).userInfo)") } } } func updateLocations(locations: [Location]?) { guard let locations = locations else { return } for location in locations { DispatchQueue.main.async { [weak self] in self?.updateLocation(location: location) } } } func updateLocation(location: Location) { guard let coordinate = location.location?.coordinate else { return } if let annotation: LocationAnnotation = mapView?.annotations.first(where: { annotation in if let annotation = annotation as? LocationAnnotation { return annotation.user?.remoteId == location.user?.remoteId } return false }) as? LocationAnnotation { annotation.coordinate = coordinate } else { if let annotation = LocationAnnotation(location: location) { mapView?.addAnnotation(annotation) } } } func deleteLocation(location: Location) { let annotation = mapView?.annotations.first(where: { annotation in if let annotation = annotation as? LocationAnnotation { return annotation.user.remoteId == location.user?.remoteId } return false }) if let annotation = annotation { mapView?.removeAnnotation(annotation) } } func viewForAnnotation(annotation: MKAnnotation, mapView: MKMapView) -> MKAnnotationView? { guard let locationAnnotation = annotation as? LocationAnnotation, let annotationView = locationAnnotation.viewForAnnotation(on: mapView, scheme: scheme ?? globalContainerScheme()) else { return nil } // adjust the center offset if this is the enlargedPin if (annotationView == self.enlargedLocationView) { annotationView.transform = annotationView.transform.scaledBy(x: 2.0, y: 2.0) if let image = annotationView.image { annotationView.centerOffset = CGPoint(x: 0, y: -(image.size.height)) } else { annotationView.centerOffset = CGPoint(x: 0, y: annotationView.centerOffset.y * 2.0) } } annotationView.canShowCallout = false; annotationView.isEnabled = false; annotationView.accessibilityLabel = "Location Annotation \(locationAnnotation.user?.objectID.uriRepresentation().absoluteString ?? "")"; return annotationView; } func focusAnnotation(annotation: MKAnnotation?) { guard let annotation = annotation as? LocationAnnotation, let _ = annotation.user, let annotationView = annotation.view else { if let selectedUserAccuracy = selectedUserAccuracy { mapView?.removeOverlay(selectedUserAccuracy) self.selectedUserAccuracy = nil } if let enlargedLocationView = enlargedLocationView { // shrink the old focused view UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseInOut) { enlargedLocationView.transform = enlargedLocationView.transform.scaledBy(x: 0.5, y: 0.5) if let image = enlargedLocationView.image { enlargedLocationView.centerOffset = CGPoint(x: 0, y: -(image.size.height / 2.0)) } else { enlargedLocationView.centerOffset = CGPoint(x: 0, y: enlargedLocationView.centerOffset.y / 2.0) } } completion: { success in } self.enlargedLocationView = nil } return } if annotationView == enlargedLocationView { // already focused ignore return } else if let enlargedLocationView = enlargedLocationView { // shrink the old focused view UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseInOut) { enlargedLocationView.transform = enlargedLocationView.transform.scaledBy(x: 0.5, y: 0.5) if let image = annotationView.image { enlargedLocationView.centerOffset = CGPoint(x: 0, y: -(image.size.height / 2.0)) } else { enlargedLocationView.centerOffset = CGPoint(x: 0, y: annotationView.centerOffset.y / 2.0) } } completion: { success in } } if let selectedUserAccuracy = selectedUserAccuracy { mapView?.removeOverlay(selectedUserAccuracy) } enlargedLocationView = annotationView let accuracy = annotation.location.horizontalAccuracy let coordinate = annotation.location.coordinate selectedUserAccuracy = LocationAccuracy(center: coordinate, radius: accuracy) mapView?.addOverlay(selectedUserAccuracy!) UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseInOut) { annotationView.transform = annotationView.transform.scaledBy(x: 2.0, y: 2.0) if let image = annotationView.image { annotationView.centerOffset = CGPoint(x: 0, y: -(image.size.height)) } else { annotationView.centerOffset = CGPoint(x: 0, y: annotationView.centerOffset.y * 2.0) } } completion: { success in } } func renderer(overlay: MKOverlay) -> MKOverlayRenderer? { if let overlay = overlay as? LocationAccuracy { return LocationAccuracyRenderer(overlay: overlay) } return nil } } extension FilteredUsersMapMixin : NSFetchedResultsControllerDelegate { func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { guard let location = anObject as? Location else { return } switch(type) { case .insert: self.updateLocation(location: location) case .delete: self.deleteLocation(location: location) case .move: self.updateLocation(location: location) case .update: self.updateLocation(location: location) @unknown default: break } } }
apache-2.0
019a34430dc507235f5a91e0a6d150ee
41.578544
200
0.625574
5.53988
false
false
false
false
crazypoo/PTools
Pods/CryptoSwift/Sources/CryptoSwift/UInt64+Extension.swift
2
2046
// // CryptoSwift // // Copyright (C) 2014-2022 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // /** array of bytes */ extension UInt64 { @_specialize(where T == ArraySlice<UInt8>) init<T: Collection>(bytes: T) where T.Element == UInt8, T.Index == Int { self = UInt64(bytes: bytes, fromIndex: bytes.startIndex) } @_specialize(where T == ArraySlice<UInt8>) @inlinable init<T: Collection>(bytes: T, fromIndex index: T.Index) where T.Element == UInt8, T.Index == Int { if bytes.isEmpty { self = 0 return } let count = bytes.count let val0 = count > 0 ? UInt64(bytes[index.advanced(by: 0)]) << 56 : 0 let val1 = count > 1 ? UInt64(bytes[index.advanced(by: 1)]) << 48 : 0 let val2 = count > 2 ? UInt64(bytes[index.advanced(by: 2)]) << 40 : 0 let val3 = count > 3 ? UInt64(bytes[index.advanced(by: 3)]) << 32 : 0 let val4 = count > 4 ? UInt64(bytes[index.advanced(by: 4)]) << 24 : 0 let val5 = count > 5 ? UInt64(bytes[index.advanced(by: 5)]) << 16 : 0 let val6 = count > 6 ? UInt64(bytes[index.advanced(by: 6)]) << 8 : 0 let val7 = count > 7 ? UInt64(bytes[index.advanced(by: 7)]) : 0 self = val0 | val1 | val2 | val3 | val4 | val5 | val6 | val7 } }
mit
3e70ebd762e1ca39e6a2dbfd380f0482
45.477273
217
0.674817
3.587719
false
false
false
false
CoderYLiu/30DaysOfSwift
Project 10 - VideoBackground/SpotifyVideoBackground/VideoSplashViewController.swift
1
3605
// // VideoSplashViewController.swift // SpotifyVideoBackground <https://github.com/DeveloperLY/30DaysOfSwift> // // Created by Liu Y on 16/4/17. // Copyright © 2016年 DeveloperLY. All rights reserved. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // import UIKit import MediaPlayer import AVKit public enum ScalingMode { case resize case resizeAspect case resizeAspectFill } open class VideoSplashViewController: UIViewController { override open func viewDidLoad() { super.viewDidLoad() } override open func viewDidAppear(_ animated: Bool) { moviePlayer.view.frame = videoFrame moviePlayer.showsPlaybackControls = false view.addSubview(moviePlayer.view) view.sendSubview(toBack: moviePlayer.view) } override open func viewWillDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.removeObserver(self) } fileprivate let moviePlayer = AVPlayerViewController() fileprivate var moviePlayerSoundLevel: Float = 1.0 open var contentURL: URL? { didSet { setMoviePlayer(contentURL!) } } open var videoFrame: CGRect = CGRect() open var startTime: CGFloat = 0.0 open var duration: CGFloat = 0.0 open var backgroundColor: UIColor = UIColor.black { didSet { view.backgroundColor = backgroundColor } } open var sound: Bool = true { didSet { if sound { moviePlayerSoundLevel = 1.0 }else{ moviePlayerSoundLevel = 0.0 } } } open var alpha: CGFloat = CGFloat() { didSet { moviePlayer.view.alpha = alpha } } open var alwaysRepeat: Bool = true { didSet { if alwaysRepeat { NotificationCenter.default.addObserver(self, selector: #selector(VideoSplashViewController.playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: moviePlayer.player?.currentItem) } } } open var fillMode: ScalingMode = .resizeAspectFill { didSet { switch fillMode { case .resize: moviePlayer.videoGravity = AVLayerVideoGravityResize case .resizeAspect: moviePlayer.videoGravity = AVLayerVideoGravityResizeAspect case .resizeAspectFill: moviePlayer.videoGravity = AVLayerVideoGravityResizeAspectFill } } } fileprivate func setMoviePlayer(_ url: URL) { let videoCutter = VideoCutter() videoCutter.cropVideoWithUrl(videoUrl: url, startTime: startTime, duration: duration) { (videoPath, error) -> Void in if let path = videoPath as URL? { let priority = DispatchQueue.GlobalQueuePriority.default DispatchQueue.global(priority: priority).async { DispatchQueue.main.async { self.moviePlayer.player = AVPlayer(url: path) self.moviePlayer.player?.play() self.moviePlayer.player?.volume = self.moviePlayerSoundLevel } } } } } func playerItemDidReachEnd() { moviePlayer.player?.seek(to: kCMTimeZero) moviePlayer.player?.play() } }
mit
fc9b8504e1b042df0b969ac904cb0d08
29.016667
125
0.600222
5.52454
false
false
false
false
anjlab/JJ
Example/Tests/Tests.swift
1
12973
import UIKit import XCTest import JJ import Foundation class Tests: XCTestCase { func testObject() { let j = ["firstName": "Yury", "lastName": "Korolev"] let o = try! jj(j).obj() XCTAssertEqual("[\"lastName\": \"Korolev\", \"firstName\": \"Yury\"]", o.raw.debugDescription) XCTAssertEqual("{\n \"firstName\": \"Yury\",\n \"lastName\": \"Korolev\"\n}", o.debugDescription) XCTAssertEqual("{\n \"firstName\": \"Yury\",\n \"lastName\": \"Korolev\"\n}", o.prettyPrint()) XCTAssertEqual("{\n \"firstName\": \"Yury\",\n \"lastName\": \"Korolev\"\n}", o.prettyPrint(space: "", spacer: " ")) let json = [ "firstName": "Yury" as AnyObject, "lastName": "Korolev" as AnyObject, "trueFlag": true as AnyObject, "falseFlag": false as AnyObject, "intValue" : 13 as AnyObject, "doubleValue" : 12.1 as AnyObject, "date" : "2016-06-10T00:00:00.000Z", "url" : "http://anjlab.com", "zone" : "Europe/Moscow", "arr" : [1, 2, 3] , "obj" : ["value" : 1] ] as [String: Any] let obj = try! jj(json).obj() XCTAssertEqual("Yury", try! obj["firstName"].string()) XCTAssertEqual("Korolev", try! obj["lastName"].string()) XCTAssertEqual(nil, try? obj["unknownKey"].string()) XCTAssertEqual("Korolev", obj["lastName"].toString()) XCTAssertEqual("Test", obj["unknownKey"].toString("Test")) XCTAssertEqual("Korolev", obj["lastName"].asString) XCTAssertEqual(true, try! obj["trueFlag"].bool()) XCTAssertEqual(false, try! obj["falseFlag"].bool()) XCTAssertEqual(true, obj["trueFlag"].toBool()) XCTAssertEqual(false, obj["falseFlag"].toBool()) XCTAssertEqual(true, obj["trueFlag"].asBool) XCTAssertEqual(false, obj["falseFlag"].asBool) XCTAssertEqual(false, obj["unknown"].toBool()) XCTAssertEqual(13, try! obj["intValue"].int()) XCTAssertEqual(13, obj["intValue"].toInt()) XCTAssertEqual(13, obj["intValue"].asInt) XCTAssertEqual(11, obj["integerValue"].toInt(11)) XCTAssertEqual(nil, obj["integerValue"].asInt) XCTAssertEqual(13, try! obj["intValue"].uInt()) XCTAssertEqual(13, obj["intValue"].toUInt()) XCTAssertEqual(11, obj["unknownKey"].toUInt(UInt(11))) XCTAssertEqual(0, obj["unknownKey"].toUInt()) XCTAssertEqual(13, obj["intValue"].asUInt) XCTAssertEqual(12.1, try! obj["doubleValue"].double()) XCTAssertEqual(12.1, obj["doubleValue"].toDouble()) XCTAssertEqual(11.1, obj["unknownKey"].toFloat(Float(11.1))) XCTAssertEqual(0, obj["unknownKey"].toFloat()) XCTAssertEqual(12.1, obj["doubleValue"].asDouble) XCTAssertEqual(12.1, obj["doubleValue"].toDouble()) XCTAssertEqual(12.1, obj["doubleValue"].toDouble(11.1)) XCTAssertEqual(12.1, obj["doubleValue"].asDouble) XCTAssertEqual(nil, obj["unknownKey"].asDouble) XCTAssertEqual(11.1, obj["unknownKey"].toDouble(11.1)) XCTAssertEqual(12.1, try! obj["doubleValue"].number()) XCTAssertEqual(12.1, obj["doubleValue"].toNumber()) XCTAssertEqual(11.1, obj["unknownKey"].toNumber(11.1)) XCTAssertEqual(12.1, obj["doubleValue"].asNumber) XCTAssertEqual(nil, try? obj["unknownKey"].date()) XCTAssertEqual(String.asRFC3339Date("2016-06-10T00:00:00.000Z")(), try! obj["date"].date()) XCTAssertEqual(String.asRFC3339Date("2016-06-10T00:00:00.000Z")(), obj["date"].asDate) XCTAssertEqual("2016-06-10T00:00:00.000Z", String.asRFC3339Date("2016-06-10T00:00:00.000Z")()?.toRFC3339String()) XCTAssertEqual(URL(string: "http://anjlab.com"), try! obj["url"].url()) XCTAssertEqual(nil, try? obj["unknownKey"].url()) XCTAssertEqual(URL(string: "http://anjlab.com"), obj["url"].toURL()) XCTAssertEqual(URL(string: "/")!, obj["unknownKey"].toURL(URL(string: "/")!)) XCTAssertEqual(URL(string: "http://anjlab.com"), obj["url"].asURL) XCTAssertEqual(nil, obj["unknownKey"].asURL) XCTAssertEqual(TimeZone(identifier: "Europe/Moscow"), obj["zone"].asTimeZone) XCTAssertEqual(nil, obj["unknownKey"].asTimeZone) XCTAssertEqual(true, obj["obj"].toObj().exists) XCTAssertEqual("[\"value\": 1]", try! obj["obj"].obj().raw.debugDescription) XCTAssertEqual(nil, try? obj["unknownKey"].obj().raw.debugDescription) XCTAssertEqual("Optional([\"value\": 1])", obj["obj"].toObj().raw.debugDescription) XCTAssertEqual("<root>.obj", obj["obj"].toObj().path) XCTAssertEqual(true, obj["arr"].toArr().exists) XCTAssertEqual("[1, 2, 3]", obj["arr"].toArr().raw?.debugDescription) XCTAssertEqual("<root>.arr", obj["arr"].toArr().path) XCTAssertEqual(11, obj.count) XCTAssertEqual(true, obj.exists) XCTAssertEqual("<root>", obj.path) XCTAssertEqual("<root>.url", obj["url"].path) XCTAssertEqual(json["firstName"].debugDescription, obj["firstName"].raw.debugDescription) XCTAssertEqual("\"Yury\"", obj["firstName"].debugDescription) XCTAssertEqual("\"Yury\"", obj["firstName"].prettyPrint()) XCTAssertEqual("\"Yury\"", obj["firstName"].prettyPrint(space: "", spacer: " ")) } func testArray() { let j = [1, "Nice"] as [Any] let a = try! jj(j).arr() XCTAssertEqual(j.debugDescription, a.raw.debugDescription) XCTAssertEqual("[\n 1,\n \"Nice\"\n]", a.debugDescription) let json = [1 as AnyObject, "Nice" as AnyObject, 5.5 as AnyObject, NSNull(), "http://anjlab.com" as AnyObject] as [AnyObject] let arr = try! jj(json).arr() XCTAssertEqual(1, try! arr[0].int()) XCTAssertEqual("Nice", try! arr[1].string()) XCTAssertEqual(5.5, try! arr[2].double()) XCTAssertEqual(true, arr[3].isNull) XCTAssertEqual(URL(string: "http://anjlab.com"), try! arr[4].url()) XCTAssertEqual(5, arr.count) XCTAssertEqual(true, arr.exists) XCTAssertEqual(true, arr[1].exists) XCTAssertEqual("<root>", arr.path) XCTAssertEqual(JJVal(1, path: "<root>.1").debugDescription, arr.at(0).debugDescription) XCTAssertEqual("[\n 1,\n \"Nice\",\n 5.5,\n null,\n \"http://anjlab.com\"\n]", arr.prettyPrint()) XCTAssertEqual("[\n 1,\n \"Nice\",\n 5.5,\n null,\n \"http://anjlab.com\"\n]", arr.prettyPrint(space: "", spacer: " ")) } func testDecEnc() { let data = NSMutableData() let coder = NSKeyedArchiver(forWritingWith: data) let enc = jj(encoder: coder) enc.put("Title", at: "title") enc.put("Nice", at: "text") enc.put(["key" : "value"], at: "obj") enc.put(String.asRFC3339Date("2016-06-10T00:00:00.000Z")(), at: "date") enc.put(false, at: "boolValue") enc.put(13, at: "number") enc.put(Double(1.1), at: "double") enc.put(Float(10), at: "float") enc.put(Optional<Float>.none, at: "optionalFloat") coder.finishEncoding() let decoder = NSKeyedUnarchiver(forReadingWith: data as Data) let dec = jj(decoder: decoder) XCTAssertEqual("Nice", try! dec["text"].string()) XCTAssertEqual(nil, dec["unknownKey"].asString) XCTAssertEqual(13, try! dec["number"].int()) XCTAssertEqual(10, try! dec["float"].float()) XCTAssertEqual(1.1, try! dec["double"].double()) XCTAssertEqual(nil, dec["optionalFloat"].asFloat) XCTAssertEqual(nil, dec["unknownKey"].asInt) XCTAssertEqual(nil, dec["unknownKey"].asDate) XCTAssertEqual(nil, dec["unknownKey"].asURL) XCTAssertEqual(String.asRFC3339Date("2016-06-10T00:00:00.000Z")(), try! dec["date"].date()) XCTAssertEqual(String.asRFC3339Date("2016-06-10T00:00:00.000Z")(), dec["date"].asDate) XCTAssertEqual(nil, dec["unknownKey"].asTimeZone) XCTAssertEqual(false, try! dec["boolValue"].bool()) XCTAssertEqual(false, dec["boolValue"].toBool()) XCTAssertEqual(decoder, dec["boolValue"].decoder) XCTAssertEqual("boolValue", dec["boolValue"].key) XCTAssertEqual("Title", try! dec["title"].decode() as NSString) // TODO: fix // let res: [String: String] = dec["obj"].decodeAs() as [String: String] // XCTAssertEqual(["key" : "value"], res) //Errors do { let _ = try dec["unknownKey"].date() XCTFail() } catch { let err = "\(error)" XCTAssertEqual("JJError.WrongType: Can\'t convert nil at path: \'unknownKey\' to type \'NSDate\'", err) } do { let _ = try dec["unknownKey"].string() XCTFail() } catch { let err = "\(error)" XCTAssertEqual("JJError.WrongType: Can\'t convert nil at path: \'unknownKey\' to type \'String\'", err) } do { let _ = try dec["unknownKey"].decode() as NSNumber XCTFail() } catch { let err = "\(error)" XCTAssertEqual("JJError.WrongType: Can\'t convert nil at path: \'unknownKey\' to type \'T\'", err) } } func testErrors() { let json = ["firstName": "Yury", "lastName": "Korolev"] let obj = try! jj(json).obj() XCTAssertEqual(false, obj["unknownKey"].exists) do { let _ = try obj["unknownKey"].string() XCTFail() } catch { let err = "\(error)" XCTAssertEqual("JJError.WrongType: Can't convert nil at path: '<root>.unknownKey' to type 'String'", err) } do { let _ = try obj["unknownKey"].date() XCTFail() } catch { let err = "\(error)" XCTAssertEqual("JJError.WrongType: Can't convert nil at path: '<root>.unknownKey' to type 'NSDate'", err) } do { let _ = try obj["unknownKey"].url() XCTFail() } catch { let err = "\(error)" XCTAssertEqual("JJError.WrongType: Can't convert nil at path: '<root>.unknownKey' to type 'NSURL'", err) } do { let _ = try obj["nested"]["unknown"][0].url() XCTFail() } catch { let err = "\(error)" XCTAssertEqual("JJError.WrongType: Can't convert nil at path: '<root>.nested<nil>.unknown<nil>[0]' to type 'NSURL'", err) } do { let _ = try jj(json).arr() XCTFail() } catch { let err = "\(error)" XCTAssertEqual("JJError.WrongType: Can't convert Optional([\"lastName\": \"Korolev\", \"firstName\": \"Yury\"]) at path: '<root>' to type '[Any]'", err) } do { let _ = try obj["unknownKey"].bool() XCTFail() } catch { let err = "\(error)" XCTAssertEqual("JJError.WrongType: Can't convert nil at path: '<root>.unknownKey' to type 'Bool'", err) } do { let _ = try obj["unknownKey"].int() XCTFail() } catch { let err = "\(error)" XCTAssertEqual("JJError.WrongType: Can't convert nil at path: '<root>.unknownKey' to type 'Int'", err) } do { let _ = try obj["unknownKey"].uInt() XCTFail() } catch { let err = "\(error)" XCTAssertEqual("JJError.WrongType: Can't convert nil at path: '<root>.unknownKey' to type 'UInt'", err) } do { let _ = try obj["unknownKey"].float() XCTFail() } catch { let err = "\(error)" XCTAssertEqual("JJError.WrongType: Can't convert nil at path: '<root>.unknownKey' to type 'Float'", err) } do { let _ = try obj["unknownKey"].double() XCTFail() } catch { let err = "\(error)" XCTAssertEqual("JJError.WrongType: Can't convert nil at path: '<root>.unknownKey' to type 'Double'", err) } do { let _ = try obj["unknownKey"].number() XCTFail() } catch { let err = "\(error)" XCTAssertEqual("JJError.WrongType: Can't convert nil at path: '<root>.unknownKey' to type 'NSNumber'", err) } } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
mit
b1e83e97c31a6778b9dfc28e910f8983
42.099668
164
0.554845
4.117106
false
false
false
false
Alloc-Studio/Hypnos
Hypnos/Hypnos/Controller/MusicHall/ActivityViewController.swift
1
2241
// // ActivityViewController.swift // Hypnos // // Created by Fay on 16/5/27. // Copyright © 2016年 DMT312. All rights reserved. // import UIKit import SVProgressHUD class ActivityViewController: UIViewController { private var activits:[ActivityModel] = [] var artist:HotArtistsModel? override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) SVProgressHUD.showWithStatus("正在拼命加载中...") DataTool.getArtistActivity((artist?.id)!) { (obj) in self.activits = (obj as! HotArtistsModel).events! self.tableView.reloadData() SVProgressHUD.dismiss() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() tableView.frame = view.bounds } lazy var tableView:UITableView = { let tb = UITableView(frame: self.view.bounds) tb.dataSource = self tb.delegate = self tb.tableFooterView = UIView() ActivityCell.registerCell(tb) return tb }() } extension ActivityViewController:UITableViewDelegate,UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return activits.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(id_ActivityCell) as! ActivityCell cell.activitys = activits[indexPath.row] return cell } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 66.0 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let web = WebViewController() web.activity = activits[indexPath.row] navigationController?.pushViewController(web, animated: true) } }
mit
03b407a7939d1b46bdea266cb2b85d5c
27.164557
109
0.660971
5.220657
false
false
false
false
natecook1000/swift
test/SILGen/generic_closures.swift
2
15205
// RUN: %target-swift-emit-silgen -module-name generic_closures -parse-stdlib -enable-sil-ownership %s | %FileCheck %s import Swift var zero: Int // CHECK-LABEL: sil hidden @$S16generic_closures0A21_nondependent_context{{[_0-9a-zA-Z]*}}F func generic_nondependent_context<T>(_ x: T, y: Int) -> Int { func foo() -> Int { return y } func bar() -> Int { return y } // CHECK: [[FOO:%.*]] = function_ref @$S16generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int // CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]](%1) // CHECK: destroy_value [[FOO_CLOSURE]] let _ = foo // CHECK: [[BAR:%.*]] = function_ref @$S16generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int // CHECK: [[BAR_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[BAR]](%1) // CHECK: destroy_value [[BAR_CLOSURE]] let _ = bar // CHECK: [[FOO:%.*]] = function_ref @$S16generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]] _ = foo() // CHECK: [[BAR:%.*]] = function_ref @$S16generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int // CHECK: [[BAR_CLOSURE:%.*]] = apply [[BAR]] // CHECK: [[BAR_CLOSURE]] return bar() } // CHECK-LABEL: sil hidden @$S16generic_closures0A8_capture{{[_0-9a-zA-Z]*}}F func generic_capture<T>(_ x: T) -> Any.Type { func foo() -> Any.Type { return T.self } // CHECK: [[FOO:%.*]] = function_ref @$S16generic_closures0A8_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick Any.Type // CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]]<T>() // CHECK: destroy_value [[FOO_CLOSURE]] let _ = foo // CHECK: [[FOO:%.*]] = function_ref @$S16generic_closures0A8_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick Any.Type // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>() // CHECK: return [[FOO_CLOSURE]] return foo() } // CHECK-LABEL: sil hidden @$S16generic_closures0A13_capture_cast{{[_0-9a-zA-Z]*}}F func generic_capture_cast<T>(_ x: T, y: Any) -> Bool { func foo(_ a: Any) -> Bool { return a is T } // CHECK: [[FOO:%.*]] = function_ref @$S16generic_closures0A13_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in_guaranteed Any) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]]<T>() // CHECK: destroy_value [[FOO_CLOSURE]] let _ = foo // CHECK: [[FOO:%.*]] = function_ref @$S16generic_closures0A13_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in_guaranteed Any) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>([[ARG:%.*]]) // CHECK: return [[FOO_CLOSURE]] return foo(y) } protocol Concept { var sensical: Bool { get } } // CHECK-LABEL: sil hidden @$S16generic_closures0A22_nocapture_existential{{[_0-9a-zA-Z]*}}F func generic_nocapture_existential<T>(_ x: T, y: Concept) -> Bool { func foo(_ a: Concept) -> Bool { return a.sensical } // CHECK: [[FOO:%.*]] = function_ref @$S16generic_closures0A22_nocapture_existential{{.*}} : $@convention(thin) (@in_guaranteed Concept) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = thin_to_thick_function [[FOO]] // CHECK: destroy_value [[FOO_CLOSURE]] let _ = foo // CHECK: [[FOO:%.*]] = function_ref @$S16generic_closures0A22_nocapture_existential{{.*}} : $@convention(thin) (@in_guaranteed Concept) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]([[ARG:%.*]]) // CHECK: return [[FOO_CLOSURE]] return foo(y) } // CHECK-LABEL: sil hidden @$S16generic_closures0A18_dependent_context{{[_0-9a-zA-Z]*}}F func generic_dependent_context<T>(_ x: T, y: Int) -> T { func foo() -> T { return x } // CHECK: [[FOO:%.*]] = function_ref @$S16generic_closures0A18_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0 // CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]]<T>([[BOX:%.*]]) // CHECK: destroy_value [[FOO_CLOSURE]] let _ = foo // CHECK: [[FOO:%.*]] = function_ref @$S16generic_closures0A18_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0 // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T> // CHECK: return return foo() } enum Optionable<Wrapped> { case none case some(Wrapped) } class NestedGeneric<U> { class func generic_nondependent_context<T>(_ x: T, y: Int, z: U) -> Int { func foo() -> Int { return y } let _ = foo return foo() } class func generic_dependent_inner_context<T>(_ x: T, y: Int, z: U) -> T { func foo() -> T { return x } let _ = foo return foo() } class func generic_dependent_outer_context<T>(_ x: T, y: Int, z: U) -> U { func foo() -> U { return z } let _ = foo return foo() } class func generic_dependent_both_contexts<T>(_ x: T, y: Int, z: U) -> (T, U) { func foo() -> (T, U) { return (x, z) } let _ = foo return foo() } // CHECK-LABEL: sil hidden @$S16generic_closures13NestedGenericC20nested_reabstraction{{[_0-9a-zA-Z]*}}F // CHECK: [[REABSTRACT:%.*]] = function_ref @$SIeg_ytytIegnr_TR // CHECK: partial_apply [callee_guaranteed] [[REABSTRACT]] func nested_reabstraction<T>(_ x: T) -> Optionable<() -> ()> { return .some({}) } } // <rdar://problem/15417773> // Ensure that nested closures capture the generic parameters of their nested // context. // CHECK: sil hidden @$S16generic_closures018nested_closure_in_A0yxxlF : $@convention(thin) <T> (@in_guaranteed T) -> @out T // CHECK: function_ref [[OUTER_CLOSURE:@\$S16generic_closures018nested_closure_in_A0yxxlFxyXEfU_]] // CHECK: sil private [[OUTER_CLOSURE]] : $@convention(thin) <T> (@inout_aliasable T) -> @out T // CHECK: function_ref [[INNER_CLOSURE:@\$S16generic_closures018nested_closure_in_A0yxxlFxyXEfU_xyXEfU_]] // CHECK: sil private [[INNER_CLOSURE]] : $@convention(thin) <T> (@inout_aliasable T) -> @out T { func nested_closure_in_generic<T>(_ x:T) -> T { return { { x }() }() } // CHECK-LABEL: sil hidden @$S16generic_closures16local_properties{{[_0-9a-zA-Z]*}}F func local_properties<T>(_ t: inout T) { var prop: T { get { return t } set { t = newValue } } // CHECK: [[GETTER_REF:%[0-9]+]] = function_ref [[GETTER_CLOSURE:@\$S16generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@inout_aliasable τ_0_0) -> @out τ_0_0 // CHECK: apply [[GETTER_REF]] t = prop // CHECK: [[SETTER_REF:%[0-9]+]] = function_ref [[SETTER_CLOSURE:@\$S16generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@in τ_0_0, @inout_aliasable τ_0_0) -> () // CHECK: apply [[SETTER_REF]] prop = t var prop2: T { get { return t } set { // doesn't capture anything } } // CHECK: [[GETTER2_REF:%[0-9]+]] = function_ref [[GETTER2_CLOSURE:@\$S16generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@inout_aliasable τ_0_0) -> @out τ_0_0 // CHECK: apply [[GETTER2_REF]] t = prop2 // CHECK: [[SETTER2_REF:%[0-9]+]] = function_ref [[SETTER2_CLOSURE:@\$S16generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@in τ_0_0) -> () // CHECK: apply [[SETTER2_REF]] prop2 = t } protocol Fooable { static func foo() -> Bool } // <rdar://problem/16399018> func shmassert(_ f: @autoclosure () -> Bool) {} // CHECK-LABEL: sil hidden @$S16generic_closures08capture_A6_param{{[_0-9a-zA-Z]*}}F func capture_generic_param<A: Fooable>(_ x: A) { shmassert(A.foo()) } // Make sure we use the correct convention when capturing class-constrained // member types: <rdar://problem/24470533> class Class {} protocol HasClassAssoc { associatedtype Assoc : Class } // CHECK-LABEL: sil hidden @$S16generic_closures027captures_class_constrained_A0_1fyx_5AssocQzAEctAA08HasClassF0RzlF // CHECK: bb0([[ARG1:%.*]] : @trivial $*T, [[ARG2:%.*]] : @guaranteed $@callee_guaranteed (@guaranteed T.Assoc) -> @owned T.Assoc): // CHECK: [[GENERIC_FN:%.*]] = function_ref @$S16generic_closures027captures_class_constrained_A0_1fyx_5AssocQzAEctAA08HasClassF0RzlFA2EcycfU_ // CHECK: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] // CHECK: [[CONCRETE_FN:%.*]] = partial_apply [callee_guaranteed] [[GENERIC_FN]]<T>([[ARG2_COPY]]) func captures_class_constrained_generic<T : HasClassAssoc>(_ x: T, f: @escaping (T.Assoc) -> T.Assoc) { let _: () -> (T.Assoc) -> T.Assoc = { f } } // Make sure local generic functions can have captures // CHECK-LABEL: sil hidden @$S16generic_closures06outer_A01t1iyx_SitlF : $@convention(thin) <T> (@in_guaranteed T, Int) -> () func outer_generic<T>(t: T, i: Int) { func inner_generic_nocapture<U>(u: U) -> U { return u } func inner_generic1<U>(u: U) -> Int { return i } func inner_generic2<U>(u: U) -> T { return t } let _: (()) -> () = inner_generic_nocapture // CHECK: [[FN:%.*]] = function_ref @$S16generic_closures06outer_A01t1iyx_SitlF06inner_A10_nocaptureL_1uqd__qd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0) -> @out τ_1_0 // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>() : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0) -> @out τ_1_0 // CHECK: [[THUNK:%.*]] = function_ref @$SytytIegnr_Ieg_TR // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]]) // CHECK: destroy_value [[THUNK_CLOSURE]] // CHECK: [[FN:%.*]] = function_ref @$S16generic_closures06outer_A01t1iyx_SitlF06inner_A10_nocaptureL_1uqd__qd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0) -> @out τ_1_0 // CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0) -> @out τ_1_0 _ = inner_generic_nocapture(u: t) // CHECK: [[FN:%.*]] = function_ref @$S16generic_closures06outer_A01t1iyx_SitlF14inner_generic1L_1uSiqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, Int) -> Int // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>(%1) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, Int) -> Int // CHECK: [[THUNK:%.*]] = function_ref @$SytSiIegnd_SiIegd_TR // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]]) // CHECK: destroy_value [[THUNK_CLOSURE]] let _: (()) -> Int = inner_generic1 // CHECK: [[FN:%.*]] = function_ref @$S16generic_closures06outer_A01t1iyx_SitlF14inner_generic1L_1uSiqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, Int) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, Int) -> Int _ = inner_generic1(u: t) // CHECK: [[FN:%.*]] = function_ref @$S16generic_closures06outer_A01t1iyx_SitlF14inner_generic2L_1uxqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, @guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0 // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>([[ARG:%.*]]) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, @guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0 // CHECK: [[THUNK:%.*]] = function_ref @$SytxIegnr_xIegr_lTR // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]<T>([[CLOSURE]]) // CHECK: destroy_value [[THUNK_CLOSURE]] let _: (()) -> T = inner_generic2 // CHECK: [[FN:%.*]] = function_ref @$S16generic_closures06outer_A01t1iyx_SitlF14inner_generic2L_1uxqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, @guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0 // CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, @guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0 _ = inner_generic2(u: t) } // CHECK-LABEL: sil hidden @$S16generic_closures14outer_concrete1iySi_tF : $@convention(thin) (Int) -> () func outer_concrete(i: Int) { func inner_generic_nocapture<U>(u: U) -> U { return u } func inner_generic<U>(u: U) -> Int { return i } // CHECK: [[FN:%.*]] = function_ref @$S16generic_closures14outer_concrete1iySi_tF06inner_A10_nocaptureL_1uxx_tlF : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<()>() : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[THUNK:%.*]] = function_ref @$SytytIegnr_Ieg_TR // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]]) // CHECK: destroy_value [[THUNK_CLOSURE]] let _: (()) -> () = inner_generic_nocapture // CHECK: [[FN:%.*]] = function_ref @$S16generic_closures14outer_concrete1iySi_tF06inner_A10_nocaptureL_1uxx_tlF : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[RESULT:%.*]] = apply [[FN]]<Int>({{.*}}) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0 _ = inner_generic_nocapture(u: i) // CHECK: [[FN:%.*]] = function_ref @$S16generic_closures14outer_concrete1iySi_tF06inner_A0L_1uSix_tlF : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, Int) -> Int // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<()>(%0) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, Int) -> Int // CHECK: [[THUNK:%.*]] = function_ref @$SytSiIegnd_SiIegd_TR // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]]) // CHECK: destroy_value [[THUNK_CLOSURE]] let _: (()) -> Int = inner_generic // CHECK: [[FN:%.*]] = function_ref @$S16generic_closures14outer_concrete1iySi_tF06inner_A0L_1uSix_tlF : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, Int) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]<Int>({{.*}}) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, Int) -> Int _ = inner_generic(u: i) } // CHECK-LABEL: sil hidden @$S16generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF : $@convention(thin) <T> (@in_guaranteed T) -> () func mixed_generic_nongeneric_nesting<T>(t: T) { func outer() { func middle<U>(u: U) { func inner() -> U { return u } inner() } middle(u: 11) } outer() } // CHECK-LABEL: sil private @$S16generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF5outerL_yylF : $@convention(thin) <T> () -> () // CHECK-LABEL: sil private @$S16generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF5outerL_yylF6middleL_1uyqd___tr__lF : $@convention(thin) <T><U> (@in_guaranteed U) -> () // CHECK-LABEL: sil private @$S16generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF5outerL_yylF6middleL_1uyqd___tr__lF5innerL_qd__yr__lF : $@convention(thin) <T><U> (@guaranteed <τ_0_0><τ_1_0> { var τ_1_0 } <T, U>) -> @out U protocol Doge { associatedtype Nose : NoseProtocol } protocol NoseProtocol { associatedtype Squeegee } protocol Doggo {} struct DogSnacks<A : Doggo> {} func capture_same_type_representative<Daisy: Doge, Roo: Doggo>(slobber: Roo, daisy: Daisy) where Roo == Daisy.Nose.Squeegee { var s = DogSnacks<Daisy.Nose.Squeegee>() _ = { _ = s } }
apache-2.0
bd568e5eed1a77e85bdd0b3fc7207865
43.943452
229
0.613072
2.925983
false
false
false
false
tombuildsstuff/swiftcity
SwiftCity/Connection/Extensions/BuildsClient.swift
1
1131
import Foundation extension TeamCityClient { public func allBuilds(start: Int = 0, count: Int = 100, successful: (Builds) -> (), failure: (NSError) -> ()) { self.connection.get("/app/rest/builds?start=\(start)&count=\(count)", acceptHeader: "application/json", done: { (data) -> () in let json = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! [String: AnyObject] let builds = Builds(dictionary: json)! successful(builds) }) { (error: NSError) -> () in failure(error) } } public func buildById(id: Int, successful: (Build?) -> (), failure: (NSError) -> ()) { self.connection.get("/app/rest/builds/id:\(id)", acceptHeader: "application/json", done: { (data) -> () in let json = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! [String: AnyObject] let build = Build(dictionary: json) successful(build) }) { (error: NSError) -> () in failure(error) } } }
mit
b1d4101b52ad9cdf50f81d5540cea5c8
44.24
142
0.597701
4.30038
false
false
false
false
ReactiveKit/Bond
Sources/Bond/UIKit/UICollectionView+DataSource.swift
1
12833
// // 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. // #if os(iOS) || os(tvOS) import UIKit import ReactiveKit extension SignalProtocol where Element: SectionedDataSourceChangesetConvertible, Error == Never { /// Binds the signal of data source elements to the given table view. /// /// - parameters: /// - tableView: A table view that should display the data from the data source. /// - animated: Animate partial or batched updates. Default is `true`. /// - rowAnimation: Row animation for partial or batched updates. Relevant only when `animated` is `true`. Default is `.automatic`. /// - createCell: A closure that creates (dequeues) cell for the given table view and configures it with the given data source at the given index path. /// - returns: A disposable object that can terminate the binding. Safe to ignore - the binding will be automatically terminated when the table view is deallocated. @discardableResult public func bind(to collectionView: UICollectionView, createCell: @escaping (Element.Changeset.Collection, IndexPath, UICollectionView) -> UICollectionViewCell) -> Disposable { let binder = CollectionViewBinderDataSource<Element.Changeset>(createCell) return bind(to: collectionView, using: binder) } /// Binds the signal of data source elements to the given table view. /// /// - parameters: /// - tableView: A table view that should display the data from the data source. /// - binder: A `TableViewBinder` or its subclass that will manage the binding. /// - returns: A disposable object that can terminate the binding. Safe to ignore - the binding will be automatically terminated when the table view is deallocated. @discardableResult public func bind(to collectionView: UICollectionView, using binderDataSource: CollectionViewBinderDataSource<Element.Changeset>) -> Disposable { binderDataSource.collectionView = collectionView return bind(to: collectionView) { (_, changeset) in binderDataSource.changeset = changeset.asSectionedDataSourceChangeset } } } extension SignalProtocol where Element: SectionedDataSourceChangesetConvertible, Element.Changeset.Collection: QueryableSectionedDataSourceProtocol, Error == Never { /// Binds the signal of data source elements to the given table view. /// /// - parameters: /// - tableView: A table view that should display the data from the data source. /// - cellType: A type of the cells that should display the data. /// - animated: Animate partial or batched updates. Default is `true`. /// - rowAnimation: Row animation for partial or batched updates. Relevant only when `animated` is `true`. Default is `.automatic`. /// - configureCell: A closure that configures the cell with the data source item at the respective index path. /// - returns: A disposable object that can terminate the binding. Safe to ignore - the binding will be automatically terminated when the table view is deallocated. /// /// Note that the cell type name will be used as a reusable identifier and the binding will automatically register and dequeue the cell. /// If there exists a nib file in the bundle with the same name as the cell type name, the framework will load the cell from the nib file. @discardableResult public func bind<Cell: UICollectionViewCell>(to collectionView: UICollectionView, cellType: Cell.Type, configureCell: @escaping (Cell, Element.Changeset.Collection.Item) -> Void) -> Disposable { let identifier = String(describing: Cell.self) let bundle = Bundle(for: Cell.self) if let _ = bundle.path(forResource: identifier, ofType: "nib") { let nib = UINib(nibName: identifier, bundle: bundle) collectionView.register(nib, forCellWithReuseIdentifier: identifier) } else { collectionView.register(cellType as AnyClass, forCellWithReuseIdentifier: identifier) } return bind(to: collectionView, createCell: { (dataSource, indexPath, collectionView) -> UICollectionViewCell in let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! Cell let item = dataSource.item(at: indexPath) configureCell(cell, item) return cell }) } /// Binds the signal of data source elements to the given table view. /// /// - parameters: /// - tableView: A table view that should display the data from the data source. /// - cellType: A type of the cells that should display the data. Cell type name will be used as reusable identifier and the binding will automatically dequeue cell. /// - animated: Animate partial or batched updates. Default is `true`. /// - rowAnimation: Row animation for partial or batched updates. Relevant only when `animated` is `true`. Default is `.automatic`. /// - configureCell: A closure that configures the cell with the data source item at the respective index path. /// - returns: A disposable object that can terminate the binding. Safe to ignore - the binding will be automatically terminated when the table view is deallocated. /// /// Note that the cell type name will be used as a reusable identifier and the binding will automatically register and dequeue the cell. /// If there exists a nib file in the bundle with the same name as the cell type name, the framework will load the cell from the nib file. @discardableResult public func bind<Cell: UICollectionViewCell>(to collectionView: UICollectionView, cellType: Cell.Type, using binderDataSource: CollectionViewBinderDataSource<Element.Changeset>, configureCell: @escaping (Cell, Element.Changeset.Collection.Item) -> Void) -> Disposable { let identifier = String(describing: Cell.self) let bundle = Bundle(for: Cell.self) if let _ = bundle.path(forResource: identifier, ofType: "nib") { let nib = UINib(nibName: identifier, bundle: bundle) collectionView.register(nib, forCellWithReuseIdentifier: identifier) } else { collectionView.register(cellType as AnyClass, forCellWithReuseIdentifier: identifier) } binderDataSource.createCell = { (dataSource, indexPath, collectionView) -> UICollectionViewCell in let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! Cell let item = dataSource.item(at: indexPath) configureCell(cell, item) return cell } return bind(to: collectionView, using: binderDataSource) } } private var CollectionViewBinderDataSourceAssociationKey = "CollectionViewBinderDataSource" open class CollectionViewBinderDataSource<Changeset: SectionedDataSourceChangeset>: NSObject, UICollectionViewDataSource { public var createCell: ((Changeset.Collection, IndexPath, UICollectionView) -> UICollectionViewCell)? public var changeset: Changeset? = nil { didSet { if let changeset = changeset, oldValue != nil { applyChangeset(changeset) } else { collectionView?.reloadData() ensureCollectionViewSyncsWithTheDataSource() } } } open weak var collectionView: UICollectionView? = nil { didSet { guard let collectionView = collectionView else { return } associateWithCollectionView(collectionView) } } public override init() { createCell = nil } /// - parameter createCell: A closure that creates cell for a given table view and configures it with the given data source at the given index path. public init(_ createCell: @escaping (Changeset.Collection, IndexPath, UICollectionView) -> UICollectionViewCell) { self.createCell = createCell } open func numberOfSections(in collectionView: UICollectionView) -> Int { return changeset?.collection.numberOfSections ?? 0 } open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return changeset?.collection.numberOfItems(inSection: section) ?? 0 } open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let changeset = changeset else { fatalError() } if let createCell = createCell { return createCell(changeset.collection, indexPath, collectionView) } else { fatalError("Subclass of CollectionViewBinderDataSource should override and implement collectionView(_:cellForItemAt:) method if they do not initialize `createCell` closure.") } } open func applyChangeset(_ changeset: Changeset) { guard let collectionView = collectionView else { return } let diff = changeset.diff.asOrderedCollectionDiff.map { $0.asSectionDataIndexPath } if diff.isEmpty { collectionView.reloadData() } else if diff.count == 1 { applyChangesetDiff(diff) } else { collectionView.performBatchUpdates({ applyChangesetDiff(diff) }, completion: nil) } ensureCollectionViewSyncsWithTheDataSource() } open func applyChangesetDiff(_ diff: OrderedCollectionDiff<IndexPath>) { guard let collectionView = collectionView else { return } let insertedSections = diff.inserts.filter { $0.count == 1 }.map { $0[0] } if !insertedSections.isEmpty { collectionView.insertSections(IndexSet(insertedSections)) } let insertedItems = diff.inserts.filter { $0.count == 2 } if !insertedItems.isEmpty { collectionView.insertItems(at: insertedItems) } let deletedSections = diff.deletes.filter { $0.count == 1 }.map { $0[0] } if !deletedSections.isEmpty { collectionView.deleteSections(IndexSet(deletedSections)) } let deletedItems = diff.deletes.filter { $0.count == 2 } if !deletedItems.isEmpty { collectionView.deleteItems(at: deletedItems) } let updatedItems = diff.updates.filter { $0.count == 2 } if !updatedItems.isEmpty { collectionView.reloadItems(at: updatedItems) } let updatedSections = diff.updates.filter { $0.count == 1 }.map { $0[0] } if !updatedSections.isEmpty { collectionView.reloadSections(IndexSet(updatedSections)) } for move in diff.moves { if move.from.count == 2 && move.to.count == 2 { collectionView.moveItem(at: move.from, to: move.to) } else if move.from.count == 1 && move.to.count == 1 { collectionView.moveSection(move.from[0], toSection: move.to[0]) } } } private func ensureCollectionViewSyncsWithTheDataSource() { // Hack to immediately apply changes. Solves the crashing issue when performing updates before collection view is on screen. _ = collectionView?.numberOfSections } private func associateWithCollectionView(_ collectionView: UICollectionView) { objc_setAssociatedObject(collectionView, &CollectionViewBinderDataSourceAssociationKey, self, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if collectionView.reactive.hasProtocolProxy(for: UICollectionViewDataSource.self) { collectionView.reactive.dataSource.forwardTo = self } else { collectionView.dataSource = self } } } #endif
mit
f3071e0838cf472ffd9457b6a953844d
52.470833
273
0.692589
5.182956
false
false
false
false
benkraus/Operations
Operations/UserNotificationCapability.swift
1
4338
/* The MIT License (MIT) Original work Copyright (c) 2015 pluralsight Modified work Copyright 2016 Ben Kraus Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #if os(iOS) import UIKit public struct UserNotification: CapabilityType { public static let name = "UserNotificaton" public static func didRegisterUserSettings() { authorizer.completeAuthorization() } public enum Behavior { case Replace case Merge } private let settings: UIUserNotificationSettings private let behavior: Behavior public init(settings: UIUserNotificationSettings, behavior: Behavior = .Merge, application: UIApplication) { self.settings = settings self.behavior = behavior if authorizer._application == nil { authorizer.application = application } } public func requestStatus(completion: CapabilityStatus -> Void) { let registered = authorizer.areSettingsRegistered(settings) completion(registered ? .Authorized : .NotDetermined) } public func authorize(completion: CapabilityStatus -> Void) { let settings: UIUserNotificationSettings switch behavior { case .Replace: settings = self.settings case .Merge: let current = authorizer.application.currentUserNotificationSettings() settings = current?.settingsByMerging(self.settings) ?? self.settings } authorizer.authorize(settings, completion: completion) } } private let authorizer = UserNotificationAuthorizer() private class UserNotificationAuthorizer { var _application: UIApplication? var application: UIApplication { set { _application = newValue } get { guard let application = _application else { fatalError("Application not yet configured. Results would be undefined.") } return application } } var completion: (CapabilityStatus -> Void)? var settings: UIUserNotificationSettings? func areSettingsRegistered(settings: UIUserNotificationSettings) -> Bool { let current = application.currentUserNotificationSettings() return current?.contains(settings) ?? false } func authorize(settings: UIUserNotificationSettings, completion: CapabilityStatus -> Void) { guard self.completion == nil else { fatalError("Cannot request push authorization while a request is already in progress") } guard self.settings == nil else { fatalError("Cannot request push authorization while a request is already in progress") } self.completion = completion self.settings = settings application.registerUserNotificationSettings(settings) } private func completeAuthorization() { guard let completion = self.completion else { return } guard let settings = self.settings else { return } self.completion = nil self.settings = nil let registered = areSettingsRegistered(settings) completion(registered ? .Authorized : .Denied) } } #endif
mit
c654bf8b890d87715361c674c7084317
32.369231
112
0.670816
5.670588
false
false
false
false
yazhenggit/wbtest
微博项目练习/微博项目练习/Classes/Model/UserAccount.swift
1
3292
// // UserAccount.swift // 微博项目练习 // // Created by 王亚征 on 15/10/11. // Copyright © 2015年 yazheng. All rights reserved. // import UIKit class UserAccount: NSObject ,NSCoding { /// 用户是否登录标记 class var userLogon: Bool { return loadAccount != nil } var access_token:String? var expires_in:NSTimeInterval = 0 { didSet{ expiresDate = NSDate(timeIntervalSinceNow:expires_in) } } var expiresDate : NSDate? var uid:String? var name:String? var avatar_large:String? init(dict: [String:AnyObject]){ super.init() setValuesForKeysWithDictionary(dict) UserAccount.userAccount = self } override func setValue(value: AnyObject?, forUndefinedKey key: String) {} override var description: String { let properties = ["access_token", "expires_in", "uid","expiresDate","name","avatar_large"] return "\(dictionaryWithValuesForKeys(properties))" } // mark: 加载用户信息 func loadUserInfo(finished:(error:NSError?) ->()){ NetworkTools.sharedTools.loadUserInfo(uid!) { (result, error) -> () in if error != nil || result == nil{ finished(error: error) return } self.name = result!["name"] as? String self.avatar_large = result!["avatar_larage"] as? String self.saveAccount() finished(error: nil) // print(self) } } // 定义归档路径 static private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("account.plist") // 保存账号信息 func saveAccount(){ NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath) } // 静态用户账户属性 private static var userAccount: UserAccount? class var loadAccount: UserAccount? { if userAccount == nil { userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount } // 判断日期 if let date = userAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending { userAccount = nil } return userAccount } // mark: 归档 func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(access_token, forKey: "access_token") aCoder.encodeDouble(expires_in, forKey: "expires_in") aCoder.encodeObject(expiresDate, forKey: "expiresDate") aCoder.encodeObject(uid, forKey: "uid") aCoder.encodeObject(name, forKey: "name") aCoder.encodeObject(avatar_large, forKey: "avatar_large") } // mark: 解 档 required init?(coder aDecoder: NSCoder) { access_token = aDecoder.decodeObjectForKey("access_token") as? String expires_in = aDecoder.decodeDoubleForKey("expires_in") expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate uid = aDecoder.decodeObjectForKey("uid") as? String name = aDecoder.decodeObjectForKey("name") as? String avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String } }
mit
59aa83b27870125dbbe9ff6b99b92fca
32.547368
204
0.639159
4.645773
false
false
false
false
tin612/Alamofire_XMLParser
Pod/Classes/Alamofire+SwiftyXMLParser.swift
1
1392
// // Alamofire+SwiftyXMLParser.swift // Pods // // Created by Phan Thanh Tin on 3/9/17. // // import Foundation import Alamofire import SwiftyXMLParser extension DataRequest { public static func xmlResponseSerializer(option: CharacterSet? = nil) -> DataResponseSerializer<XML.Accessor> { return DataResponseSerializer { request, response, data, error in guard error == nil else { return .failure(XMLError.parseError) } if let response = response, response.statusCode == 204 { return .success(XML.parse(Data())) } guard let validData = data, validData.count > 0 else { return .failure(XMLError.parseError) } let xml: XML.Accessor if let option = option { xml = XML.parse(validData, trimming: option) } else { xml = XML.parse(validData) } return .success(xml) } } @discardableResult public func responseXML( queue: DispatchQueue? = nil, option: CharacterSet? = nil, completionHandler: @escaping (DataResponse<XML.Accessor>) -> Void ) -> Self { return response(queue: queue, responseSerializer: DataRequest.xmlResponseSerializer(option: option), completionHandler: completionHandler) } }
mit
1c477b42396fd960e96ede3cdc3f7bf2
32.142857
146
0.594109
5.025271
false
false
false
false
mshhmzh/firefox-ios
UITests/PrivateBrowsingTests.swift
5
8040
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit class PrivateBrowsingTests: KIFTestCase { private var webRoot: String! override func setUp() { webRoot = SimplePageServer.start() } override func tearDown() { do { try tester().tryFindingTappableViewWithAccessibilityLabel("home") tester().tapViewWithAccessibilityLabel("home") } catch _ { } BrowserUtils.resetToAboutHome(tester()) } func testPrivateTabDoesntTrackHistory() { // First navigate to a normal tab and see that it tracks let url1 = "\(webRoot)/numberedPage.html?page=1" tester().tapViewWithAccessibilityIdentifier("url") tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url1)\n") tester().waitForWebViewElementWithAccessibilityLabel("Page 1") tester().waitForTimeInterval(3) tester().tapViewWithAccessibilityIdentifier("url") tester().tapViewWithAccessibilityLabel("History") var tableView = tester().waitForViewWithAccessibilityIdentifier("History List") as! UITableView XCTAssertEqual(tableView.numberOfRowsInSection(0), 1) tester().tapViewWithAccessibilityLabel("Cancel") // Then try doing the same thing for a private tab tester().tapViewWithAccessibilityLabel("Menu") tester().tapViewWithAccessibilityLabel("New Private Tab") tester().tapViewWithAccessibilityIdentifier("url") tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url1)\n") tester().waitForWebViewElementWithAccessibilityLabel("Page 1") tester().tapViewWithAccessibilityIdentifier("url") tester().tapViewWithAccessibilityLabel("History") tableView = tester().waitForViewWithAccessibilityIdentifier("History List") as! UITableView XCTAssertEqual(tableView.numberOfRowsInSection(0), 1) // Exit private mode tester().tapViewWithAccessibilityLabel("Cancel") tester().tapViewWithAccessibilityLabel("Show Tabs") tester().tapViewWithAccessibilityLabel("Private Mode") tester().tapViewWithAccessibilityLabel("Page 1") } func testTabCountShowsOnlyNormalOrPrivateTabCount() { let url1 = "\(webRoot)/numberedPage.html?page=1" tester().tapViewWithAccessibilityIdentifier("url") tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url1)\n") tester().waitForWebViewElementWithAccessibilityLabel("Page 1") // Add two tabs and make sure we see the right tab count tester().tapViewWithAccessibilityLabel("Menu") tester().tapViewWithAccessibilityLabel("New Tab") tester().waitForAnimationsToFinish() var tabButton = tester().waitForViewWithAccessibilityLabel("Show Tabs") as! UIControl XCTAssertEqual(tabButton.accessibilityValue, "2", "Tab count shows 2 tabs") // Add a private tab and make sure we only see the private tab in the count, and not the normal tabs tester().tapViewWithAccessibilityLabel("Menu") tester().tapViewWithAccessibilityLabel("New Private Tab") tester().waitForAnimationsToFinish() tabButton = tester().waitForViewWithAccessibilityLabel("Show Tabs") as! UIControl XCTAssertEqual(tabButton.accessibilityValue, "1", "Private tab count should show 1 tab opened") // Switch back to normal tabs and make sure the private tab doesnt get added to the count tester().tapViewWithAccessibilityLabel("Show Tabs") tester().tapViewWithAccessibilityLabel("Private Mode") tester().tapViewWithAccessibilityLabel("Page 1") tabButton = tester().waitForViewWithAccessibilityLabel("Show Tabs") as! UIControl XCTAssertEqual(tabButton.accessibilityValue, "2", "Tab count shows 2 tabs") } func testNoPrivateTabsShowsAndHidesEmptyView() { // Do we show the empty private tabs panel view? tester().tapViewWithAccessibilityLabel("Show Tabs") tester().tapViewWithAccessibilityLabel("Private Mode") var emptyView = tester().waitForViewWithAccessibilityLabel("Private Browsing") XCTAssertTrue(emptyView.superview!.alpha == 1) // Do we hide it when we add a tab? tester().tapViewWithAccessibilityLabel("Menu") tester().tapViewWithAccessibilityLabel("New Private Tab") tester().waitForViewWithAccessibilityLabel("Show Tabs") tester().tapViewWithAccessibilityLabel("Show Tabs") emptyView = tester().waitForViewWithAccessibilityLabel("Private Browsing") XCTAssertTrue(emptyView.superview!.alpha == 0) // Remove the private tab - do we see the empty view now? let tabsView = tester().waitForViewWithAccessibilityLabel("Tabs Tray").subviews.first as! UICollectionView while tabsView.numberOfItemsInSection(0) > 0 { let cell = tabsView.cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0))! tester().swipeViewWithAccessibilityLabel(cell.accessibilityLabel, inDirection: KIFSwipeDirection.Left) tester().waitForAbsenceOfViewWithAccessibilityLabel(cell.accessibilityLabel) } emptyView = tester().waitForViewWithAccessibilityLabel("Private Browsing") XCTAssertTrue(emptyView.superview!.alpha == 1) // Exit private mode tester().tapViewWithAccessibilityLabel("Private Mode") } func testClosePrivateTabsClosesPrivateTabs() { // First, make sure that selecting the option to ON will close the tabs tester().tapViewWithAccessibilityLabel("Show Tabs") tester().tapViewWithAccessibilityLabel("Menu") tester().tapViewWithAccessibilityLabel("Settings") tester().setOn(true, forSwitchWithAccessibilityLabel: "Close Private Tabs, When Leaving Private Browsing") tester().tapViewWithAccessibilityLabel("Done") tester().tapViewWithAccessibilityLabel("Private Mode") XCTAssertEqual(numberOfTabs(), 0) tester().tapViewWithAccessibilityLabel("Menu") tester().tapViewWithAccessibilityLabel("New Private Tab") tester().waitForViewWithAccessibilityLabel("Show Tabs") tester().tapViewWithAccessibilityLabel("Show Tabs") XCTAssertEqual(numberOfTabs(), 1) tester().tapViewWithAccessibilityLabel("Private Mode") tester().waitForAnimationsToFinish() tester().tapViewWithAccessibilityLabel("Private Mode") XCTAssertEqual(numberOfTabs(), 0) tester().tapViewWithAccessibilityLabel("Private Mode") // Second, make sure selecting the option to OFF will not close the tabs tester().tapViewWithAccessibilityLabel("Menu") tester().tapViewWithAccessibilityLabel("Settings") tester().setOn(false, forSwitchWithAccessibilityLabel: "Close Private Tabs, When Leaving Private Browsing") tester().tapViewWithAccessibilityLabel("Done") tester().tapViewWithAccessibilityLabel("Private Mode") XCTAssertEqual(numberOfTabs(), 0) tester().tapViewWithAccessibilityLabel("Menu") tester().tapViewWithAccessibilityLabel("New Private Tab") tester().waitForViewWithAccessibilityLabel("Show Tabs") tester().tapViewWithAccessibilityLabel("Show Tabs") XCTAssertEqual(numberOfTabs(), 1) tester().tapViewWithAccessibilityLabel("Private Mode") tester().waitForAnimationsToFinish() tester().tapViewWithAccessibilityLabel("Private Mode") XCTAssertEqual(numberOfTabs(), 1) tester().tapViewWithAccessibilityLabel("Private Mode") } private func numberOfTabs() -> Int { let tabsView = tester().waitForViewWithAccessibilityLabel("Tabs Tray").subviews.first as! UICollectionView return tabsView.numberOfItemsInSection(0) } }
mpl-2.0
43e2bb75ef30aecae0d63c946a350aeb
44.681818
115
0.708706
6.345699
false
true
false
false
mshhmzh/firefox-ios
Client/Frontend/Widgets/ChevronView.swift
2
4472
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation enum ChevronDirection { case Left case Up case Right case Down } enum ChevronStyle { case Angular case Rounded } class ChevronView: UIView { private let Padding: CGFloat = 2.5 private var direction = ChevronDirection.Right private var lineCapStyle = CGLineCap.Round private var lineJoinStyle = CGLineJoin.Round var lineWidth: CGFloat = 3.0 var style: ChevronStyle = .Rounded { didSet { switch style { case .Rounded: lineCapStyle = CGLineCap.Round lineJoinStyle = CGLineJoin.Round case .Angular: lineCapStyle = CGLineCap.Butt lineJoinStyle = CGLineJoin.Miter } } } init(direction: ChevronDirection) { super.init(frame: CGRectZero) self.direction = direction if UIApplication.sharedApplication().userInterfaceLayoutDirection == .RightToLeft { if direction == .Left { self.direction = .Right } else if direction == .Right { self.direction = .Left } } self.backgroundColor = UIColor.clearColor() self.contentMode = UIViewContentMode.Redraw } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(rect: CGRect) { super.drawRect(rect) let strokeLength = (rect.size.height / 2) - Padding; let path: UIBezierPath switch (direction) { case .Left: path = drawLeftChevronAt(origin: CGPointMake(rect.size.width - (strokeLength + Padding), strokeLength + Padding), strokeLength:strokeLength) case .Up: path = drawUpChevronAt(origin: CGPointMake((rect.size.width - Padding) - strokeLength, (strokeLength / 2) + Padding), strokeLength:strokeLength) case .Right: path = drawRightChevronAt(origin: CGPointMake(rect.size.width - Padding, strokeLength + Padding), strokeLength:strokeLength) case .Down: path = drawDownChevronAt(origin: CGPointMake((rect.size.width - Padding) - strokeLength, (strokeLength * 1.5) + Padding), strokeLength:strokeLength) } tintColor.set() // The line thickness needs to be proportional to the distance from the arrow head to the tips. Making it half seems about right. path.lineCapStyle = lineCapStyle path.lineJoinStyle = lineJoinStyle path.lineWidth = lineWidth path.stroke(); } private func drawUpChevronAt(origin origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath { return drawChevron(leftTip: CGPointMake(origin.x-strokeLength, origin.y+strokeLength), head: CGPointMake(origin.x, origin.y), rightTip: CGPointMake(origin.x+strokeLength, origin.y+strokeLength)) } private func drawDownChevronAt(origin origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath { return drawChevron(leftTip: CGPointMake(origin.x-strokeLength, origin.y-strokeLength), head: CGPointMake(origin.x, origin.y), rightTip: CGPointMake(origin.x+strokeLength, origin.y-strokeLength)) } private func drawLeftChevronAt(origin origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath { return drawChevron(leftTip: CGPointMake(origin.x+strokeLength, origin.y-strokeLength), head: CGPointMake(origin.x, origin.y), rightTip: CGPointMake(origin.x+strokeLength, origin.y+strokeLength)) } private func drawRightChevronAt(origin origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath { return drawChevron(leftTip: CGPointMake(origin.x-strokeLength, origin.y+strokeLength), head: CGPointMake(origin.x, origin.y), rightTip: CGPointMake(origin.x-strokeLength, origin.y-strokeLength)) } private func drawChevron(leftTip leftTip: CGPoint, head: CGPoint, rightTip: CGPoint) -> UIBezierPath { let path = UIBezierPath() // Left tip path.moveToPoint(leftTip) // Arrow head path.addLineToPoint(head) // Right tip path.addLineToPoint(rightTip) return path } }
mpl-2.0
9b591fb3c9eee476fdbcd52c9245b7be
35.357724
160
0.65161
4.803437
false
false
false
false
SerhatSurguvec/IOSTest
example/AddBeaconViewController.swift
1
2685
// // AddBeaconViewController.swift // example // // Created by Serhat Sürgüveç on 5.11.2015. // Copyright © 2015 Serhat Sürgüveç. All rights reserved. // import UIKit import ObjectMapper class AddBeaconViewController: UIViewController { @IBOutlet weak var lblName: UITextField! @IBOutlet weak var lblUUID: UITextField! @IBOutlet weak var lblMajor: UITextField! @IBOutlet weak var lblMinor: UITextField! @IBOutlet weak var lblText: UITextField! override func viewDidLoad() { super.viewDidLoad() } @IBAction func onSendBroClicked(sender: UIButton) { if( lblText.text!.isEmpty || lblName.text!.isEmpty || lblUUID.text!.isEmpty || lblMinor.text!.isEmpty || lblMajor.text!.isEmpty){ alert("Please fill the blank fields.") return } let beacon : Beacon = Beacon() let info : Info = Info() info.text = lblText.text; beacon.name = lblName.text beacon.uuid = lblUUID.text beacon.major = lblMajor.text beacon.minor = lblMinor.text beacon.info = info let JSONString = Mapper().toJSONString(beacon, prettyPrint: true) MyProgressView.shared.showProgressView(view) let url = NSURL(string: "http://sheltered-inlet-4835.herokuapp.com/beacon/add") let request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5) request.HTTPBody = JSONString!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) request.HTTPMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in print(NSString(data: data!, encoding: NSUTF8StringEncoding)) let str = NSString(data: data!, encoding: NSUTF8StringEncoding); if((str?.isEqualToString("1")) != nil){ self.alert("Successful") }else{ self.alert("Failed") } MyProgressView.shared.hideProgressView() } } func alert( msg : String ){ let alert = UIAlertController(title: "Alert", message: msg, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } }
apache-2.0
3f318a8215a3afc780b4c0c5ad1e1c1d
33.333333
139
0.62472
4.869091
false
false
false
false
FandyLiu/FDDemoCollection
Swift/Apply/Apply/SegmentedImageView.swift
1
1844
// // SegmentedImageView.swift // Apply // // Created by QianTuFD on 2017/3/31. // Copyright © 2017年 fandy. All rights reserved. // import UIKit class SegmentedImageView: UIImageView { fileprivate var segmentedImages: [UIImage] fileprivate let action: (_ index: Int) -> () init(segmentedImageStrs: [String], action: @escaping (_ index: Int) -> ()) { self.action = action self.segmentedImages = segmentedImageStrs.map{ guard let image = UIImage(named: $0) else { assert(false, "\($0) 图片名称不存在") return UIImage() } return image } super.init(frame: .zero) setup() } init(segmentedImages: UIImage..., action: @escaping (_ index: Int) -> ()) { self.segmentedImages = segmentedImages self.action = action super.init(frame: .zero) setup() } func setup() { self.image = segmentedImages.first isUserInteractionEnabled = true let tapGesture = UITapGestureRecognizer() tapGesture.delegate = self addGestureRecognizer(tapGesture) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension SegmentedImageView: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { let touchPoint = touch.location(in: self) guard self.bounds.contains(touchPoint) else { return false } let segmentWidth = self.frame.width / segmentedImages.count.f let index = Int(touchPoint.x / segmentWidth) self.image = segmentedImages[index] action(index) return false } }
mit
0c58a959e50a2addfa07c4c3fc6b43d3
27.107692
108
0.603175
4.745455
false
false
false
false
mvetoshkin/MVImagePicker
MVImagePicker/Classes/Controllers/ImagePickerViewController.swift
1
16401
// // ImagePickerViewController.swift // MVImagePicker // // Created by Mikhail Vetoshkin on 22/06/16. // Copyright (c) 2016 Mikhail Vetoshkin. All rights reserved. // import MobileCoreServices import Photos import SnapKit import UIKit @objc public protocol ImagePickerViewControllerDelegate { optional func imagePickerViewControllerBeforeAssetChanged(viewController: ImagePickerViewController) optional func imagePickerViewControllerAfterAssetChanged(viewController: ImagePickerViewController) optional func imagePickerViewControllerLibraryDidSelect(viewController: ImagePickerViewController) optional func imagePickerViewControllerDidEnabled(viewController: ImagePickerViewController, isAuthorized: Bool) func imagePickerViewControllerAssetDidCreate(viewController: ImagePickerViewController, asset: PHAsset, locally: Bool) func imagePickerViewControllerAssetDidRemove(viewController: ImagePickerViewController, asset: PHAsset) func imagePickerViewControllerAssetDidSelect(viewController: ImagePickerViewController, asset: PHAsset, cell: ImagePickerPhotoCell) func imagePickerViewControllerAssetDidDeselect(viewController: ImagePickerViewController, asset: PHAsset, cell: ImagePickerPhotoCell) optional func imagePickerViewControllerAssetDidLongTap(viewController: ImagePickerViewController, asset: PHAsset, cell: ImagePickerPhotoCell) optional func imagePickerViewControllerAlbumOpened(viewController: ImagePickerViewController, album: PHAssetCollection) } @objc public protocol ImagePickerViewControllerScrollDelegate { optional func imagePickerViewControllerWillBeginDragging(scrollView: UIScrollView) optional func imagePickerViewControllerDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) optional func imagePickerViewControllerDidScroll(scrollView: UIScrollView) } public class ImagePickerViewController: UIViewController, PHPhotoLibraryChangeObserver, UIImagePickerControllerDelegate, UINavigationControllerDelegate, ImagePickerPhotosViewControllerDelegate, ImagePickerSourcesViewDelegate { public static let sourcesHeight: CGFloat = 40 public var newPhotoAlbumName: String? = nil public var multipleSelection: Bool = false public weak var delegate: ImagePickerViewControllerDelegate? public weak var scrollDelegate: ImagePickerViewControllerScrollDelegate? private var photosDataSource = ImagePickerPhotosDataSource() private let libraryView = UIView(frame: CGRectZero) private var allAssetsFetchResults: PHFetchResult? private var isAuthorized = false private var isAssetCreating = false // MARK: Lazy init lazy private var sourcesView: ImagePickerSourcesView = { let el = ImagePickerSourcesView(frame: CGRectZero) el.delegate = self return el }() lazy private var accessDeniedView: ImagePickerAccessDeniedView = { let gesture = UITapGestureRecognizer(target: self, action: #selector(ImagePickerViewController.imagePickerAccessDeniedViewDidTap(_:))) gesture.numberOfTapsRequired = 1 let el = ImagePickerAccessDeniedView(frame: CGRectZero) el.userInteractionEnabled = true el.addGestureRecognizer(gesture) return el }() // MARK: Class init deinit { PHPhotoLibrary.sharedPhotoLibrary().unregisterChangeObserver(self) } // MARK: Life cycle override public func viewDidLoad() { super.viewDidLoad() self.title = "Image Picker" self.view.backgroundColor = UIColor.ipLightGrayColor() self.addCloseButton() self.sourcesView.hidden = true self.libraryView.hidden = true self.accessDeniedView.hidden = true self.view.addSubview(self.sourcesView) self.view.addSubview(self.libraryView) self.view.addSubview(self.accessDeniedView) self.setupConstraints() self.sourcesView.showLibraryPicker() PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self) PHPhotoLibrary.requestAuthorization({ (status) -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in if status == PHAuthorizationStatus.Authorized { self.enableLibrary() } else { self.disableLibrary() } }) }) } // MARK: Layout private func setupConstraints() { self.sourcesView.snp_makeConstraints { (make) -> Void in make.left.equalTo(self.view) make.right.equalTo(self.view) make.top.equalTo(0) make.height.equalTo(ImagePickerViewController.sourcesHeight) } self.libraryView.snp_makeConstraints { (make) -> Void in make.left.equalTo(self.view) make.top.equalTo(self.sourcesView.snp_bottom) make.right.equalTo(self.view) make.bottom.equalTo(self.view) } self.accessDeniedView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(self.view) } } // MARK: PHPhotoLibraryChangeObserver public func photoLibraryDidChange(changeInstance: PHChange) { dispatch_async(dispatch_get_main_queue(), { () -> Void in self.delegate?.imagePickerViewControllerAfterAssetChanged?(self) let locally = self.isAssetCreating self.isAssetCreating = false if self.allAssetsFetchResults == nil { return } if let changeDetails = changeInstance.changeDetailsForFetchResult(self.allAssetsFetchResults!) { self.allAssetsFetchResults = changeDetails.fetchResultAfterChanges for obj in changeDetails.insertedObjects { let asset = obj as! PHAsset self.delegate?.imagePickerViewControllerAssetDidCreate(self, asset: asset, locally: locally) } for obj in changeDetails.removedObjects { let asset = obj as! PHAsset if let idx = self.photosDataSource.selectedAssets.indexOf(asset) { self.photosDataSource.selectedAssets.removeAtIndex(idx) } self.delegate?.imagePickerViewControllerAssetDidRemove(self, asset: asset) } } }) } // MARK: UIImagePickerControllerDelegate public func imagePickerControllerDidCancel(picker: UIImagePickerController) { self.dismissViewControllerAnimated(true, completion: nil) self.sourcesView.showLibraryPicker() self.isAssetCreating = false } public func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { self.delegate?.imagePickerViewControllerBeforeAssetChanged?(self) let mediaType = info[UIImagePickerControllerMediaType] as! String if CFStringCompare(mediaType, mediaType, CFStringCompareFlags()) == CFComparisonResult.CompareEqualTo { var imageToSave = info[UIImagePickerControllerOriginalImage] as! UIImage if let img = info[UIImagePickerControllerEditedImage] as? UIImage { imageToSave = img } self.saveAsset(imageToSave) } self.dismissViewControllerAnimated(true, completion: nil) self.sourcesView.showLibraryPicker() } // MARK: ImagePickerPhotosViewControllerDelegate func imagePickerPhotosViewControllerAssetDidSelect(viewController: ImagePickerPhotosViewController, asset: PHAsset, cell: ImagePickerPhotoCell) { self.delegate?.imagePickerViewControllerAssetDidSelect(self, asset: asset, cell: cell) } func imagePickerPhotosViewControllerAssetDidDeselect(viewController: ImagePickerPhotosViewController, asset: PHAsset, cell: ImagePickerPhotoCell) { self.delegate?.imagePickerViewControllerAssetDidDeselect(self, asset: asset, cell: cell) } func imagePickerPhotosViewControllerAssetDidLongTap(viewController: ImagePickerPhotosViewController, asset: PHAsset, cell: ImagePickerPhotoCell) { self.delegate?.imagePickerViewControllerAssetDidLongTap?(self, asset: asset, cell: cell) } func imagePickerPhotosViewControllerAlbumOpened(viewController: ImagePickerPhotosViewController, album: PHAssetCollection) { self.delegate?.imagePickerViewControllerAlbumOpened?(self, album: album) } // MARK: ImagePickerSourcesViewDelegate func imagePickerSourcesViewCameraDidTap(view: ImagePickerSourcesView) { if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) { self.sourcesView.showLibraryPicker() return } let cameraUI = UIImagePickerController() cameraUI.allowsEditing = true cameraUI.delegate = self cameraUI.mediaTypes = [kUTTypeImage as String] cameraUI.modalPresentationStyle = UIModalPresentationStyle.CurrentContext cameraUI.sourceType = UIImagePickerControllerSourceType.Camera self.isAssetCreating = true self.presentViewController(cameraUI, animated: true, completion: nil) } func imagePickerSourcesViewLibraryDidTap(view: ImagePickerSourcesView) { self.delegate?.imagePickerViewControllerLibraryDidSelect?(self) } // MARK: Handlers @objc private func closeButtonDidTap(button: UIButton) { self.dismissViewControllerAnimated(true, completion: nil) } @objc private func imagePickerAccessDeniedViewDidTap(gesture: UITapGestureRecognizer) { let url = NSURL(string: UIApplicationOpenSettingsURLString) UIApplication.sharedApplication().openURL(url!) } // MARK: Private methods private func addCloseButton() { let button = UIButton(frame: CGRectMake(0, 0, 16, 16)) let buttonImage = UIImage(named: "close-icon")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) button.tintColor = UIColor.whiteColor() button.addTarget(self, action: #selector(ImagePickerViewController.closeButtonDidTap(_:)), forControlEvents: UIControlEvents.TouchUpInside) button.setBackgroundImage(buttonImage, forState: UIControlState.Normal) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button) } private func disableLibrary() { self.isAuthorized = false self.sourcesView.hidden = true self.libraryView.hidden = true self.accessDeniedView.hidden = false self.delegate?.imagePickerViewControllerDidEnabled?(self, isAuthorized: false) } private func enableLibrary() { self.isAuthorized = true self.sourcesView.hidden = false self.libraryView.hidden = false self.accessDeniedView.hidden = true let vc = ImagePickerAlbumsViewController(photosDataSource: photosDataSource) vc.delegate = self vc.multipleSelection = self.multipleSelection vc.scrollDelegate = self.scrollDelegate let navigationController = UINavigationController(rootViewController: vc) navigationController.setNavigationBarHidden(true, animated: false) self.addChildViewController(navigationController) self.libraryView.addSubview(navigationController.view) navigationController.view.snp_makeConstraints { (make) -> Void in make.edges.equalTo(self.libraryView) } self.allAssetsFetchResults = ImagePickerPhotosDataSource.fetchAssets(nil) self.delegate?.imagePickerViewControllerDidEnabled?(self, isAuthorized: true) } private func imageWithText(text: String) -> UIImage { let initialSize = CGSizeMake(640, 640) var size = initialSize UIGraphicsBeginImageContext(size) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor) CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height)) size = CGSizeMake(600, 600) CGContextSetFillColorWithColor(context, UIColor.colorWithHex("#f2f2f2").CGColor) CGContextFillRect(context, CGRectMake(20, 20, size.width, size.height)) size = CGSizeMake(560, 560) CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor) CGContextFillRect(context, CGRectMake(40, 40, size.width, size.height)) let fontSize: CGFloat = text.characters.count <= 30 ? 80 : 70 let font = UIFont.systemFontOfSize(fontSize) let paragraphStyle: NSMutableParagraphStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle paragraphStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping paragraphStyle.alignment = NSTextAlignment.Center paragraphStyle.hyphenationFactor = 0 let attributes = [ NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor.colorWithHex("#242b30"), NSParagraphStyleAttributeName: paragraphStyle ] size = CGSizeMake(520, 520); let textRect = text.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil) let x = (initialSize.width / 2) - (textRect.size.width / 2) let y = (initialSize.height / 2) - (textRect.size.height / 2) let rect = CGRectMake(x, y, textRect.size.width, textRect.size.height); text.drawInRect(rect, withAttributes: attributes) let newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } private func findAppAlbum() -> PHAssetCollection? { if let albName = self.newPhotoAlbumName { var appAlbum: PHAssetCollection? = nil let albums = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.Album, subtype: PHAssetCollectionSubtype.Any, options: nil) albums.enumerateObjectsUsingBlock { (album, idx, stop) -> Void in let alb = album as! PHAssetCollection if alb.localizedTitle == albName { appAlbum = alb stop.memory = true } } return appAlbum } return nil } // MARK: Public methods public func saveAsset(image: UIImage) { let library = PHPhotoLibrary.sharedPhotoLibrary() typealias saveImageType = (collection: PHAssetCollection?) -> Void let saveImage: saveImageType = { (collection: PHAssetCollection?) -> Void in library.performChanges({ () -> Void in if let coll = collection, let request = PHAssetCollectionChangeRequest(forAssetCollection: coll) { let r = PHAssetChangeRequest.creationRequestForAssetFromImage(image) if let plh = r.placeholderForCreatedAsset { request.addAssets([plh]) } } else { PHAssetChangeRequest.creationRequestForAssetFromImage(image) } }, completionHandler: { (_, error) -> Void in if let err = error { print("Error creating asset: \(err.description)") } }) } if let albName = self.newPhotoAlbumName { if let ca = self.findAppAlbum() { saveImage(collection: ca) } else { do { try library.performChangesAndWait({ () -> Void in PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(albName) }) } catch let error { print("Error creating collection: \(error)") return } if let ca = self.findAppAlbum() { saveImage(collection: ca) } } } else { saveImage(collection: nil) } } public func selectAsset(asset: PHAsset) { self.photosDataSource.selectAsset(asset) } public func deselectAsset(asset: PHAsset) { self.photosDataSource.deselectAsset(asset) } }
mit
a39aa5325afb9271e63d25b7a99c22a1
37.409836
151
0.686604
5.708667
false
false
false
false
amco/couchbase-lite-ios
Swift/Query.swift
1
9746
// // Query.swift // CouchbaseLite // // Copyright (c) 2017 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /// A database query. /// A Query instance can be constructed by calling one of the select class methods. public class Query { /// A Parameters object used for setting values to the query parameters defined /// in the query. All parameters defined in the query must be given values /// before running the query, or the query will fail. /// /// The returned Parameters object will be readonly. public var parameters: Parameters? { get { return params } set { if let p = newValue { params = Parameters(parameters: p, readonly: true) } else { params = nil } applyParameters() } } /// Executes the query. The returning an enumerator that returns result rows one at a time. /// You can run the query any number of times, and you can even have multiple enumerators active /// at once. /// /// The results come from a snapshot of the database taken at the moment -run: is called, so they /// will not reflect any changes made to the database afterwards. /// /// - Returns: The ResultSet object representing the query result. /// - Throws: An error on failure, or if the query is invalid. public func execute() throws -> ResultSet { applyParameters() return try ResultSet(impl: queryImpl!.execute()) } /// Returns a string describing the implementation of the compiled query. /// This is intended to be read by a developer for purposes of optimizing the query, especially /// to add database indexes. It's not machine-readable and its format may change. /// /// As currently implemented, the result is two or more lines separated by newline characters: /// * The first line is the SQLite SELECT statement. /// * The subsequent lines are the output of SQLite's "EXPLAIN QUERY PLAN" command applied to that /// statement; for help interpreting this, see https://www.sqlite.org/eqp.html . The most /// important thing to know is that if you see "SCAN TABLE", it means that SQLite is doing a /// slow linear scan of the documents instead of using an index. /// /// - Returns: The implementation detail of the compiled query. /// - Throws: An error if the query is not valid. public func explain() throws -> String { prepareQuery() return try queryImpl!.explain() } /// Adds a query change listener. Changes will be posted on the main queue. /// /// - Parameter listener: The listener to post changes. /// - Returns: An opaque listener token object for removing the listener. @discardableResult public func addChangeListener( _ listener: @escaping (QueryChange) -> Void) -> ListenerToken { return self.addChangeListener(withQueue: nil, listener) } /// Adds a query change listener with the dispatch queue on which changes /// will be posted. If the dispatch queue is not specified, the changes will be /// posted on the main queue. /// /// - Parameters: /// - queue: The dispatch queue. /// - listener: The listener to post changes. /// - Returns: An opaque listener token object for removing the listener. @discardableResult public func addChangeListener(withQueue queue: DispatchQueue?, _ listener: @escaping (QueryChange) -> Void) -> ListenerToken { lock.lock() defer { lock.unlock() } prepareQuery() let token = self.queryImpl!.addChangeListener(with: queue, listener: { (change) in let rows: ResultSet?; if let rs = change.results { rows = ResultSet(impl: rs) } else { rows = nil; } listener(QueryChange(query: self, results: rows, error: change.error)) }) if tokens.count == 0 { database!.addQuery(self) } tokens.add(token) return token } /// Removes a change listener wih the given listener token. /// /// - Parameter token: The listener token. public func removeChangeListener(withToken token: ListenerToken) { lock.lock() prepareQuery() queryImpl!.removeChangeListener(with: token) tokens.remove(token) if tokens.count == 0 { database!.removeQuery(self) } lock.unlock() } // MARK: Internal var params: Parameters? var selectImpl: [CBLQuerySelectResult]? var distinct = false var fromImpl: CBLQueryDataSource? var joinsImpl: [CBLQueryJoin]? var database: Database? var whereImpl: CBLQueryExpression? var groupByImpl: [CBLQueryExpression]? var havingImpl: CBLQueryExpression? var orderingsImpl: [CBLQueryOrdering]? var limitImpl: CBLQueryLimit? var queryImpl: CBLQuery? var tokens = NSMutableSet() var lock = NSRecursiveLock() init() { } func prepareQuery() { lock.lock() defer { lock.unlock() } if queryImpl != nil { return } precondition(fromImpl != nil, "From statement is required.") assert(selectImpl != nil && database != nil) if self.distinct { queryImpl = CBLQueryBuilder.selectDistinct( selectImpl!, from: fromImpl!, join: joinsImpl, where: whereImpl, groupBy: groupByImpl, having: havingImpl, orderBy: orderingsImpl, limit: limitImpl) } else { queryImpl = CBLQueryBuilder.select( selectImpl!, from: fromImpl!, join: joinsImpl, where: whereImpl, groupBy: groupByImpl, having: havingImpl, orderBy: orderingsImpl, limit: limitImpl) } } func applyParameters() { lock.lock() prepareQuery() queryImpl!.parameters = self.params?.toImpl() lock.unlock() } func stop() { lock.lock() database!.removeQuery(self) tokens.removeAllObjects() lock.unlock() } func copy(_ query: Query) { self.database = query.database self.selectImpl = query.selectImpl self.distinct = query.distinct self.fromImpl = query.fromImpl self.joinsImpl = query.joinsImpl self.whereImpl = query.whereImpl self.groupByImpl = query.groupByImpl self.havingImpl = query.havingImpl self.orderingsImpl = query.orderingsImpl self.limitImpl = query.limitImpl } } /// A factory class to create a Select instance. public final class QueryBuilder { /// Create a SELECT statement instance that you can use further /// (e.g. calling the from() function) to construct the complete query statement. /// /// - Parameter results: The array of the SelectResult object for specifying the returned values. /// - Returns: A Select object. public static func select(_ results: SelectResultProtocol...) -> Select { return select(results) } /// Create a SELECT statement instance that you can use further /// (e.g. calling the from() function) to construct the complete query statement. /// /// - Parameter results: The array of the SelectResult object for specifying the returned values. /// - Returns: A Select object. public static func select(_ results: [SelectResultProtocol]) -> Select { return Select(impl: QuerySelectResult.toImpl(results: results), distinct: false) } /// Create a SELECT DISTINCT statement instance that you can use further /// (e.g. calling the from() function) to construct the complete query statement. /// /// - Parameter results: The array of the SelectResult object for specifying the returned values. /// - Returns: A Select distinct object. public static func selectDistinct(_ results: SelectResultProtocol...) -> Select { return selectDistinct(results) } /// Create a SELECT DISTINCT statement instance that you can use further /// (e.g. calling the from() function) to construct the complete query statement. /// /// - Parameter results: The array of the SelectResult object for specifying the returned values. /// - Returns: A Select distinct object. public static func selectDistinct(_ results: [SelectResultProtocol]) -> Select { return Select(impl: QuerySelectResult.toImpl(results: results), distinct: true) } } extension Query: CustomStringConvertible { public var description: String { prepareQuery() return "\(type(of: self))[\(self.queryImpl!.description)]" } }
apache-2.0
6a9c7fa2e25d6b953562869f5dc2f553
32.606897
102
0.617074
4.822365
false
false
false
false
HTWDD/htwcampus
HTWDD/Main Categories/General/PersistenceService.swift
1
5141
// // PersistenceService.swift // HTWDD // // Created by Benjamin Herzog on 30.10.17. // Copyright © 2017 HTW Dresden. All rights reserved. // import Foundation import RxSwift import KeychainAccess class PersistenceService: Service { private enum Const { static let service = "de.htw-dresden.ios" static let accessGroup = "3E4PGPNR47.keychain-group" static let scheduleKey = "htw-dresden.schedule.auth" static let scheduleHiddenKey = "htw-dresden.schedule.hidden" static let scheduleColorsKey = "htw-dresden.schedule.colors" static let gradesKey = "htw-dresden.grades.auth" static let scheduleCacheKey = "htw-dresden.schedule.cache" static let gradesCacheKey = "htw-dresden.grades.cache" static let examsCacheKey = "htw-dresden.exams.cache" } struct Response { var schedule: ScheduleService.Auth? var grades: GradeService.Auth? } private let keychain = Keychain(service: Const.service, accessGroup: Const.accessGroup) // MARK: - Load func load(parameters: () = ()) -> Observable<Response> { let res = Response(schedule: self.load(type: ScheduleService.Auth.self, key: Const.scheduleKey), grades: self.load(type: GradeService.Auth.self, key: Const.gradesKey)) return Observable.just(res) } private func load<T: Codable>(type: T.Type, key: String) -> T? { let savedData = (try? keychain.getData(key)).flatMap(identity) guard let data = savedData else { return nil } return try? JSONDecoder().decode(T.self, from: data) } func loadHidden() -> [Int: Bool] { return self.load(type: [Int: Bool].self, key: Const.scheduleHiddenKey) ?? [:] } func loadScheduleColors() -> [Int: UInt] { return self.load(type: [Int: UInt].self, key: Const.scheduleColorsKey) ?? [:] } func loadScheduleCache() -> Observable<ScheduleService.Information> { guard let saved = self.load(type: ScheduleService.Information.self, key: Const.scheduleCacheKey) else { return Observable.empty() } return Observable.just(saved) } func loadGradesCache() -> Observable<[GradeService.Information]> { guard let saved = self.load(type: [GradeService.Information].self, key: Const.gradesCacheKey) else { return Observable.empty() } return Observable.just(saved) } func loadExamsCache() -> Observable<ExamsService.Information> { guard let saved = self.load(type: ExamsService.Information.self, key: Const.examsCacheKey) else { return Observable.empty() } return Observable.just(saved) } // MARK: - Save func save(_ schedule: ScheduleService.Auth) { self.save(object: schedule, key: Const.scheduleKey) } func save(_ hidden: [Int: Bool]) { var all = self.loadHidden() all.merge(hidden, uniquingKeysWith: { $0 || $1 }) self.save(object: all, key: Const.scheduleHiddenKey) } func save(_ colors: [Int: UInt]) { self.save(object: colors, key: Const.scheduleColorsKey) } func save(_ grade: GradeService.Auth) { self.save(object: grade, key: Const.gradesKey) } func save(_ grades: [GradeService.Information]) { self.save(objects: grades, key: Const.gradesCacheKey) } func save(_ lectures: ScheduleService.Information) { self.save(object: lectures, key: Const.scheduleCacheKey) } func save(_ exams: ExamsService.Information) { self.save(object: exams, key: Const.examsCacheKey) } private func save<T: Encodable>(object: T, key: String) { guard let data = try? JSONEncoder().encode(object) else { return } try? self.keychain.set(data, key: key) } private func save<T: Encodable>(objects: [T], key: String) { guard let data = try? JSONEncoder().encode(objects) else { return } try? self.keychain.set(data, key: key) } // MARK: - Remove // TODO: Remove colors, hidden upon changing study group. Or maybe leave for convenience??? func clear() { self.removeGrade() self.removeSchedule() self.removeScheduleHidden() self.removeScheduleColors() self.removeGradesCache() self.removeScheduleCache() } func removeSchedule() { self.remove(key: Const.scheduleKey) } func removeScheduleHidden() { self.remove(key: Const.scheduleHiddenKey) } func removeScheduleColors() { self.remove(key: Const.scheduleColorsKey) } func removeGrade() { self.remove(key: Const.gradesKey) } func removeScheduleCache() { self.remove(key: Const.scheduleCacheKey) } func removeExamsCache() { self.remove(key: Const.examsCacheKey) } func removeGradesCache() { self.remove(key: Const.gradesCacheKey) } private func remove(key: String) { try? self.keychain.remove(key) } }
mit
232b7a1d946e2d1639c51b44438dfe68
29.595238
111
0.626459
4.028213
false
false
false
false
hacktoolkit/hacktoolkit-ios_lib
Hacktoolkit/lib/GitHub/GitHubClient.swift
1
2052
// // GitHubClient.swift // // Created by Hacktoolkit (@hacktoolkit) and Jonathan Tsai (@jontsai) // Copyright (c) 2014 Hacktoolkit. All rights reserved. // import Foundation let GITHUB_API_CONSUMER_KEY = HTKUtils.getStringFromInfoBundleForKey("GITHUB_API_CONSUMER_KEY") let GITHUB_API_CONSUMER_SECRET = HTKUtils.getStringFromInfoBundleForKey("GITHUB_API_CONSUMER_SECRET") let GITHUB_API_BASE_URL = "https://api.github.com" class GitHubClient { var cache = [String:AnyObject]() class var sharedInstance : GitHubClient { struct Static { static var token : dispatch_once_t = 0 static var instance : GitHubClient? = nil } dispatch_once(&Static.token) { Static.instance = GitHubClient() } return Static.instance! } func makeApiRequest(resource: String, callback: (AnyObject) -> ()) { var apiUrl = "\(GITHUB_API_BASE_URL)\(resource)" // temporarily include App key to increase rate limit // https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications apiUrl = "\(apiUrl)?client_id=\(GITHUB_API_CONSUMER_KEY)&client_secret=\(GITHUB_API_CONSUMER_SECRET)" let request = NSMutableURLRequest(URL: NSURL(string: apiUrl)!) NSLog("Hitting API: \(apiUrl)") var cachedResult: AnyObject? = cache[apiUrl] if cachedResult != nil { callback(cachedResult!) } else { NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: { (response, data, error) in var errorValue: NSError? = nil let result: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &errorValue) if result != nil { callback(result!) self.cache[apiUrl] = result! } else { HTKNotificationUtils.displayNetworkErrorMessage() } }) } } }
mit
82c050d8d70416567591e2c2c6975aef
37
145
0.627193
4.431965
false
false
false
false
DaftMobile/ios4beginners_2017
Class 6/Class6.playground/Pages/CollectionViews.xcplaygroundpage/Contents.swift
1
3364
//: A UIKit based Playground for presenting user interface import UIKit import PlaygroundSupport class MyCustomCollectionViewCell: UICollectionViewCell { let titleLabel: UILabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(titleLabel) setupConstraints() setupFont() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) contentView.addSubview(titleLabel) setupConstraints() setupFont() } private func setupConstraints() { addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0)) addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0)) titleLabel.translatesAutoresizingMaskIntoConstraints = false } private func setupFont() { titleLabel.font = UIFont.systemFont(ofSize: 14.0, weight: .black) } } class MyViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { var collectionView: UICollectionView! var layout: UICollectionViewFlowLayout! override func loadView() { self.view = UIView() view.backgroundColor = .white layout = UICollectionViewFlowLayout() collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) view.addSubview(collectionView) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[collectionView]|", options: [], metrics: nil, views: ["collectionView": collectionView])) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[collectionView]|", options: [], metrics: nil, views: ["collectionView": collectionView])) collectionView.translatesAutoresizingMaskIntoConstraints = false } override func viewDidLoad() { super.viewDidLoad() collectionView.delegate = self collectionView.dataSource = self collectionView.register(MyCustomCollectionViewCell.self, forCellWithReuseIdentifier: "CELL") collectionView.backgroundColor = .white layout.itemSize = CGSize(width: 100, height: 150) layout.minimumLineSpacing = 20 layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 30, right: 10) } // func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { // let width = max(30, (65 * (indexPath.item + 41)) % 217) // let height = max(30, (45 * (indexPath.item + 53)) % 132) // return CGSize(width: width, height: height) // } func numberOfSections(in collectionView: UICollectionView) -> Int { return 4 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 16 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CELL", for: indexPath) as? MyCustomCollectionViewCell else { fatalError() } cell.backgroundColor = UIColor.lightGray cell.titleLabel.text = "[\(indexPath.section):\(indexPath.item)]" cell.titleLabel.textColor = .white return cell } } // Present the view controller in the Live View window PlaygroundPage.current.liveView = MyViewController()
apache-2.0
a884245f0d815b0380d3be31e50f3b26
37.666667
165
0.764863
4.558266
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift
57
3427
// // DispatchQueueConfiguration.swift // RxSwift // // Created by Krunoslav Zaher on 7/23/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import Foundation import Dispatch struct DispatchQueueConfiguration { let queue: DispatchQueue let leeway: DispatchTimeInterval } private func dispatchInterval(_ interval: Foundation.TimeInterval) -> DispatchTimeInterval { precondition(interval >= 0.0) // TODO: Replace 1000 with something that actually works // NSEC_PER_MSEC returns 1000000 return DispatchTimeInterval.milliseconds(Int(interval * 1000.0)) } extension DispatchQueueConfiguration { func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { let cancel = SingleAssignmentDisposable() queue.async { if cancel.isDisposed { return } cancel.setDisposable(action(state)) } return cancel } func scheduleRelative<StateType>(_ state: StateType, dueTime: Foundation.TimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { let deadline = DispatchTime.now() + dispatchInterval(dueTime) let compositeDisposable = CompositeDisposable() let timer = DispatchSource.makeTimerSource(queue: queue) timer.scheduleOneshot(deadline: deadline) // TODO: // This looks horrible, and yes, it is. // It looks like Apple has made a conceputal change here, and I'm unsure why. // Need more info on this. // It looks like just setting timer to fire and not holding a reference to it // until deadline causes timer cancellation. var timerReference: DispatchSourceTimer? = timer let cancelTimer = Disposables.create { timerReference?.cancel() timerReference = nil } timer.setEventHandler(handler: { if compositeDisposable.isDisposed { return } _ = compositeDisposable.insert(action(state)) cancelTimer.dispose() }) timer.resume() _ = compositeDisposable.insert(cancelTimer) return compositeDisposable } func schedulePeriodic<StateType>(_ state: StateType, startAfter: TimeInterval, period: TimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { let initial = DispatchTime.now() + dispatchInterval(startAfter) var timerState = state let timer = DispatchSource.makeTimerSource(queue: queue) timer.scheduleRepeating(deadline: initial, interval: dispatchInterval(period), leeway: leeway) // TODO: // This looks horrible, and yes, it is. // It looks like Apple has made a conceputal change here, and I'm unsure why. // Need more info on this. // It looks like just setting timer to fire and not holding a reference to it // until deadline causes timer cancellation. var timerReference: DispatchSourceTimer? = timer let cancelTimer = Disposables.create { timerReference?.cancel() timerReference = nil } timer.setEventHandler(handler: { if cancelTimer.isDisposed { return } timerState = action(timerState) }) timer.resume() return cancelTimer } }
apache-2.0
c38c5378f34faf0437fe6da8a1588d81
31.942308
164
0.643024
5.319876
false
false
false
false
rudkx/swift
test/decl/protocol/req/associated_type_inference_fixed_type_experimental_inference.swift
1
29171
// RUN: %target-typecheck-verify-swift -enable-experimental-associated-type-inference // RUN: not %target-swift-frontend -typecheck -enable-experimental-associated-type-inference -dump-type-witness-systems %s 2>&1 | %FileCheck %s protocol P1 where A == Never { associatedtype A } // CHECK-LABEL: Abstract type witness system for conformance of S1 to P1: { // CHECK-NEXT: A => Never, // CHECK-NEXT: } struct S1: P1 {} protocol P2a { associatedtype A } protocol P2b: P2a where A == Never {} protocol P2c: P2b {} // CHECK-LABEL: Abstract type witness system for conformance of S2a to P2a: { // CHECK-NEXT: A => Never, // CHECK-NEXT: } struct S2a: P2b {} // CHECK-LABEL: Abstract type witness system for conformance of S2b to P2a: { // CHECK-NEXT: A => Never, // CHECK-NEXT: } struct S2b: P2c {} // Fixed type witnesses can reference dependent members. protocol P3a { associatedtype A associatedtype B } protocol P3b: P3a where A == [B] {} // CHECK-LABEL: Abstract type witness system for conformance of S3 to P3a: { // CHECK-NEXT: A => [Self.B], // CHECK-NEXT: } struct S3: P3b { typealias B = Never } protocol P4a where A == [B] { associatedtype A associatedtype B } protocol P4b {} extension P4b { typealias B = Self } // CHECK-LABEL: Abstract type witness system for conformance of S4 to P4a: { // CHECK-NEXT: A => [Self.B], // CHECK-NEXT: } struct S4: P4a, P4b {} // Self is a valid fixed type witness. protocol P5a { associatedtype A } protocol P5b: P5a where A == Self {} // CHECK-LABEL: Abstract type witness system for conformance of S5<X> to P5a: { // CHECK-NEXT: A => Self, // CHECK-NEXT: } struct S5<X>: P5b {} // OK, A := S5<X> protocol P6 where A == Never { // expected-error {{same-type constraint type 'Never' does not conform to required protocol 'P6'}} // expected-error@+2 {{same-type constraint type 'Never' does not conform to required protocol 'P6'}} // expected-note@+1 {{protocol requires nested type 'A}} associatedtype A: P6 } // CHECK-LABEL: Abstract type witness system for conformance of S6 to P6: { // CHECK-NEXT: A => (unresolved){{$}} // CHECK-NEXT: } struct S6: P6 {} // expected-error {{type 'S6' does not conform to protocol 'P6'}} protocol P7a where A == Never { associatedtype A } // expected-error@+2 {{'Self.A' cannot be equal to both 'Bool' and 'Never'}} // expected-note@+1 {{same-type constraint 'Self.A' == 'Never' implied here}} protocol P7b: P7a where A == Bool {} // CHECK-LABEL: Abstract type witness system for conformance of S7 to P7a: { // CHECK-NEXT: A => Never, // CHECK-NEXT: } struct S7: P7b {} protocol P8a where A == Never { associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}} } protocol P8b where A == Bool { associatedtype A } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P8a: { // CHECK-NEXT: A => (ambiguous), // CHECK-NEXT: } struct Conformer: P8a, P8b {} // expected-error@-1 {{type 'Conformer' does not conform to protocol 'P8a'}} // expected-error@-2 {{type 'Conformer' does not conform to protocol 'P8b'}} } protocol P9a where A == Never { associatedtype A } protocol P9b: P9a { associatedtype A } // CHECK-LABEL: Abstract type witness system for conformance of S9a to P9b: { // CHECK-NEXT: A => Never, // CHECK-NEXT: } struct S9a: P9b {} // expected-error@+3 {{type 'S9b' does not conform to protocol 'P9a'}} // expected-error@+2 {{'P9a' requires the types 'S9b.A' (aka 'Bool') and 'Never' be equivalent}} // expected-note@+1 {{requirement specified as 'Self.A' == 'Never' [with Self = S9b]}} struct S9b: P9b { typealias A = Bool } struct S9c: P9b { // OK, S9c.A does not contradict Self.A == Never. typealias Sugar = Never typealias A = Sugar } protocol P10a where A == Never { associatedtype A } protocol P10b {} extension P10b { typealias A = Bool } // FIXME: 'P10 extension.A' should not be considered a viable type witness; // instead, the compiler should infer A := Never and synthesize S10.A. // expected-error@+3 {{type 'S10' does not conform to protocol 'P10a'}} // expected-error@+2 {{'P10a' requires the types 'S10.A' (aka 'Bool') and 'Never' be equivalent}} // expected-note@+1 {{requirement specified as 'Self.A' == 'Never' [with Self = S10]}} struct S10: P10b, P10a {} protocol P11a { associatedtype A } protocol P11b: P11a where A == Never {} protocol Q11 { associatedtype A } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to Q11: { // CHECK-NEXT: A => Never, // CHECK-NEXT: } struct Conformer: Q11, P11b {} } protocol P12 where A == B { associatedtype A associatedtype B func foo(arg: A) } // CHECK-LABEL: Abstract type witness system for conformance of S12 to P12: { // CHECK-NEXT: B => Self.A, // CHECK-NEXT: } struct S12: P12 { func foo(arg: Never) {} } protocol P13a { associatedtype A func foo(arg: A) } protocol P13b { associatedtype B } protocol P13c: P13a, P13b where A == B {} // CHECK-LABEL: Abstract type witness system for conformance of S13 to P13b: { // CHECK-NEXT: B => Self.A, // CHECK-NEXT: } struct S13: P13c { func foo(arg: Never) {} } protocol P14 { associatedtype A = Array<Self> } do { // CHECK-LABEL: Abstract type witness system for conformance of Outer<Element>.Conformer to P14: { // CHECK-NEXT: A => Array<Self>, // CHECK-NEXT: } struct Outer<Element> { struct Conformer: P14 {} } } protocol P15a { associatedtype A associatedtype B = Never } protocol P15b: P15a where A == B {} do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P15a: { // CHECK-NEXT: A => Never, [[EQUIV_CLASS:0x[0-9a-f]+]] // CHECK-NEXT: B => Never, [[EQUIV_CLASS]] // CHECK-NEXT: } struct Conformer: P15b {} } protocol P16a where A == B { associatedtype A associatedtype B = Never } protocol P16b: P16a {} do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P16a: { // CHECK-NEXT: A => Never, [[EQUIV_CLASS:0x[0-9a-f]+]] // CHECK-NEXT: B => Never, [[EQUIV_CLASS]] // CHECK-NEXT: } struct Conformer: P16b {} } protocol P17a where A == Never { associatedtype A = B // expected-note {{protocol requires nested type 'A'; do you want to add it?}} associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}} } protocol P17b { associatedtype A = B // expected-note {{protocol requires nested type 'A'; do you want to add it?}} associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}} } protocol P17c where A == Never { associatedtype A associatedtype B = A } protocol P17d { associatedtype A = B associatedtype B = Int } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer1 to P17a: { // CHECK-NEXT: A => Never, // CHECK-NEXT: B => (unresolved){{$}} // CHECK-NEXT: } struct Conformer1: P17a {} // expected-error {{type 'Conformer1' does not conform to protocol 'P17a'}} // CHECK-LABEL: Abstract type witness system for conformance of Conformer2<A> to P17b: { // CHECK-NEXT: A => (unresolved), [[EQUIV_CLASS:0x[0-9a-f]+]] // CHECK-NEXT: B => (unresolved), [[EQUIV_CLASS]] // CHECK-NEXT: } struct Conformer2<A>: P17b {} // expected-error {{type 'Conformer2<A>' does not conform to protocol 'P17b'}} // CHECK-LABEL: Abstract type witness system for conformance of Conformer3 to P17c: { // CHECK-NEXT: A => Never, [[EQUIV_CLASS:0x[0-9a-f]+]] // CHECK-NEXT: B => Never, [[EQUIV_CLASS]] // CHECK-NEXT: } struct Conformer3: P17c {} // CHECK-LABEL: Abstract type witness system for conformance of Conformer4<A> to P17d: { // CHECK-NEXT: A => Int, [[EQUIV_CLASS:0x[0-9a-f]+]] // CHECK-NEXT: B => Int, [[EQUIV_CLASS]] // CHECK-NEXT: } struct Conformer4<A>: P17d {} } protocol P18 { associatedtype A = B associatedtype B = C associatedtype C = (D) -> D associatedtype D } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer<D> to P18: { // CHECK-NEXT: A => (Self.D) -> Self.D, [[EQUIV_CLASS:0x[0-9a-f]+]] // CHECK-NEXT: B => (Self.D) -> Self.D, [[EQUIV_CLASS]] // CHECK-NEXT: C => (Self.D) -> Self.D, [[EQUIV_CLASS]] // CHECK-NEXT: D => D, // CHECK-NEXT: } struct Conformer<D>: P18 {} } protocol P19 where Self == A { associatedtype A associatedtype B = (A, A) } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P19: { // CHECK-NEXT: A => Self, // CHECK-NEXT: B => (Self.A, Self.A), // CHECK-NEXT: } struct Conformer: P19 {} } protocol P20 where A == B.Element, B == B.SubSequence, C.Element == B.Element { associatedtype A associatedtype B: Collection associatedtype C: Collection = Array<Character> } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P20: { // CHECK-NEXT: A => Self.B.Element, // CHECK-NEXT: C => Array<Character>, // CHECK-NEXT: } struct Conformer: P20 { typealias B = Substring } } protocol P21 where A == B { associatedtype A associatedtype B = C associatedtype C } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer<C> to P21: { // CHECK-NEXT: A => C, [[EQUIV_CLASS:0x[0-9a-f]+]] // CHECK-NEXT: B => C, [[EQUIV_CLASS]] // CHECK-NEXT: C => C, [[EQUIV_CLASS]] // CHECK-NEXT: } struct Conformer<C>: P21 {} } protocol P22 where A == B, C == D { associatedtype A associatedtype B associatedtype C = B associatedtype D } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer<A> to P22: { // CHECK-NEXT: A => A, [[EQUIV_CLASS:0x[0-9a-f]+]] // CHECK-NEXT: B => A, [[EQUIV_CLASS]] // CHECK-NEXT: C => A, [[EQUIV_CLASS]] // CHECK-NEXT: D => A, [[EQUIV_CLASS]] // CHECK-NEXT: } struct Conformer<A>: P22 {} } protocol P23 { associatedtype A: P23 = B.A // expected-note 2 {{protocol requires nested type 'A'; do you want to add it?}} associatedtype B: P23 = A.B // expected-note 2 {{protocol requires nested type 'B'; do you want to add it?}} } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P23: { // CHECK-NEXT: A => Self.B.A, // CHECK-NEXT: B => Self.A.B, // CHECK-NEXT: } struct Conformer: P23 {} // expected-error {{type 'Conformer' does not conform to protocol 'P23'}} // CHECK-LABEL: Abstract type witness system for conformance of ConformerGeneric<T> to P23: { // CHECK-NEXT: A => Self.B.A, // CHECK-NEXT: B => Self.A.B, // CHECK-NEXT: } struct ConformerGeneric<T>: P23 {} // expected-error {{type 'ConformerGeneric<T>' does not conform to protocol 'P23'}} } protocol P24 where A == B.A { associatedtype A: P24 // expected-note 2 {{protocol requires nested type 'A'; do you want to add it?}} associatedtype B: P24 = A.B // expected-note 2 {{protocol requires nested type 'B'; do you want to add it?}} } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P24: { // CHECK-NEXT: A => Self.B.A, // CHECK-NEXT: B => Self.A.B, // CHECK-NEXT: } struct Conformer: P24 {} // expected-error {{type 'Conformer' does not conform to protocol 'P24'}} // CHECK-LABEL: Abstract type witness system for conformance of ConformerGeneric<T> to P24: { // CHECK-NEXT: A => Self.B.A, // CHECK-NEXT: B => Self.A.B, // CHECK-NEXT: } struct ConformerGeneric<T>: P24 {} // expected-error {{type 'ConformerGeneric<T>' does not conform to protocol 'P24'}} } protocol P25a_1 where A == Int, B == C.Element { associatedtype A associatedtype B associatedtype C: Sequence } protocol P25a_2 where A == C.Element, B == Int { associatedtype A associatedtype B associatedtype C: Sequence } protocol P25b where A == B { associatedtype A associatedtype B } protocol P25c_1: P25a_1, P25b {} protocol P25c_2: P25a_2, P25b {} do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer1<C> to P25a_1: { // CHECK-NEXT: A => Int, [[EQUIV_CLASS:0x[0-9a-f]+]] // CHECK-NEXT: B => Int, [[EQUIV_CLASS]] // CHECK-NEXT: C => C, // CHECK-NEXT: } struct Conformer1<C: Sequence>: P25c_1 where C.Element == Int {} // CHECK-LABEL: Abstract type witness system for conformance of Conformer2<C> to P25a_2: { // CHECK-NEXT: A => Int, [[EQUIV_CLASS:0x[0-9a-f]+]] // CHECK-NEXT: B => Int, [[EQUIV_CLASS]] // CHECK-NEXT: C => C, // CHECK-NEXT: } struct Conformer2<C: Sequence>: P25c_2 where C.Element == Int {} } protocol P26 where C == B, F == G { associatedtype A = Int associatedtype B = A associatedtype C associatedtype D associatedtype E = D associatedtype F associatedtype G = [B] } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer<D> to P26: { // CHECK-NEXT: A => Int, [[EQUIV_CLASS_1:0x[0-9a-f]+]] // CHECK-NEXT: B => Int, [[EQUIV_CLASS_1]] // CHECK-NEXT: C => Int, [[EQUIV_CLASS_1]] // CHECK-NEXT: D => D, [[EQUIV_CLASS_2:0x[0-9a-f]+]] // CHECK-NEXT: E => D, [[EQUIV_CLASS_2]] // CHECK-NEXT: F => [Self.B], [[EQUIV_CLASS_3:0x[0-9a-f]+]] // CHECK-NEXT: G => [Self.B], [[EQUIV_CLASS_3]] // CHECK-NEXT: } struct Conformer<D>: P26 {} } protocol P27a where A == Int { associatedtype A } protocol P27b where A == B.Element { associatedtype A associatedtype B: Sequence } protocol P27c_1: P27a, P27b {} protocol P27c_2: P27b, P27a {} do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer1<B> to P27a: { // CHECK-NEXT: A => Int, // CHECK-NEXT: } // CHECK-LABEL: Abstract type witness system for conformance of Conformer1<B> to P27b: { // CHECK-NEXT: B => B, // CHECK-NEXT: } struct Conformer1<B: Sequence>: P27c_1 where B.Element == Int {} // CHECK-LABEL: Abstract type witness system for conformance of Conformer2<B> to P27b: { // CHECK-NEXT: A => Int, // CHECK-NEXT: B => B, // CHECK-NEXT: } struct Conformer2<B: Sequence>: P27c_2 where B.Element == Int {} } protocol P28a where A == Int { associatedtype A // expected-note 2 {{protocol requires nested type 'A'; do you want to add it?}} } protocol P28b where A == Bool { associatedtype A } protocol P28c where A == Never { associatedtype A } protocol Q28a: P28a, P28b {} // expected-error@-1 {{'Self.A' cannot be equal to both 'Bool' and 'Int'}} // expected-note@-2 {{same-type constraint 'Self.A' == 'Int' implied here}} protocol Q28b: P28a, P28b, P28c {} // expected-error@-1 {{'Self.A' cannot be equal to both 'Bool' and 'Int'}} // expected-error@-2 {{'Self.A' cannot be equal to both 'Never' and 'Int'}} // expected-note@-3 {{same-type constraint 'Self.A' == 'Int' implied here}} // expected-note@-4 {{same-type constraint 'Self.A' == 'Int' implied here}} do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer1 to P28a: { // CHECK-NEXT: A => (ambiguous), // CHECK-NEXT: } struct Conformer1: Q28a {} // expected-error@-1 {{type 'Conformer1' does not conform to protocol 'P28a'}} // expected-error@-2 {{type 'Conformer1' does not conform to protocol 'P28b'}} // CHECK-LABEL: Abstract type witness system for conformance of Conformer2 to P28a: { // CHECK-NEXT: A => (ambiguous), // CHECK-NEXT: } struct Conformer2: Q28b {} // expected-error@-1 {{type 'Conformer2' does not conform to protocol 'P28a'}} // expected-error@-2 {{type 'Conformer2' does not conform to protocol 'P28b'}} // expected-error@-3 {{type 'Conformer2' does not conform to protocol 'P28c'}} } protocol P29a where A == Int { associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}} associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}} } protocol P29b where B == Never { associatedtype B } protocol P29c where A == B { associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}} associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}} } protocol Q29a: P29a, P29b, P29c {} // expected-error@-1 {{'Self.B' cannot be equal to both 'Never' and 'Int'}} // expected-note@-2 {{same-type constraint 'Self.A' == 'Int' implied here}} protocol Q29b: P29c, P29a, P29b {} // expected-error@-1 {{'Self.B' cannot be equal to both 'Never' and 'Int'}} // expected-note@-2 {{same-type constraint 'Self.A' == 'Int' implied here}} do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer1 to P29a: { // CHECK-NEXT: A => (ambiguous), [[EQUIV_CLASS:0x[0-9a-f]+]] // CHECK-NEXT: B => (ambiguous), [[EQUIV_CLASS]] // CHECK-NEXT: } struct Conformer1: Q29a {} // expected-error@-1 {{type 'Conformer1' does not conform to protocol 'P29a'}} // expected-error@-2 {{type 'Conformer1' does not conform to protocol 'P29b'}} // expected-error@-3 {{type 'Conformer1' does not conform to protocol 'P29c'}} // CHECK-LABEL: Abstract type witness system for conformance of Conformer2 to P29c: { // CHECK-NEXT: A => (ambiguous), [[EQUIV_CLASS:0x[0-9a-f]+]] // CHECK-NEXT: B => (ambiguous), [[EQUIV_CLASS]] // CHECK-NEXT: } struct Conformer2: Q29b {} // expected-error@-1 {{type 'Conformer2' does not conform to protocol 'P29a'}} // expected-error@-2 {{type 'Conformer2' does not conform to protocol 'P29b'}} // expected-error@-3 {{type 'Conformer2' does not conform to protocol 'P29c'}} } protocol P30a where A == Int { associatedtype A } protocol P30b where A == Never { associatedtype A } protocol P30c where A == B { associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}} associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}} } protocol Q30: P30c, P30a, P30b {} // expected-error@-1 {{'Self.A' cannot be equal to both 'Never' and 'Int'}} // expected-note@-2 {{same-type constraint 'Self.A' == 'Int' implied here}} do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P30c: { // CHECK-NEXT: A => (ambiguous), [[EQUIV_CLASS:0x[0-9a-f]+]] // CHECK-NEXT: B => (ambiguous), [[EQUIV_CLASS]] // CHECK-NEXT: } struct Conformer: Q30 {} // expected-error@-1 {{type 'Conformer' does not conform to protocol 'P30a'}} // expected-error@-2 {{type 'Conformer' does not conform to protocol 'P30b'}} // expected-error@-3 {{type 'Conformer' does not conform to protocol 'P30c'}} } protocol P31a where B == Int { associatedtype B } protocol P31b where B == Never { associatedtype B } protocol P31c where B == A { associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}} associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}} } protocol Q31: P31c, P31a, P31b {} // expected-error@-1 {{'Self.B' cannot be equal to both 'Never' and 'Int'}} // expected-note@-2 {{same-type constraint 'Self.B' == 'Int' implied here}} do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P31c: { // CHECK-NEXT: A => (ambiguous), [[EQUIV_CLASS:0x[0-9a-f]+]] // CHECK-NEXT: B => (ambiguous), [[EQUIV_CLASS]] // CHECK-NEXT: } struct Conformer: Q31 {} // expected-error@-1 {{type 'Conformer' does not conform to protocol 'P31a'}} // expected-error@-2 {{type 'Conformer' does not conform to protocol 'P31b'}} // expected-error@-3 {{type 'Conformer' does not conform to protocol 'P31c'}} } protocol P32a where A == Int { associatedtype A } protocol P32b where A == Bool { associatedtype A } protocol P32c where B == Void { associatedtype B } protocol P32d where B == Never { associatedtype B } protocol P32e where A == B { associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}} associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}} } protocol Q32: P32e, P32a, P32b, P32c, P32d {} // expected-error@-1 {{'Self.B' cannot be equal to both 'Never' and 'Int'}} // expected-error@-2 {{'Self.B' cannot be equal to both '()' and 'Int'}} // expected-error@-3 {{'Self.A' cannot be equal to both 'Bool' and 'Int'}} // expected-note@-4 3 {{same-type constraint 'Self.A' == 'Int' implied here}} do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P32e: { // CHECK-NEXT: A => (ambiguous), [[EQUIV_CLASS:0x[0-9a-f]+]] // CHECK-NEXT: B => (ambiguous), [[EQUIV_CLASS]] // CHECK-NEXT: } struct Conformer: Q32 {} // expected-error@-1 {{type 'Conformer' does not conform to protocol 'P32a'}} // expected-error@-2 {{type 'Conformer' does not conform to protocol 'P32b'}} // expected-error@-3 {{type 'Conformer' does not conform to protocol 'P32c'}} // expected-error@-4 {{type 'Conformer' does not conform to protocol 'P32d'}} // expected-error@-5 {{type 'Conformer' does not conform to protocol 'P32e'}} } protocol P33a where A == Int { associatedtype A } protocol P33b where A == Int { associatedtype A } protocol Q33: P33a, P33b {} do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P33a: { // CHECK-NEXT: A => Int, // CHECK-NEXT: } struct Conformer: Q33 {} } protocol P34a { associatedtype A = Void } protocol P34b { associatedtype A = Never } protocol Q34a: P34a, P34b {} protocol Q34b: P34b, P34a {} protocol Q34c: P34a, P34b { associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}} } do { // FIXME: should really be ambiguous (source-breaking)? // CHECK-LABEL: Abstract type witness system for conformance of Conformer1 to P34a: { // CHECK-NEXT: A => Void, // CHECK-NEXT: } struct Conformer1: Q34a {} // FIXME: should really be ambiguous (source-breaking)? // CHECK-LABEL: Abstract type witness system for conformance of Conformer2 to P34b: { // CHECK-NEXT: A => Never, // CHECK-NEXT: } struct Conformer2: Q34b {} // CHECK-LABEL: Abstract type witness system for conformance of Conformer3 to Q34c: { // CHECK-NEXT: A => (unresolved){{$}} // CHECK-NEXT: } struct Conformer3: Q34c {} // expected-error {{type 'Conformer3' does not conform to protocol 'Q34c'}} } protocol P35 { associatedtype A associatedtype B = Array<C> associatedtype C = Array<D> associatedtype D = Array<A> } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P35: { // CHECK-NEXT: B => Array<Self.C>, // CHECK-NEXT: C => Array<Self.D>, // CHECK-NEXT: D => Array<Self.A>, // CHECK-NEXT: } struct Conformer: P35 { typealias A = Never } // CHECK-LABEL: Abstract type witness system for conformance of ConformerGeneric<A> to P35: { // CHECK-NEXT: A => A, // CHECK-NEXT: B => Array<Self.C>, // CHECK-NEXT: C => Array<Self.D>, // CHECK-NEXT: D => Array<Self.A>, // CHECK-NEXT: } struct ConformerGeneric<A>: P35 {} } struct G36<S: P36> {} protocol P36 { // FIXME: Don't create and expose malformed types like 'G36<Never>' -- check // non-dependent type witnesses first. // expected-note@+1 {{default type 'G36<Never>' for associated type 'A' (from protocol 'P36') does not conform to 'P36'}} associatedtype A: P36 = G36<B> associatedtype B: P36 = Never } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P36: { // CHECK-NEXT: A => G36<Self.B>, // CHECK-NEXT: B => Never, // CHECK-NEXT: } struct Conformer: P36 {} // expected-error {{type 'Conformer' does not conform to protocol 'P36'}} } protocol P37a { associatedtype A } protocol P37b { associatedtype B : P37a associatedtype C where C == B.A } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer1<C> to P37b: { // CHECK-NEXT: C => Self.B.A, // CHECK-NEXT: } struct Conformer1<C>: P37b { struct Inner: P37a { typealias A = C } typealias B = Inner } // CHECK-LABEL: Abstract type witness system for conformance of Conformer2<T> to P37b: { // CHECK-NEXT: C => Self.B.A, // CHECK-NEXT: } struct Conformer2<T>: P37b { struct Inner: P37a { typealias A = T } typealias B = Inner } } protocol P38a { associatedtype A } protocol P38b { associatedtype B } protocol P38c: P38a, P38b where A == B {} do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer<T> to P38b: { // CHECK-NEXT: B => Self.A, // CHECK-NEXT: } struct Conformer<T>: P38c { typealias A = Self } } protocol P39 { associatedtype A: P39 associatedtype B = A.C associatedtype C = Never } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P39: { // CHECK-NEXT: B => Self.A.C, // CHECK-NEXT: C => Never, // CHECK-NEXT: } struct Conformer: P39 { typealias A = Self } } protocol P40a { associatedtype A associatedtype B = (A, A) } protocol P40b: P40a { override associatedtype A = Int } protocol P40c: P40b { override associatedtype A override associatedtype B } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P40c: { // CHECK-NEXT: A => Int, // CHECK-NEXT: B => (Self.A, Self.A), // CHECK-NEXT: } struct Conformer: P40c {} } protocol P41 { associatedtype A where A == B.A // expected-note {{protocol requires nested type 'A'; do you want to add it?}} associatedtype B: P41 = Self // expected-note {{protocol requires nested type 'B'; do you want to add it?}} } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P41: { // CHECK-NEXT: A => Self.B.A, // CHECK-NEXT: B => Self, // CHECK-NEXT: } struct Conformer: P41 {} // expected-error{{type 'Conformer' does not conform to protocol 'P41'}} } protocol P42a { associatedtype B: P42b } protocol P42b: P42a { associatedtype A = B.A } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer<B> to P42b: { // CHECK-NEXT: A => Self.B.A, // CHECK-NEXT: } // CHECK-LABEL: Abstract type witness system for conformance of Conformer<B> to P42a: { // CHECK-NEXT: B => B, // CHECK-NEXT: } struct Conformer<B: P42b>: P42b {} } protocol P43a { associatedtype A: P43a associatedtype B } protocol P43b: P43a { associatedtype C where C == A.B } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer<B> to P43b: { // CHECK-NEXT: C => Self.A.B, // CHECK-NEXT: } // CHECK-LABEL: Abstract type witness system for conformance of Conformer<B> to P43a: { // CHECK-NEXT: B => B, // CHECK-NEXT: } struct Conformer<B: P43a>: P43b { typealias A = Conformer<B.A> } } protocol P44 { associatedtype A: P44 associatedtype B associatedtype C where C == A.B } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer1<T> to P44: { // CHECK-NEXT: C => Self.A.B, // CHECK-NEXT: } struct Conformer1<T: P44>: P44 { typealias B = T.A typealias A = Conformer1<T.A> } // CHECK-LABEL: Abstract type witness system for conformance of Conformer2<B> to P44: { // CHECK-NEXT: B => B, // CHECK-NEXT: C => Self.A.B, // CHECK-NEXT: } struct Conformer2<B: P44>: P44 { typealias A = Conformer2<B.A> } // CHECK-LABEL: Abstract type witness system for conformance of Conformer3<B> to P44: { // CHECK-NEXT: B => B, // CHECK-NEXT: C => Self.A.B, // CHECK-NEXT: } struct Conformer3<B>: P44 { typealias A = Conformer3<Int> } } protocol P45 { associatedtype A associatedtype B: P45 = Conformer45<D> associatedtype C where C == B.A associatedtype D = Never } // CHECK-LABEL: Abstract type witness system for conformance of Conformer45<A> to P45: { // CHECK-NEXT: A => A, // CHECK-NEXT: B => Conformer45<Self.D>, // CHECK-NEXT: C => Self.B.A, // CHECK-NEXT: D => Never, // CHECK-NEXT: } struct Conformer45<A>: P45 {} protocol P46 { associatedtype A: P46 associatedtype B associatedtype C where C == A.B func method(_: B) } do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer<T> to P46: { // CHECK-NEXT: C => Self.A.B, // CHECK-NEXT: } struct Conformer<T: P46>: P46 { typealias A = Conformer<T.A> func method(_: T) {} } } protocol P47 { associatedtype A } do { // CHECK-LABEL: Abstract type witness system for conformance of Outer<A>.Inner to P47: { // CHECK-NEXT: A => A, // CHECK-NEXT: } struct Outer<A> { struct Inner: P47 {} } } protocol P48a { associatedtype A = Int } // expected-note {{protocol requires nested type 'A'; do you want to add it?}} protocol P48b { associatedtype B } // expected-note {{protocol requires nested type 'B'; do you want to add it?}} protocol P48c: P48a, P48b where A == B {} do { // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P48a: { // CHECK-NEXT: A => Self.B, // CHECK-NEXT: } // CHECK-LABEL: Abstract type witness system for conformance of Conformer to P48b: { // CHECK-NEXT: B => Self.A, // CHECK-NEXT: } // CHECK-NOT: Abstract type witness system for conformance of Conformer to P48c // FIXME: Should compile struct Conformer: P48c {} // expected-error@-1 {{type 'Conformer' does not conform to protocol 'P48a'}} // expected-error@-2 {{type 'Conformer' does not conform to protocol 'P48b'}} // expected-error@-3 {{type 'Conformer' does not conform to protocol 'P48c'}} }
apache-2.0
0d3e60f96fa96b139db0104b5febf095
31.55692
143
0.660142
3.21479
false
false
false
false
michalziman/mz-location-picker
MZLocationPicker/Classes/MZLocationsTableController.swift
1
1718
// // MZLocationsTableController.swift // Pods // // Created by Michal Ziman on 02/09/2017. // // import UIKit protocol MZLocationsTableDelegate: class { func tableController(_ tableController:MZLocationsTableController, didPickLocation location:MZLocation) } class MZLocationsTableController: UITableViewController { var results: [MZLocation] = [] weak var delegate: MZLocationsTableDelegate? override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return results.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let dequeuedCell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier") let cell = dequeuedCell ?? UITableViewCell(style: .subtitle, reuseIdentifier: "reuseIdentifier") cell.selectionStyle = .none let location = results[indexPath.row] if let name = location.name { cell.textLabel?.text = name cell.detailTextLabel?.text = location.address?.replacingOccurrences(of: "\n", with: ", ") } else if let address = location.address { cell.textLabel?.text = address.replacingOccurrences(of: "\n", with: ", ") } else { cell.textLabel?.text = location.coordinate.formattedCoordinates } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let d = delegate { d.tableController(self, didPickLocation: results[indexPath.row]) } } }
mit
736fe0aac232a0dcfef6cf44f821849e
34.061224
109
0.672875
5.023392
false
false
false
false
halo/LinkLiar
LinkLiar/Classes/InterfaceSubmenu.swift
1
6088
/* * Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar * * 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 Cocoa class InterfaceSubmenu { private let interface: Interface init(_ interface: Interface) { self.interface = interface } lazy var titleMenuItem: NSMenuItem = { let item = NSMenuItem(title: self.interface.title, action: nil, keyEquivalent: "") item.toolTip = "The MAC address of this Interface can be changed." item.representedObject = self.interface return item }() lazy var menuItem: NSMenuItem = { let item = NSMenuItem(title: "Loading...", action: nil, keyEquivalent: "") item.representedObject = self.interface item.target = Controller.self item.toolTip = "The currently assigned MAC address of this Interface." item.tag = 42 // So we can identify this menu item among other Inteface-based items. if self.interface.softMAC.isValid { item.title = self.interface.softMAC.humanReadable SoftMACCache.remember(BSDName: self.interface.BSDName, address: self.interface.softMAC.humanReadable) } else { if let address = SoftMACCache.address(BSDName: self.interface.BSDName) { item.title = address } else { item.title = self.interface.hardMAC.humanReadable } } item.state = NSControl.StateValue(rawValue: self.interface.hasOriginalMAC ? 1 : 0) item.onStateImage = #imageLiteral(resourceName: "InterfaceLeaking") item.submenu = self.subMenuItem() return item }() private func subMenuItem() -> NSMenu { let configurable = ConfigWriter.isWritable let submenu: NSMenu = NSMenu() submenu.autoenablesItems = false let vendorName = MACVendors.name(address: interface.softMAC) let vendorNameItem = NSMenuItem(title: vendorName, action: nil, keyEquivalent: "") vendorNameItem.isEnabled = false vendorNameItem.toolTip = "The vendor of this Interface's currently assigned MAC address." submenu.addItem(vendorNameItem) submenu.addItem(NSMenuItem.separator()) if (interface.isPoweredOffWifi) { let poweredOffItem = NSMenuItem(title: "Powered off", action: nil, keyEquivalent: "") submenu.addItem(poweredOffItem) } else { let action = Config.instance.knownInterface.action(interface.hardMAC) let ignoreItem: NSMenuItem = NSMenuItem(title: "Do nothing", action: #selector(Controller.ignoreInterface), keyEquivalent: "") ignoreItem.representedObject = interface ignoreItem.target = Controller.self ignoreItem.state = NSControl.StateValue(rawValue: action == .ignore ? 1 : 0) ignoreItem.isEnabled = configurable ignoreItem.toolTip = "This Interface will not be modified in any way." submenu.addItem(ignoreItem) let randomizeItem: NSMenuItem = NSMenuItem(title: "Random", action: #selector(Controller.randomizeInterface), keyEquivalent: "") randomizeItem.representedObject = interface randomizeItem.target = Controller.self randomizeItem.state = NSControl.StateValue(rawValue: action == .random ? 1 : 0) randomizeItem.isEnabled = configurable randomizeItem.toolTip = "Keep the MAC address of this Interface random." submenu.addItem(randomizeItem) let specifyItem: NSMenuItem = NSMenuItem(title: "Define manually", action: #selector(Controller.specifyInterface), keyEquivalent: "") specifyItem.representedObject = interface specifyItem.target = Controller.self specifyItem.state = NSControl.StateValue(rawValue: action == .specify ? 1 : 0) specifyItem.isEnabled = configurable specifyItem.toolTip = "Assign a specific MAC address to this Interfaces." submenu.addItem(specifyItem) let originalizeItem: NSMenuItem = NSMenuItem(title: "Keep original", action: #selector(Controller.originalizeInterface), keyEquivalent: "") originalizeItem.representedObject = interface originalizeItem.target = Controller.self originalizeItem.state = NSControl.StateValue(rawValue: action == .original ? 1 : 0) originalizeItem.isEnabled = configurable originalizeItem.toolTip = "Ensure this Interface is kept at its original hardware MAC address." submenu.addItem(originalizeItem) let forgetItem: NSMenuItem = NSMenuItem(title: "Default", action: #selector(Controller.forgetInterface), keyEquivalent: "") forgetItem.representedObject = interface forgetItem.target = Controller.self forgetItem.state = NSControl.StateValue(rawValue: action == nil ? 1 : 0) forgetItem.isEnabled = configurable forgetItem.toolTip = "Handle this Interfaces according to whatever is specified under \"Default\"." submenu.addItem(forgetItem) submenu.addItem(NSMenuItem.separator()) let hardMACItem: NSMenuItem = NSMenuItem(title: interface.hardMAC.humanReadable, action: nil, keyEquivalent: "") hardMACItem.isEnabled = false hardMACItem.toolTip = "The original hardware MAC address of this interface." submenu.addItem(hardMACItem) } return submenu } }
mit
3134eaab3705e0a9e9ce689f38cf0ff6
46.937008
145
0.731932
4.577444
false
true
false
false
ahoppen/swift
benchmark/single-source/Chars.swift
10
1602
//===--- Chars.swift ------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test tests the performance of ASCII Character comparison. import TestsUtils public let benchmarks = BenchmarkInfo( name: "Chars2", runFunction: run_Chars, tags: [.validation, .api, .String], setUpFunction: { blackHole(alphabetInput) }, legacyFactor: 50) let alphabetInput: [Character] = [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "/", "f", "Z", "z", "6", "7", "C", "j", "f", "9", "g", "g", "I", "J", "K", "c", "x", "i", ".", "2", "a", "t", "i", "o", "e", "q", "n", "X", "Y", "Z", "?", "m", "Z", "," ] @inline(never) public func run_Chars(_ n: Int) { // Permute some characters. let alphabet: [Character] = alphabetInput for _ in 0..<n { for firstChar in alphabet { for lastChar in alphabet { blackHole(firstChar < lastChar) blackHole(firstChar == lastChar) blackHole(firstChar > lastChar) blackHole(firstChar <= lastChar) blackHole(firstChar >= lastChar) } } } }
apache-2.0
da48e41ee86dec21f69368885773a4ac
31.693878
80
0.515605
3.536424
false
true
false
false
hirohisa/RxSwift
RxExample/RxExample/Examples/TableView/DetailViewController.swift
3
1070
// // DetailViewController.swift // RxExample // // Created by carlos on 26/5/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import UIKit #if !RX_NO_MODULE import RxSwift #endif class DetailViewController: ViewController { weak var masterVC: TableViewController! var user: User! let $ = Dependencies.sharedDependencies var disposeBag = DisposeBag() @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() imageView.makeRoundedCorners(5) let url = NSURL(string: user.imageURL)! let request = NSURLRequest(URL: url) NSURLSession.sharedSession().rx_data(request) >- map { data in UIImage(data: data) } >- observeSingleOn($.mainScheduler) >- imageView.rx_subscribeImageTo >- disposeBag.addDisposable label.text = user.firstName + " " + user.lastName } }
mit
42e3decd2f8d972b2028f9447fe817bd
22.777778
60
0.6
4.776786
false
false
false
false
zadr/conservatory
Code/Inputs/Canvas.swift
1
1998
/** A *Canvas* is the base object that everything is rendered onto. *Canvas*es conform to the *AppearanceContainer* and *Viewable* protocols, and can be recursively drawn inside of one another. */ public final class Canvas<T: Renderer>: AppearanceContainer, Viewable { private let renderer: T private var viewables: [Viewable] /** Create a *Canvas*. - Parameter size: How big should the canvas be? If no size is given, the default canvas is 1024x768 pixels in size. */ public init(size: Size = Size(width: 1024.0, height: 768.0)) { renderer = T(size: size) viewables = [Viewable]() } /** How big is the canvas, in pixels. */ public var size: Size { return renderer.size } /** Add a *Viewable* object to be rendered onto the current canvas. */ public func add(_ viewable: Viewable) { viewables.append(viewable) } /** Add a list of *Viewable* objects to be rendered onto the current canvas. */ public func add(viewables _viewables: [Viewable]) { viewables += _viewables } public func debugQuickLookObject() -> AnyObject? { return currentRepresentation as AnyObject? } /** Render the current list of viewable objects, and return the results of said operation. */ public var currentRepresentation: T.RenderResultType? { return renderer.render([ self ]) } // MARK: - Appearance public var appearance = Appearance() // MARK: - Viewable /** Render the current canvas, in the following order: 1. Apply the blend mode 2. Apply the current transform 3. Apply the background color(s) 4. Render any objects that have been added to the canvas 5. Apply the aura 6. Apply the border color(s) */ public func render<T: Renderer>(_ renderer: T) { renderer.apply(appearance.blendMode) renderer.apply(appearance.transform) renderer.apply(appearance.background) renderer.fill() let _ = renderer.render(viewables) renderer.apply(appearance.aura) renderer.apply(appearance.border, width: appearance.borderWidth) renderer.stroke() } }
bsd-2-clause
6da415a8622c42af7dc81204d148a096
24.615385
125
0.718719
3.456747
false
false
false
false
soffes/HotKey
Sources/HotKey/KeyCombo.swift
1
1660
import AppKit public struct KeyCombo: Equatable { // MARK: - Properties public var carbonKeyCode: UInt32 public var carbonModifiers: UInt32 public var key: Key? { get { return Key(carbonKeyCode: carbonKeyCode) } set { carbonKeyCode = newValue?.carbonKeyCode ?? 0 } } public var modifiers: NSEvent.ModifierFlags { get { return NSEvent.ModifierFlags(carbonFlags: carbonModifiers) } set { carbonModifiers = modifiers.carbonFlags } } public var isValid: Bool { return carbonKeyCode >= 0 } // MARK: - Initializers public init(carbonKeyCode: UInt32, carbonModifiers: UInt32 = 0) { self.carbonKeyCode = carbonKeyCode self.carbonModifiers = carbonModifiers } public init(key: Key, modifiers: NSEvent.ModifierFlags = []) { self.carbonKeyCode = key.carbonKeyCode self.carbonModifiers = modifiers.carbonFlags } // MARK: - Converting Keys public static func carbonKeyCodeToString(_ carbonKeyCode: UInt32) -> String? { return nil } } extension KeyCombo { public var dictionary: [String: Any] { return [ "keyCode": Int(carbonKeyCode), "modifiers": Int(carbonModifiers) ] } public init?(dictionary: [String: Any]) { guard let keyCode = dictionary["keyCode"] as? Int, let modifiers = dictionary["modifiers"] as? Int else { return nil } self.init(carbonKeyCode: UInt32(keyCode), carbonModifiers: UInt32(modifiers)) } } extension KeyCombo: CustomStringConvertible { public var description: String { var output = modifiers.description if let keyDescription = key?.description { output += keyDescription } return output } }
mit
6ed0cda59fec3656690d6242fe1df5bc
19.243902
79
0.693976
3.721973
false
false
false
false
codeforgreenville/trolley-tracker-ios-client
TrolleyTracker/Models/TrolleyRoute.swift
1
3566
// // TrolleyRoute.swift // TrolleyTracker // // Created by Austin Younts on 8/19/15. // Copyright (c) 2015 Code For Greenville. All rights reserved. // import Foundation import MapKit /// Represents a route that trolleys follow. struct TrolleyRoute: Equatable { static func ==(lhs: TrolleyRoute, rhs: TrolleyRoute) -> Bool { return lhs.ID == rhs.ID } let ID: Int let shortName: String let longName: String let routeDescription: String let flagStopsOnly: Bool let color: UIColor let stops: [TrolleyStop] private let _shapeCoordinates: [Coordinate] var shapePoints: [CLLocation] { return _shapeCoordinates.map { $0.location } } lazy var overlay: MKOverlay = { let coordinates = self.shapePoints.map { $0.coordinate } let coordinatesPointer = UnsafeMutablePointer<CLLocationCoordinate2D>(mutating: coordinates) let polyline = TrolleyRouteOverlay(coordinates: coordinatesPointer, count: coordinates.count) polyline.color = color return polyline }() init(id: Int, shortName: String, longName: String, routeDescription: String, flagStopsOnly: Bool, stops: [TrolleyStop], shapeCoordinates: [Coordinate], color: UIColor) { self.ID = id self.shortName = shortName self.longName = longName self.routeDescription = routeDescription self.flagStopsOnly = flagStopsOnly self.stops = stops self._shapeCoordinates = shapeCoordinates self.color = color } } struct _APIRoute: Codable { let ID: Int let ShortName: String let LongName: String let Description: String let FlagStopsOnly: Bool let RouteColorRGB: String } struct _APITrolleyRoute: Codable { let ID: Int let ShortName: String let LongName: String let Description: String let FlagStopsOnly: Bool let RouteShape: [_APIShapePoint] let Stops: [_APITrolleyStop] func route(withMetadata metadata: RouteMetadata?) -> TrolleyRoute { let color = metadata.map { UIColor(hex: $0.colorString) } ?? GreenlinkColor(routeName: ShortName)?.color ?? .black let stops = Stops.map { $0.trolleyStop(with: color) } let coords = RouteShape.map { $0.coordinate } return TrolleyRoute(id: ID, shortName: ShortName, longName: LongName, routeDescription: Description, flagStopsOnly: FlagStopsOnly, stops: stops, shapeCoordinates: coords, color: color) } } struct _APITrolleyStop: Codable { let ID: Int let Name: String let Description: String let Lat: Double let Lon: Double let StopImageURL: String? let NextTrolleyArrivalTime: [Int: String] func trolleyStop(with color: UIColor) -> TrolleyStop { return TrolleyStop(name: Name, latitude: Lat, longitude: Lon, description: Description, ID: ID, lastTrolleyArrivals: NextTrolleyArrivalTime, color: color) } } struct _APIShapePoint: Codable { let Lat: Double let Lon: Double var coordinate: Coordinate { return Coordinate(latitude: Lat, longitude: Lon) } }
mit
a40a244eca9a3c5995531e087ea1fb41
26.643411
122
0.59226
4.67979
false
false
false
false
thillsman/Override
Source/Override.swift
1
2162
// // Override.swift // Override // // Created by Tyler Hillsman on 10/25/17. // Copyright © 2017 Tyler Hillsman. All rights reserved. // import Foundation class Override { typealias BooleanCompletionHandler = (Bool) -> Void public var userDefaultsInstance = UserDefaults.standard public var initialValues: [String: Any] = [:] { didSet { setInitialValues(config: initialValues) } } public func update(from source: String, completion: BooleanCompletionHandler? = nil) { guard let url = URL(string: source) else { print("Override warning: The Override URL is invalid."); return } let request = buildRequest(url: url) let task = URLSession.shared.dataTask(with: request) { data, response, sessionError in guard let data = data else { print("Override warning: The Override URL is not returning any data."); if let completion = completion { completion(false) } return } guard let json = try? JSONSerialization.jsonObject(with: data, options: []), let overrideObject = json as? [String: Any] else { print("Override warning: The Override URL is not returning valid JSON."); if let completion = completion { completion(false) } return } for (key, value) in overrideObject { self.userDefaultsInstance.set(value, forKey: key) } if let completion = completion { completion(true) } } task.resume() } private func setInitialValues(config: [String: Any]) { for (key, value) in config { if userDefaultsInstance.object(forKey: key) == nil { userDefaultsInstance.set(value, forKey: key) } } } private func buildRequest(url: URL) -> URLRequest { var request = URLRequest(url: url) request.httpMethod = "GET" return request } }
mit
7059f31995f7374bae6c840ca380ea3d
31.253731
139
0.554836
5.002315
false
false
false
false
Stosyk/stosyk-service
Sources/AppLogic/Routing/V1PublicCollection.swift
1
3081
import Vapor import HTTP import Routing /** Routes for `/api` service */ final class V1PublicCollection: RouteCollection { typealias Wrapped = HTTP.Responder func build<B: RouteBuilder>(_ builder: B) where B.Value == Wrapped { let v1 = builder.grouped("v1") /** Routes group for `/api/v1/projects` */ v1.group("projects") { projects in func projectStub(id: Node) -> Node { // TODO: Remove after implementation return .object([ "id": id, "name": "StubProject" ]) } /** Get all projects. `GET: /projects?since=timestamp` - Parameter since: Unix timestamp, allows filtering by update time. (Optional) - Returns 200: List of projects */ projects.get { request in var meta: Node = ["total": 2, "limit": 10, "offset": 0] if let since = request.query?["since"]?.int { meta["since"] = Node(since) } return try JSON(node: [ "projects": [ projectStub(id: 1), projectStub(id: 2) ], "_meta": meta ]) } /** Get project with `id` `GET: /projects/<id>` - Parameter id: Int identifier of a project. - Returns 200: Project */ projects.get(Int.self) { request, projectId in return try JSON(node: [ "projects": [ projectStub(id: Node(projectId)) ]]) } /** Get translations in `locale` for project with `id` `GET: /projects/<id>/translations/<locale>?since=timestamp` - Parameter id: Int identifier of a project. - Parameter locale: Locale identifier (e.g. 'en', 'de', etc.) for translations. - Parameter since: Unix timestamp, allows filtering by update time. (Optional) - Returns 200: List of translations as a key-value structure */ projects.get(Int.self, "translations", String.self) { request, projectId, locale in var meta: Node = ["total": 2] if let since = request.query?["since"]?.int { meta["since"] = Node(since) } return try JSON(node: [ "translations": [ "main.title": "Main", "main.sub": "" ], "_meta": meta ]) } } } }
mit
96aa70a9a3eb6499f3f2a3814a4a7ef3
31.776596
95
0.406362
5.472469
false
false
false
false
michikono/Wasting-Time-Framework
Wasting Time Framework/UIColor.swift
1
712
// // UIColor.swift // Wasting Time Framework // // Created by Michi Kono on 4/25/15. // Copyright (c) 2015 Michi Kono. All rights reserved. // import UIKit 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(netHex:Int) { self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff) } }
mit
a76de4d698de1072ca64defc065b4dcc
30
116
0.594101
3.281106
false
false
false
false
mac-cain13/R.swift
Sources/RswiftCore/Generators/ResourceFileStructGenerator.swift
2
3252
// // ResourceFileStructGenerator.swift // R.swift // // Created by Mathijs Kadijk on 10-12-15. // From: https://github.com/mac-cain13/R.swift // License: MIT License // import Foundation struct ResourceFileStructGenerator: ExternalOnlyStructGenerator { private let resourceFiles: [ResourceFile] init(resourceFiles: [ResourceFile]) { self.resourceFiles = resourceFiles } func generatedStruct(at externalAccessLevel: AccessLevel, prefix: SwiftIdentifier) -> Struct { let structName: SwiftIdentifier = "file" let qualifiedName = prefix + structName let localized = resourceFiles.grouped(by: { $0.fullname }) let groupedLocalized = localized.grouped(bySwiftIdentifier: { $0.0 }) groupedLocalized.printWarningsForDuplicatesAndEmpties(source: "resource file", result: "file") // For resource files, the contents of the different locales don't matter, so we just use the first one let firstLocales = groupedLocalized.uniques.map { ($0.0, Array($0.1.prefix(1))) } return Struct( availables: [], comments: ["This `\(qualifiedName)` struct is generated, and contains static references to \(firstLocales.count) files."], accessModifier: externalAccessLevel, type: Type(module: .host, name: structName), implements: [], typealiasses: [], properties: firstLocales.flatMap { propertiesFromResourceFiles(resourceFiles: $0.1, at: externalAccessLevel) }, functions: firstLocales.flatMap { functionsFromResourceFiles(resourceFiles: $0.1, at: externalAccessLevel) }, structs: [], classes: [], os: [] ) } private func propertiesFromResourceFiles(resourceFiles: [ResourceFile], at externalAccessLevel: AccessLevel) -> [Let] { return resourceFiles .map { return Let( comments: ["Resource file `\($0.fullname)`."], accessModifier: externalAccessLevel, isStatic: true, name: SwiftIdentifier(name: $0.fullname), typeDefinition: .inferred(Type.FileResource), value: "Rswift.FileResource(bundle: R.hostingBundle, name: \"\($0.filename)\", pathExtension: \"\($0.pathExtension)\")" ) } } private func functionsFromResourceFiles(resourceFiles: [ResourceFile], at externalAccessLevel: AccessLevel) -> [Function] { return resourceFiles .flatMap { resourceFile -> [Function] in let fullname = resourceFile.fullname let filename = resourceFile.filename let pathExtension = resourceFile.pathExtension return [ Function( availables: [], comments: ["`bundle.url(forResource: \"\(filename)\", withExtension: \"\(pathExtension)\")`"], accessModifier: externalAccessLevel, isStatic: true, name: SwiftIdentifier(name: fullname), generics: nil, parameters: [ Function.Parameter(name: "_", type: Type._Void, defaultValue: "()") ], doesThrow: false, returnType: Type._URL.asOptional(), body: "let fileResource = R.file.\(SwiftIdentifier(name: fullname))\nreturn fileResource.bundle.url(forResource: fileResource)", os: [] ) ] } } }
mit
b75d02c5a491364f64241132ea4fc208
36.37931
140
0.653752
4.706223
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
Pods/HXPHPicker/Sources/HXPHPicker/Editor/View/Photo/EditorImageResizerView+ControlView.swift
1
10391
// // EditorImageResizerView+ControlView.swift // HXPHPicker // // Created by Slience on 2021/8/25. // import UIKit // MARK: EditorImageResizerControlViewDelegate extension EditorImageResizerView: EditorImageResizerControlViewDelegate { func controlView(beganChanged controlView: EditorImageResizerControlView, _ rect: CGRect) { delegate?.imageResizerView(willChangedMaskRect: self) hideMaskBgView() stopControlTimer() } func controlView(didChanged controlView: EditorImageResizerControlView, _ rect: CGRect) { stopControlTimer() if state == .normal { return } maskBgView.updateLayers(rect, false) maskLinesView.updateLayers(rect, false) scrollView.minimumZoomScale = getScrollViewMinimumZoomScale(rect) var imageViewHeight: CGFloat var imageViewWidth: CGFloat switch getImageOrientation() { case .up, .down: imageViewWidth = imageView.width imageViewHeight = imageView.height case .left, .right: imageViewWidth = imageView.height imageViewHeight = imageView.width } var changedZoomScale = false if rect.height > imageViewHeight { let imageZoomScale = rect.height / imageViewHeight let zoomScale = scrollView.zoomScale scrollView.setZoomScale(zoomScale * imageZoomScale, animated: false) changedZoomScale = true } if rect.width > imageViewWidth { let imageZoomScale = rect.width / imageViewWidth let zoomScale = scrollView.zoomScale scrollView.setZoomScale(zoomScale * imageZoomScale, animated: false) changedZoomScale = true } if !changedZoomScale { updateScrollViewContentInset(controlView.frame) } } func controlView(endChanged controlView: EditorImageResizerControlView, _ rect: CGRect) { startControlTimer() } func startControlTimer() { controlTimer?.invalidate() let timer = Timer.scheduledTimer( timeInterval: 0.5, target: self, selector: #selector(controlTimerAction), userInfo: nil, repeats: false ) controlTimer = timer inControlTimer = true } func stopControlTimer() { controlTimer?.invalidate() controlTimer = nil } @objc func controlTimerAction() { adjustmentViews(true) } func adjustmentViews(_ animated: Bool, showMaskShadow: Bool = true) { maskBgViewisShowing = true /// 显示遮罩背景 showMaskBgView() /// 停止定时器 stopControlTimer() /// 最大高度 let maxHeight = containerView.height - contentInsets.top - contentInsets.bottom /// 裁剪框x var rectX = contentInsets.left /// 裁剪框的宽度 var rectW = containerView.width - contentInsets.left - contentInsets.right /// 裁剪框高度 var rectH = rectW / controlView.width * controlView.height if rectH > maxHeight { /// 裁剪框超过最大高度就进行缩放 rectW = maxHeight / rectH * rectW rectH = maxHeight rectX = controlView.maxImageresizerFrame.midX - rectW * 0.5 } /// 裁剪框y let rectY = controlView.maxImageresizerFrame.midY - rectH * 0.5 /// 裁剪框将需要更新坐标 let rect = CGRect(x: rectX, y: rectY, width: rectW, height: rectH) /// 裁剪框当前的坐标 let beforeRect = controlView.frame /// 裁剪框当前在imageView上的坐标 let controlBeforeRect = maskBgView.convert(controlView.frame, to: imageView) /// 更新裁剪框坐标 updateMaskViewFrame(to: rect, animated: animated) /// 裁剪框更新之后再imageView上的坐标 let controlAfterRect = maskBgView.convert(controlView.frame, to: imageView) let scrollCotentInset = getScrollViewContentInset(rect) /// 计算scrollView偏移量 var offset = scrollView.contentOffset var offsetX: CGFloat var offsetY: CGFloat switch getImageOrientation() { case .up: if mirrorType == .horizontal { offsetX = offset.x + (rect.midX - beforeRect.midX) }else { offsetX = offset.x - (rect.midX - beforeRect.midX) } offsetY = offset.y - (rect.midY - beforeRect.midY) case .left: offsetX = offset.x + (rect.midY - beforeRect.midY) if mirrorType == .horizontal { offsetY = offset.y + (rect.midX - beforeRect.midX) }else { offsetY = offset.y - (rect.midX - beforeRect.midX) } case .down: if mirrorType == .horizontal { offsetX = offset.x - (rect.midX - beforeRect.midX) }else { offsetX = offset.x + (rect.midX - beforeRect.midX) } offsetY = offset.y + (rect.midY - beforeRect.midY) case .right: offsetX = offset.x - (rect.midY - beforeRect.midY) if mirrorType == .horizontal { offsetY = offset.y - (rect.midX - beforeRect.midX) }else { offsetY = offset.y + (rect.midX - beforeRect.midX) } } offset = checkZoomOffset(CGPoint(x: offsetX, y: offsetY), scrollCotentInset) let zoomScale = getZoomScale(fromRect: controlBeforeRect, toRect: controlAfterRect) let needZoomScale = zoomScale != scrollView.zoomScale if animated { isUserInteractionEnabled = false let currentOffset = scrollView.contentOffset scrollView.setContentOffset(currentOffset, animated: false) UIView.animate( withDuration: animationDuration, delay: 0, options: [.curveEaseOut] ) { self.updateScrollViewContentInset(rect) if needZoomScale { /// 需要进行缩放 self.scrollView.zoomScale = zoomScale offset = self.getZoomOffset( fromRect: controlBeforeRect, zoomScale: zoomScale, scrollCotentInset: scrollCotentInset ) } self.scrollView.contentOffset = offset } completion: { (isFinished) in self.maskBgViewisShowing = false self.inControlTimer = false self.delegate?.imageResizerView(didEndChangedMaskRect: self) self.isUserInteractionEnabled = true } }else { updateScrollViewContentInset(rect) if needZoomScale { /// 需要进行缩放 scrollView.zoomScale = zoomScale offset = getZoomOffset( fromRect: controlBeforeRect, zoomScale: zoomScale, scrollCotentInset: scrollCotentInset ) } scrollView.contentOffset = offset maskBgViewisShowing = false inControlTimer = false delegate?.imageResizerView(didEndChangedMaskRect: self) } } func checkZoomOffset( _ offset: CGPoint, _ scrollCotentInset: UIEdgeInsets ) -> CGPoint { var offsetX = offset.x var offsetY = offset.y var maxOffsetX: CGFloat var maxOffsetY: CGFloat switch getImageOrientation() { case .up: maxOffsetX = scrollView.contentSize.width - scrollView.width + scrollCotentInset.left maxOffsetY = scrollView.contentSize.height - scrollView.height + scrollCotentInset.bottom case .right: maxOffsetX = scrollView.contentSize.width - scrollView.height + scrollCotentInset.right maxOffsetY = scrollView.contentSize.height - scrollView.width + scrollCotentInset.bottom case .down: maxOffsetX = scrollView.contentSize.width - scrollView.width + scrollCotentInset.left maxOffsetY = scrollView.contentSize.height - scrollView.height + scrollCotentInset.bottom case .left: maxOffsetX = scrollView.contentSize.width - scrollView.height + scrollCotentInset.right maxOffsetY = scrollView.contentSize.height - scrollView.width + scrollCotentInset.top } if offsetX > maxOffsetX { offsetX = maxOffsetX } if offsetX < -scrollCotentInset.left { offsetX = -scrollCotentInset.left } if offsetY > maxOffsetY { offsetY = maxOffsetY } if offsetY < -scrollCotentInset.top { offsetY = -scrollCotentInset.top } return CGPoint(x: offsetX, y: offsetY) } func getZoomOffset(fromRect: CGRect, zoomScale: CGFloat, scrollCotentInset: UIEdgeInsets) -> CGPoint { let offsetX = fromRect.minX * zoomScale - scrollView.contentInset.left let offsetY = fromRect.minY * zoomScale - scrollView.contentInset.top return checkZoomOffset(CGPoint(x: offsetX, y: offsetY), scrollCotentInset) } func getExactnessSize(_ size: CGSize) -> CGSize { CGSize( width: CGFloat(Float(String(format: "%.2f", size.width))!), height: CGFloat(Float(String(format: "%.2f", size.height))!) ) } func getZoomScale(fromRect: CGRect, toRect: CGRect) -> CGFloat { var widthScale = toRect.width / fromRect.width let fromSize = getExactnessSize(fromRect.size) let toSize = getExactnessSize(toRect.size) /// 大小一样不需要缩放 var isMaxZoom = fromSize.equalTo(toSize) if scrollView.zoomScale * widthScale > scrollView.maximumZoomScale { let scale = scrollView.maximumZoomScale - scrollView.zoomScale if scale > 0 { widthScale = scrollView.maximumZoomScale }else { isMaxZoom = true } }else { widthScale *= scrollView.zoomScale } return isMaxZoom ? scrollView.zoomScale : widthScale } }
mit
df4433b74c7a6d891b0bb16e5197f450
38.660156
106
0.594406
4.986739
false
false
false
false
NetScaleNow-Admin/ios_sdk
NetScaleNow/Classes/ApiService.swift
1
10055
import Foundation protocol ApiService { typealias SubscribeCallback = (Bool, Error?) -> Void typealias VoucherCallback = (Voucher?, Error?) -> Void typealias CampaignsCallback = ([Campaign]?, Error?) -> Void typealias CampaignCallback = (Campaign?, Error?) -> Void func campaigns(metadata: Metadata, callback: @escaping CampaignsCallback) func campaign(metadata: Metadata, campaign: Campaign, callback: @escaping CampaignCallback) func requestVoucher(metadata: Metadata, campaign: Campaign, callback: @escaping VoucherCallback) func subscribeToNewsletter(metadata: Metadata, callback: @escaping SubscribeCallback) } class ApiServiceImpl: ApiService { static let shared = ApiServiceImpl() private init() {} // private let baseUrl = URL(string:"http://localhost:8080")! // private let baseUrl = URL(string:"https://cmc.arconsis.com/api")! private let baseUrl = URL(string:"https://staging.cmc.arconsis.com/api")! private var configuration = URLSessionConfiguration.default private var session : URLSession { return URLSession(configuration: configuration) } func campaigns(metadata: Metadata, callback: @escaping CampaignsCallback ) { updateToken { let request = self.campaignsRequest(with: metadata) self.session.dataTask(with: request, completionHandler: { (data, response, error) in guard !self.shouldRetry(response: response) else { self.campaigns(metadata: metadata, callback: callback) return } guard let data = data, let response = response as? HTTPURLResponse, response.statusCode == 200, error == nil else { DispatchQueue.main.async { callback(nil, error) } return } self.parseCampaignData(data: data, callback: callback) }).resume() } } func campaign(metadata: Metadata, campaign: Campaign, callback: @escaping CampaignCallback) { updateToken { let request = self.campaignRequest(for: campaign, metadata: metadata) self.session.dataTask(with: request, completionHandler: { (data, response, error) in guard !self.shouldRetry(response: response) else { self.campaign(metadata: metadata, campaign: campaign, callback: callback) return } guard let data = data, let response = response as? HTTPURLResponse, response.statusCode == 200, error == nil else { DispatchQueue.main.async { callback(nil, error) } return } let decoder = JSONDecoder() do { let campaign = try decoder.decode(Campaign.self, from: data) DispatchQueue.main.async { callback(campaign, nil) } } catch { debugPrint(error) callback(nil, error) } }).resume() } } func requestVoucher(metadata: Metadata, campaign: Campaign, callback: @escaping VoucherCallback) { updateToken { let request = self.voucherRequest(for: campaign, metadata: metadata) self.session.dataTask(with: request, completionHandler: { (data, response, error) in guard !self.shouldRetry(response: response) else { self.requestVoucher(metadata: metadata, campaign: campaign, callback: callback) return } guard let data = data, let response = response as? HTTPURLResponse, response.statusCode == 200, error == nil else { DispatchQueue.main.async { callback(nil, error) } return } self.parseVoucherData(data: data, campaign: campaign, callback: callback) }).resume() } } func subscribeToNewsletter(metadata: Metadata, callback: @escaping SubscribeCallback) { updateToken { let request = self.subscribeToNewsletterRequest(with: metadata) self.session.dataTask(with: request, completionHandler: { (data, response, error) in guard !self.shouldRetry(response: response) else { self.subscribeToNewsletter(metadata: metadata, callback: callback) return } guard let response = response as? HTTPURLResponse, response.statusCode == 200, error == nil else { DispatchQueue.main.async { callback(false, error) } return } DispatchQueue.main.async { callback(true, nil) } }).resume() } } private var retryCount = 0 private var maxRetryCount = 1 private func shouldRetry(response: URLResponse?) -> Bool{ // handle 401 error if let response = response as? HTTPURLResponse, response.statusCode == 401, retryCount < maxRetryCount { resetToken() retryCount += 1 return true } retryCount = 0 return false } private func campaignsRequest(with metadata: Metadata) -> URLRequest { var url = baseUrl.appendingPathComponent("campaigns").appendingPathComponent("container") url = add(metadata: metadata, to: url) return URLRequest(url: url) } private func campaignRequest(for campaign:Campaign, metadata: Metadata) -> URLRequest { var url = baseUrl.appendingPathComponent("campaigns").appendingPathComponent(campaign.id.description) url = add(metadata: metadata, to: url) return URLRequest(url: url) } private func voucherRequest(for campaign:Campaign, metadata: Metadata) -> URLRequest { var url = baseUrl.appendingPathComponent("campaigns").appendingPathComponent(campaign.id.description).appendingPathComponent("voucher") url = add(metadata: metadata, to: url) var request = URLRequest(url: url) request.httpMethod = "POST" return request } private func subscribeToNewsletterRequest(with metadata: Metadata) -> URLRequest { var url = baseUrl.appendingPathComponent("newsletter").appendingPathComponent("subscribe") url = add(metadata: metadata, to: url) var request = URLRequest(url: url) request.httpMethod = "POST" return request } private func add(metadata: Metadata, to url:URL) -> URL { var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)! urlComponents.queryItems = metadata.queryItems return urlComponents.url! } fileprivate func parseCampaignData(data: Data, callback: @escaping CampaignsCallback) { let decoder = JSONDecoder() do { let container = try decoder.decode(Container.self, from: data) Config.groupConfig = container.groupConfig DispatchQueue.main.async { callback(container.campaigns, nil) } } catch { debugPrint(error) callback(nil, error) } } fileprivate func parseVoucherData(data: Data, campaign: Campaign, callback: @escaping VoucherCallback) { let decoder = JSONDecoder() do { var voucher = try decoder.decode(Voucher.self, from: data) voucher.campaign = campaign DispatchQueue.main.async { callback(voucher, nil) } } catch { debugPrint(error) callback(nil, error) } } typealias TokenCallback = () -> Void private var token: Token? private func resetToken() { token = nil } private func updateToken(callback: @escaping TokenCallback) { if (token?.tokenIsValid ?? false) { callback() } else if (token?.refreshTokenIsValid ?? false) { refreshToken(refreshToken: token!.refreshToken, callback: callback) } else { requestToken(callback: callback) } } private func requestToken(callback: @escaping TokenCallback) { guard let apiKey = Config.apiKey, let apiSecret = Config.apiSecret else { print("Configuration Error: Please specify apiKey and apiSecret") return } let url = self.baseUrl.appendingPathComponent("token") var request = URLRequest(url: url) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") let data = [ "clientId": "ios-sdk", "username": apiKey, "password": apiSecret ] request.httpBody = try! JSONSerialization.data(withJSONObject: data, options: []) performTokenRequest(request: request, callback: callback) } private func refreshToken(refreshToken: String, callback:@escaping TokenCallback) { let url = self.baseUrl.appendingPathComponent("token/refresh") var request = URLRequest(url: url) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") let data = [ "clientId": "ios-sdk", "refreshToken": refreshToken ] request.httpBody = try! JSONSerialization.data(withJSONObject: data, options: []) performTokenRequest(request: request, callback: callback) } private func performTokenRequest(request: URLRequest, callback: @escaping TokenCallback) { configuration.httpAdditionalHeaders?.removeValue(forKey: "Authorization") session.dataTask(with: request) { (jsonData, response, error) in guard let jsonData = jsonData else { return } let decoder = JSONDecoder() decoder.dateDecodingStrategy = .custom { d in let seconds = try d.singleValueContainer().decode(Double.self) return Date(timeIntervalSinceNow: seconds) } do { self.token = try decoder.decode(Token.self, from: jsonData) self.configuration.httpAdditionalHeaders = ["Authorization": "bearer \(self.token!.accessToken)"] callback() } catch { debugPrint(error) } }.resume() } }
mit
6caa195f644bd3d017bb0a63403b4147
29.195195
139
0.633118
4.91687
false
false
false
false
SFantasy/swift-tour
Functions&Closures.playground/section-1.swift
1
905
// Experiments in The Swift Programming Language // // Functions and Closures // The origin function: func greet1(name: String, day: String) -> String { return "Hello \(name), today is \(day)" } greet1("Bob", "Tuesday") // Remove the day parameter. Add a parameter to include today's lunch special in the greeting func greet(name: String, special: Int) -> String { return "Hello, \(name), today's lunch is \(special)" } greet("Bobo", 100) // Write a function that calculates the average of its arguments. func averageOf(numbers: Int...) -> Int { var sum = 0, index = 0 for number in numbers { sum += number index++ } return index > 0 ? sum/index : 0 } averageOf() averageOf(1, 2, 3) // Rewrite the closure to return zero for all odd numbers var numbers = [1, 3, 4, 7, 9] numbers.map({ (number: Int) -> Int in return number%2 == 0 ? number : 0 })
mit
13959e54b5784d7b8145daf14b67be67
23.459459
93
0.639779
3.535156
false
false
false
false
fanxiangyang/FanRefresh
Classes/FanRefreshComponent.swift
1
10366
// // FanRefreshComponent.swift // FanRefresh // // Created by 向阳凡 on 2017/3/29. // Copyright © 2017年 凡向阳. All rights reserved. // import UIKit /// 刷新控件状态 /// /// - Default: 默认闲着状态 /// - Pulling: 松开就可以刷新的状态 /// - Refreshing: 正在刷新状态 /// - WillRefresh: 即将刷新状态 /// - NoMoreData: 数据加载完成,没有更多数据 public enum FanRefreshState:Int { case Default=0 case Pulling=1 case Refreshing=2 case WillRefresh=3 case NoMoreData=4 } /// 进入刷新状态的回调 public typealias FanRefreshComponentRefreshingBlock = (()->()) /// 开始刷新后的回调 public typealias FanRefreshComponentBeginRefreshingBlock = (()->()) /// 结束刷新后的回调 public typealias FanRefreshComponentEndRefreshingBlock = (()->()) public class FanRefreshComponent: UIView { /// 记录scrolView刚开始的Inset public var scrollViewOriginalInset:UIEdgeInsets? /// 父类scrollView public weak var superScrollView:UIScrollView? /// 正在刷新的回调 public var fan_refreshingBlock:FanRefreshComponentRefreshingBlock? /// 开始刷新 public var fan_beginRefreshBlock:FanRefreshComponentBeginRefreshingBlock? /// 结束刷新 public var fan_endRefreshBlock:FanRefreshComponentEndRefreshingBlock? public var state:FanRefreshState = .Default{ willSet{ // print("\(self.state)----\(newValue)\n") // self.fan_changeState(newState: newValue) } didSet{ // print("\(self.state)\n") self.fan_changeState(oldState: oldValue) } } public var scrollViewPan:UIPanGestureRecognizer? /// 拖拽百分比改透明度(内部属性,) public var fan_pullingPercent:CGFloat=0.0{ didSet{ if self.isRefreshing() { return } if self.fan_automaticallyChangeAlpha { self.alpha = self.fan_pullingPercent } } } /// 下拉时使用属性,上拉没有用 public var fan_automaticallyChangeAlpha:Bool=true{ didSet{ if self.isRefreshing() { return } if self.fan_automaticallyChangeAlpha { self.alpha = self.fan_pullingPercent }else{ self.alpha = 1.0 } } } //MARK: - 初始化 public override init(frame: CGRect) { super.init(frame: frame) self.state = .Default self.fan_prepare() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) fatalError("init(coder:) has not been implemented") } deinit { self.fan_removeObservers() // print(#function) } //MARK: - 内部方法 public override func draw(_ rect: CGRect) { super.draw(rect) // 预防view还没显示出来就调用了fan_beginRefreshing if self.state == .WillRefresh { self.state = .Refreshing } } public override func layoutSubviews() { self.fan_placeSubviews() super.layoutSubviews() } public func fan_addObservers() { let options:NSKeyValueObservingOptions = [ .new,.old ] self.superScrollView?.addObserver(self, forKeyPath: FanRefreshKeyPathContentOffset, options: options, context: nil) self.superScrollView?.addObserver(self, forKeyPath: FanRefreshKeyPathContentSize, options: options, context: nil) self.scrollViewPan=self.superScrollView?.panGestureRecognizer self.scrollViewPan?.addObserver(self, forKeyPath: FanRefreshKeyPathPanState, options: options, context: nil) } public func fan_removeObservers() { self.superview?.removeObserver(self, forKeyPath: FanRefreshKeyPathContentOffset) self.superview?.removeObserver(self, forKeyPath: FanRefreshKeyPathContentSize) self.scrollViewPan?.removeObserver(self, forKeyPath: FanRefreshKeyPathPanState) self.scrollViewPan = nil } override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { //不可用状态不处理 if self.isUserInteractionEnabled == false { return } if keyPath == FanRefreshKeyPathContentOffset{ if self.isHidden { return } self.fan_scrollViewContentOffsetDidChange(change: change!) }else if keyPath == FanRefreshKeyPathContentSize{ self.fan_scrollViewContentSizeDidChange(change: change!) }else if keyPath == FanRefreshKeyPathPanState{ self.fan_scrollViewPanStateDidChange(change: change!) } } /// 刷新回调block public func fan_executeRefreshingCallBack() { DispatchQueue.main.async { if (self.fan_refreshingBlock != nil) { self.fan_refreshingBlock!() } if (self.fan_beginRefreshBlock != nil) { self.fan_beginRefreshBlock!() } } } //MARK: - 子类有些需要实现的 override public func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) if (newSuperview != nil) && !(newSuperview is UIScrollView) { return } //移除监听 self.fan_removeObservers() if (newSuperview != nil) { self.fan_width=(newSuperview?.fan_width)! self.fan_x=0.0 self.superScrollView=newSuperview as? UIScrollView self.superScrollView?.alwaysBounceVertical=true self.scrollViewOriginalInset=self.superScrollView?.fan_inset //添加监听 self.fan_addObservers() } } //MARK: - 子类重写方法 /// 准备工作,子类重写 public func fan_prepare() -> () { // let autoresize = UIViewAutoresizing().union(.flexibleLeftMargin).union(.flexibleRightMargin).union(.flexibleWidth) //适配约束 let autoresize = UIView.AutoresizingMask().union(.flexibleWidth) self.autoresizingMask=autoresize self.backgroundColor=UIColor.clear } /// 重新布局UI,子控件 public func fan_placeSubviews() -> () { } public func fan_scrollViewContentOffsetDidChange(change:[NSKeyValueChangeKey : Any]) { } public func fan_scrollViewContentSizeDidChange(change:[NSKeyValueChangeKey : Any]) { } public func fan_scrollViewPanStateDidChange(change:[NSKeyValueChangeKey : Any]) { } public func fan_changeState(oldState:FanRefreshState) -> () { // 加入主队列的目的是等setState:方法调用完毕、设置完文字后再去布局子控件 DispatchQueue.main.async { self.setNeedsLayout() } if self.state==oldState { return } } //MARK: - 刷新状态控制 /// 开始刷新 public func fan_beginRefreshing() { UIView.animate(withDuration: FanRefreshAnimationDuration) { self.alpha = 1.0 } self.fan_pullingPercent=1.0 //只要正在刷新,就完全显示 if (self.window != nil) { self.state = .Refreshing }else{ // 预防正在刷新中时,调用本方法使得header inset回置失败 if self.state != .Refreshing { self.state = .WillRefresh // 刷新(预防从另一个控制器回到这个控制器的情况,回来要重新刷新一下) self.setNeedsDisplay() } } } public func fan_beginRefreshing(beginRefreshBlock:@escaping FanRefreshComponentBeginRefreshingBlock) { self.fan_beginRefreshBlock=beginRefreshBlock self.fan_beginRefreshing() } /// 结束刷新 public func fan_endRefreshing() { self.state = .Default } public func fan_endRefreshing(endRefreshBlock:@escaping FanRefreshComponentEndRefreshingBlock) { self.fan_endRefreshBlock=endRefreshBlock self.fan_endRefreshing() } /// 是否正在刷新 /// /// - Returns: false/ture public func isRefreshing() -> (Bool){ return self.state == .Refreshing || self.state == .WillRefresh } //这里是只读的计算属性,不设置set,默认是只读的 // var isRefreshing:Bool{ // get{ // return self.state == .Refreshing || self.state == .WillRefresh // } // } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ } //MARK: - Label扩展 public extension UILabel{ class func fan_label()-> UILabel { let label = UILabel() label.font=FanRefreshLableFont() label.textColor=FanRefreshTextColor() label.autoresizingMask=[.flexibleWidth] label.textAlignment = .center label.backgroundColor=UIColor.clear return label } func fan_textWidth(height:CGFloat) -> CGFloat { var stringWidth:CGFloat=0.0 let size:CGSize = CGSize(width: CGFloat(MAXFLOAT), height: height) //FIXME: 字符串不存在时的崩溃 if (self.text != nil) { if (self.text?.count)! > 0 { stringWidth = (self.text! as NSString).boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: [NSAttributedString.Key.font:self.font!], context: nil).size.width } } return stringWidth } func fan_textHeight(width:CGFloat) -> CGFloat { var stringHeight:CGFloat=0.0 let size:CGSize = CGSize(width: width , height: CGFloat(MAXFLOAT)) if (self.text != nil) { if (self.text?.count)! > 0 { stringHeight = (self.text! as NSString).boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: [NSAttributedString.Key.font:self.font!], context: nil).size.height } } return stringHeight } }
mit
6564faab25e34af565a3ce17008e4d21
29.878594
196
0.611381
4.522695
false
false
false
false
khizkhiz/swift
test/decl/func/default-values.swift
4
3537
// RUN: %target-parse-verify-swift var func5 : (fn : (Int,Int) -> ()) -> () // Default arguments for functions. func foo3(a a: Int = 2, b: Int = 3) {} func functionCall() { foo3(a: 4) foo3() foo3(a : 4) foo3(b : 4) foo3(a : 2, b : 4) } func g() {} func h(x: () -> () = g) { x() } // Tuple types cannot have default values, but recover well here. func tupleTypes() { typealias ta1 = (a : Int = ()) // expected-error{{default argument not permitted in a tuple type}}{{28-32=}} // expected-error @-1{{cannot create a single-element tuple with an element label}}{{20-24=}} var c1 : (a : Int, b : Int, c : Int = 3, // expected-error{{default argument not permitted in a tuple type}}{{39-42=}} d = 4) = (1, 2, 3, 4) // expected-error{{default argument not permitted in a tuple type}}{{15-18=}} expected-error{{use of undeclared type 'd'}} } func returnWithDefault() -> (a: Int, b: Int = 42) { // expected-error{{default argument not permitted in a tuple type}} {{45-49=}} return 5 // expected-error{{cannot convert return expression of type 'Int' to return type '(a: Int, b: Int)'}} } func selectorStyle(i: Int = 1, withFloat f: Float = 2) { } // Default arguments of constructors. struct Ctor { init (i : Int = 17, f : Float = 1.5) { } } Ctor() // expected-warning{{unused}} Ctor(i: 12) // expected-warning{{unused}} Ctor(f:12.5) // expected-warning{{unused}} // Default arguments for nested constructors/functions. struct Outer<T> { struct Inner { // expected-error{{type 'Inner' nested in generic type}} struct VeryInner {// expected-error{{type 'VeryInner' nested in generic type}} init (i : Int = 17, f : Float = 1.5) { } static func f(i i: Int = 17, f: Float = 1.5) { } func g(i i: Int = 17, f: Float = 1.5) { } } } } Outer<Int>.Inner.VeryInner() // expected-warning{{unused}} Outer<Int>.Inner.VeryInner(i: 12) // expected-warning{{unused}} Outer<Int>.Inner.VeryInner(f:12.5) // expected-warning{{unused}} Outer<Int>.Inner.VeryInner.f() Outer<Int>.Inner.VeryInner.f(i: 12) Outer<Int>.Inner.VeryInner.f(f:12.5) var vi : Outer<Int>.Inner.VeryInner vi.g() vi.g(i: 12) vi.g(f:12.5) // <rdar://problem/14564964> crash on invalid func foo(x: WonkaWibble = 17) { } // expected-error{{use of undeclared type 'WonkaWibble'}} // Default arguments for initializers. class SomeClass2 { init(x: Int = 5) {} } class SomeDerivedClass2 : SomeClass2 { init() { super.init() } } func shouldNotCrash(a : UndefinedType, bar b : Bool = true) { // expected-error {{use of undeclared type 'UndefinedType'}} } // <rdar://problem/20749423> Compiler crashed while building simple subclass // code class SomeClass3 { init(x: Int = 5, y: Int = 5) {} } class SomeDerivedClass3 : SomeClass3 {} _ = SomeDerivedClass3() // Tuple types with default arguments are not materializable func identity<T>(t: T) -> T { return t } func defaultArgTuplesNotMaterializable(x: Int, y: Int = 0) {} defaultArgTuplesNotMaterializable(identity(5)) // <rdar://problem/22333090> QoI: Propagate contextual information in a call to operands defaultArgTuplesNotMaterializable(identity((5, y: 10))) // expected-error@-1 {{cannot convert value of type '(Int, y: Int)' to expected argument type 'Int'}} // rdar://problem/21799331 func foo<T>(x: T, y: Bool = true) {} foo(true ? "foo" : "bar") func foo2<T>(x: T, y: Bool = true) {} extension Array { func bar(x: Element -> Bool) -> Int? { return 0 } } foo2([].bar { $0 == "c" }!) // rdar://problem/21643052 let a = ["1", "2"].map { Int($0) }
apache-2.0
66c6de603d8d58cde326b7aafceb035e
30.300885
156
0.644897
3.099912
false
false
false
false
JohnKim/stalk.messenger
stalk-messenger/ios/RNSwiftSocketIO/SocketIOClient/SocketStringReader.swift
24
2665
// // SocketStringReader.swift // Socket.IO-Client-Swift // // Created by Lukas Schmidt on 07.09.15. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. struct SocketStringReader { let message: String var currentIndex: String.Index var hasNext: Bool { return currentIndex != message.endIndex } var currentCharacter: String { return String(message[currentIndex]) } init(message: String) { self.message = message currentIndex = message.startIndex } @discardableResult mutating func advance(by: Int) -> String.Index { currentIndex = message.characters.index(currentIndex, offsetBy: by) return currentIndex } mutating func read(count: Int) -> String { let readString = message[currentIndex..<message.characters.index(currentIndex, offsetBy: count)] advance(by: count) return readString } mutating func readUntilOccurence(of string: String) -> String { let substring = message[currentIndex..<message.endIndex] guard let foundRange = substring.range(of: string) else { currentIndex = message.endIndex return substring } advance(by: message.characters.distance(from: message.characters.startIndex, to: foundRange.lowerBound) + 1) return substring.substring(to: foundRange.lowerBound) } mutating func readUntilEnd() -> String { return read(count: message.characters.distance(from: currentIndex, to: message.endIndex)) } }
mit
c213bfa3f84015cff6e53402e919a3b2
35.506849
116
0.680675
4.750446
false
false
false
false
Carthage/PrettyColors
Source/Color/EightBitColor.swift
1
526
extension Color { public struct EightBit: Parameter, ColorType { public var color: UInt8 public var level: Level public var code: (enable: [UInt8], disable: UInt8?) { return ( enable: [ (self.level == .Foreground ? 38 : 48), 5, self.color ], disable: nil ) } public init( foreground color: UInt8 ) { self.color = color self.level = Level.Foreground } public init( background color: UInt8 ) { self.color = color self.level = Level.Background } } }
mit
95af83848c6171b95ddabcc64e4a26de
15.4375
55
0.602662
3.094118
false
false
false
false
SwiftyBeaver/SwiftyBeaver
Sources/FilterValidator.swift
1
5278
// // FilterValidator.swift // SwiftyBeaver (iOS) // // Created by Felix Lisczyk on 07.07.19. // Copyright © 2019 Sebastian Kreutzberger. All rights reserved. // import Foundation /// FilterValidator is a utility class used by BaseDestination. /// It encapsulates the filtering logic for excluded, required /// and non-required filters. /// /// FilterValidator evaluates a set of filters for a single log /// entry. It determines if these filters apply to the log entry /// based on their condition (path, function, message) and their /// minimum log level. struct FilterValidator { // These are the different filter types that the user can set enum ValidationType: CaseIterable { case excluded case required case nonRequired func apply(to filters: [FilterType]) -> [FilterType] { switch self { case .excluded: return filters.filter { $0.isExcluded() } case .required: return filters.filter { $0.isRequired() && !$0.isExcluded() } case .nonRequired: return filters.filter { !$0.isRequired() && !$0.isExcluded() } } } } // Wrapper object for input parameters struct Input { let filters: [FilterType] let level: SwiftyBeaver.Level let path: String let function: String let message: String? } // Result wrapper object enum Result { case allFiltersMatch // All filters fully match the log entry (condition + minimum log level) case someFiltersMatch(PartialMatchData) // Only some filters fully match the log entry (condition + minimum log level) case noFiltersMatchingType // There are no filters set for a particular type (excluded, required, nonRequired) struct PartialMatchData { let fullMatchCount: Int // Number of filters that match both the condition and the minimum log level of the log entry let conditionMatchCount: Int // Number of filters that match ONLY the condition of the log entry (path, function, message) let logLevelMatchCount: Int // Number of filters that match ONLY the minimum log level of the log entry } } static func validate(input: Input, for types: [ValidationType] = ValidationType.allCases) -> [ValidationType: Result] { var results = [ValidationType: Result]() for type in types { let filtersToValidate = type.apply(to: input.filters) if filtersToValidate.isEmpty { // There are no filters set for this particular type results[type] = .noFiltersMatchingType } else { var fullMatchCount: Int = 0 var conditionMatchCount: Int = 0 var logLevelMatchCount: Int = 0 for filter in filtersToValidate { let filterMatchesCondition = self.filterMatchesCondition(filter, level: input.level, path: input.path, function: input.function, message: input.message) let filterMatchesMinLogLevel = self.filterMatchesMinLogLevel(filter, level: input.level) switch (filterMatchesCondition, filterMatchesMinLogLevel) { // Filter matches both the condition and the minimum log level case (true, true): fullMatchCount += 1 // Filter matches only the condition (path, function, message) case (true, false): conditionMatchCount += 1 // Filter matches only the minimum log level case (false, true): logLevelMatchCount += 1 // Filter does not match the condition nor the minimum log level case (false, false): break } } if filtersToValidate.count == fullMatchCount { // All filters fully match the log entry results[type] = .allFiltersMatch } else { // Only some filters match the log entry results[type] = .someFiltersMatch(.init(fullMatchCount: fullMatchCount, conditionMatchCount: conditionMatchCount, logLevelMatchCount: logLevelMatchCount)) } } } return results } private static func filterMatchesCondition(_ filter: FilterType, level: SwiftyBeaver.Level, path: String, function: String, message: String?) -> Bool { let passes: Bool switch filter.getTarget() { case .Path(_): passes = filter.apply(path) case .Function(_): passes = filter.apply(function) case .Message(_): guard let message = message else { return false } passes = filter.apply(message) } return passes } private static func filterMatchesMinLogLevel(_ filter: FilterType, level: SwiftyBeaver.Level) -> Bool { return filter.reachedMinLevel(level) } }
mit
e2f2241c6176f7d8c58e367d4809003d
39.906977
174
0.586128
5.235119
false
false
false
false
paperboy1109/Capstone
Pods/NumberMorphView/Pod/Classes/NumberMorphView.swift
1
18575
// // NumberMorphView.swift // Pods // // Created by Abhinav Chauhan on 14/03/16. // // import Foundation import UIKit import QuartzCore public protocol InterpolatorProtocol { func getInterpolation(x: CGFloat) -> CGFloat; } // Recommended ration for width : height is 13 : 24 public class NumberMorphView: UIView { private static let DEFAULT_FONT_SIZE: CGFloat = 24; // ************************************************************************************************* // * IBInspectable properties // ************************************************************************************************* @IBInspectable public var fontSize: CGFloat = NumberMorphView.DEFAULT_FONT_SIZE { didSet { self.lineWidth = fontSize / 16; invalidateIntrinsicContentSize(); } } @IBInspectable public var lineWidth: CGFloat = 2 { didSet { path.lineWidth = lineWidth; shapeLayer.lineWidth = lineWidth; } } @IBInspectable public var fontColor: UIColor = UIColor.blackColor().colorWithAlphaComponent(0.6) { didSet { self.shapeLayer.strokeColor = fontColor.CGColor; } } @IBInspectable public var animationDuration: Double = 0.5 { didSet { if displayLink.duration > 0 { maxFrames = Int(animationDuration / displayLink.duration); } } } // ************************************************************************************************* // * Private properties // ************************************************************************************************* private var endpoints_original: [[[CGFloat]]] = Array(count: 10, repeatedValue: Array(count: 5, repeatedValue: Array(count: 2, repeatedValue: 0))); private var controlPoints1_original: [[[CGFloat]]] = Array(count: 10, repeatedValue: Array(count: 4, repeatedValue: Array(count: 2, repeatedValue: 0))); private var controlPoints2_original: [[[CGFloat]]] = Array(count: 10, repeatedValue: Array(count: 4, repeatedValue: Array(count: 2, repeatedValue: 0))); private var endpoints_scaled: [[[CGFloat]]] = Array(count: 10, repeatedValue: Array(count: 5, repeatedValue: Array(count: 2, repeatedValue: 0))); private var controlPoints1_scaled: [[[CGFloat]]] = Array(count: 10, repeatedValue: Array(count: 4, repeatedValue: Array(count: 2, repeatedValue: 0))); private var controlPoints2_scaled: [[[CGFloat]]] = Array(count: 10, repeatedValue: Array(count: 4, repeatedValue: Array(count: 2, repeatedValue: 0))); private var paths = [UIBezierPath](); private var maxFrames = 0; // will be initialized in first update() call private var _currentDigit = 0; private var _nextDigit = 0; private var currentFrame = 1; private var displayLink: CADisplayLink!; private var path = UIBezierPath(); private var shapeLayer = CAShapeLayer(); // ************************************************************************************************* // * Constructors // ************************************************************************************************* override init(frame: CGRect) { super.init(frame: frame); initialize(); } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); initialize(); } override public func layoutSubviews() { super.layoutSubviews(); scalePoints(); initializePaths(); shapeLayer.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height); if displayLink.paused { drawDigitWithoutAnimation(_currentDigit); } } override public func intrinsicContentSize() -> CGSize { return CGSize(width: fontSize * 0.65, height: fontSize * 1.2); } // ************************************************************************************************* // * Public properties and methods // ************************************************************************************************* public var interpolator: InterpolatorProtocol = OvershootInterpolator(tension: 1.3); public var currentDigit: Int { get { return _currentDigit; } set { _currentDigit = newValue; _nextDigit = _currentDigit; } } public var nextDigit: Int { get { return _nextDigit; } set { animateToDigit(newValue); } } public func animateToDigit(digit: Int) { _currentDigit = _nextDigit; _nextDigit = digit; currentFrame = 1; displayLink.paused = false; } public func animateToDigit_withCABasicAnimation(digit: Int) { _currentDigit = _nextDigit; _nextDigit = digit; let anim = CABasicAnimation(keyPath: "path"); anim.duration = 0.2; anim.fromValue = paths[_currentDigit].CGPath; anim.toValue = paths[_nextDigit].CGPath; anim.repeatCount = 0; anim.fillMode = kCAFillModeForwards; anim.removedOnCompletion = false; anim.autoreverses = false; CATransaction.begin(); CATransaction.setCompletionBlock() { self._currentDigit = self._nextDigit; print("completed"); } shapeLayer.addAnimation(anim, forKey: "path"); CATransaction.commit(); } // ************************************************************************************************* // * Helper / utility methods // ************************************************************************************************* private func drawDigitWithoutAnimation(digit: Int) { let p = endpoints_scaled[digit]; let cp1 = controlPoints1_scaled[digit]; let cp2 = controlPoints2_scaled[digit]; path.removeAllPoints(); path.moveToPoint(CGPoint(x: p[0][0], y: p[0][1])); for i in 1..<p.count { let endpoint = CGPoint(x: p[i][0], y: p[i][1]); let cp1 = CGPoint(x: cp1[i-1][0], y: cp1[i-1][1]); let cp2 = CGPoint(x: cp2[i-1][0], y: cp2[i-1][1]); path.addCurveToPoint(endpoint, controlPoint1: cp1, controlPoint2: cp2); } shapeLayer.path = path.CGPath; } func updateAnimationFrame() { if maxFrames <= 0 { maxFrames = Int(animationDuration / displayLink.duration); } let pCur = endpoints_scaled[_currentDigit]; let cp1Cur = controlPoints1_scaled[_currentDigit]; let cp2Cur = controlPoints2_scaled[_currentDigit]; let pNext = endpoints_scaled[_nextDigit]; let cp1Next = controlPoints1_scaled[_nextDigit]; let cp2Next = controlPoints2_scaled[_nextDigit]; path.removeAllPoints(); let factor: CGFloat = interpolator.getInterpolation((CGFloat)(currentFrame) / (CGFloat)(maxFrames)); path.moveToPoint(CGPoint(x: pCur[0][0] + (pNext[0][0] - pCur[0][0]) * factor, y: pCur[0][1] + (pNext[0][1] - pCur[0][1]) * factor)); for i in 1..<pCur.count { let ex = pCur[i][0] + (pNext[i][0] - pCur[i][0]) * factor let ey = pCur[i][1] + (pNext[i][1] - pCur[i][1]) * factor; let endpoint = CGPoint(x: ex, y: ey); let iMinus1 = i-1; let cp1x = cp1Cur[iMinus1][0] + (cp1Next[iMinus1][0] - cp1Cur[iMinus1][0]) * factor; let cp1y = cp1Cur[iMinus1][1] + (cp1Next[iMinus1][1] - cp1Cur[iMinus1][1]) * factor; let cp1 = CGPoint(x: cp1x, y: cp1y); let cp2x = cp2Cur[iMinus1][0] + (cp2Next[iMinus1][0] - cp2Cur[iMinus1][0]) * factor; let cp2y = cp2Cur[iMinus1][1] + (cp2Next[iMinus1][1] - cp2Cur[iMinus1][1]) * factor; let cp2 = CGPoint(x: cp2x, y: cp2y); path.addCurveToPoint(endpoint, controlPoint1: cp1, controlPoint2: cp2); } shapeLayer.path = path.CGPath; currentFrame += 1; if currentFrame > maxFrames { currentFrame = 1; currentDigit = _nextDigit; displayLink.paused = true; drawDigitWithoutAnimation(currentDigit); } } private func initialize() { path.lineJoinStyle = .Round; path.lineCapStyle = .Round; path.miterLimit = -10; path.lineWidth = self.lineWidth; shapeLayer.fillColor = UIColor.clearColor().CGColor; shapeLayer.strokeColor = self.fontColor.CGColor; shapeLayer.lineWidth = self.lineWidth; shapeLayer.contentsScale = UIScreen.mainScreen().scale; shapeLayer.shouldRasterize = false; shapeLayer.lineCap = kCALineCapRound; shapeLayer.lineJoin = kCALineJoinRound; self.layer.addSublayer(shapeLayer); displayLink = CADisplayLink(target: self, selector: Selector("updateAnimationFrame")); displayLink.frameInterval = 1; displayLink.paused = true; displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes); endpoints_original[0] = [[500, 800], [740, 400], [500, 0], [260, 400], [500, 800]]; endpoints_original[1] = [[383, 712], [500, 800], [500, 0], [500, 800], [383, 712]]; endpoints_original[2] = [[300, 640], [700, 640], [591, 369], [300, 0], [700, 0]]; endpoints_original[3] = [[300, 600], [700, 600], [500, 400], [700, 200], [300, 200]]; endpoints_original[4] = [[650, 0], [650, 140], [650, 800], [260, 140], [760, 140]]; endpoints_original[5] = [[645, 800], [400, 800], [300, 480], [690, 285], [272, 92]]; endpoints_original[6] = [[640, 800], [321, 458], [715, 144], [257, 146], [321, 458]]; endpoints_original[7] = [[275, 800], [725, 800], [586, 544], [424, 262], [275, 0]]; endpoints_original[8] = [[500, 400], [500, 0], [500, 400], [500, 800], [500, 400]]; endpoints_original[9] = [[679, 342], [743, 654], [285, 656], [679, 342], [360, 0]]; controlPoints1_original[0] = [[650, 800], [740, 200], [350, 0], [260, 600]]; controlPoints1_original[1] = [[383, 712], [500, 488], [500, 488], [383, 712]]; controlPoints1_original[2] = [[335, 853], [710, 538], [477, 213], [450, 0]]; controlPoints1_original[3] = [[300, 864], [700, 400], [500, 400], [700, -64]]; controlPoints1_original[4] = [[650, 50], [650, 340], [502, 572], [350, 140]]; controlPoints1_original[5] = [[550, 800], [400, 800], [495, 567], [717, 30]]; controlPoints1_original[6] = [[578, 730], [492, 613], [634, -50], [208, 264]]; controlPoints1_original[7] = [[350, 800], [676, 700], [538, 456], [366, 160],]; controlPoints1_original[8] = [[775, 400], [225, 0], [225, 400], [775, 800]]; controlPoints1_original[9] = [[746, 412], [662, 850], [164, 398], [561, 219]]; controlPoints2_original[0] = [[740, 600], [650, 0], [260, 200], [350, 800]]; controlPoints2_original[1] = [[500, 800], [500, 312], [500, 312], [500, 800]]; controlPoints2_original[2] = [[665, 853], [658, 461], [424, 164], [544, 1]]; controlPoints2_original[3] = [[700, 864], [500, 400], [700, 400], [300, -64]]; controlPoints2_original[4] = [[650, 100], [650, 600], [356, 347], [680, 140]]; controlPoints2_original[5] = [[450, 800], [300, 480], [672, 460], [410, -100]]; controlPoints2_original[6] = [[455, 602], [840, 444], [337, -46], [255, 387]]; controlPoints2_original[7] = [[500, 800], [634, 631], [487, 372], [334, 102]]; controlPoints2_original[8] = [[775, 0], [225, 400], [225, 800], [775, 400]]; controlPoints2_original[9] = [[792, 536], [371, 840], [475, 195], [432, 79]]; for digit in 0..<endpoints_original.count { for pointIndex in 0..<endpoints_original[digit].count { endpoints_original[digit][pointIndex][1] = 800 - endpoints_original[digit][pointIndex][1]; if pointIndex < 4 { controlPoints1_original[digit][pointIndex][1] = 800 - controlPoints1_original[digit][pointIndex][1]; controlPoints2_original[digit][pointIndex][1] = 800 - controlPoints2_original[digit][pointIndex][1]; } } // for pointIndex } // for digit } private func scalePoints() { let width = self.bounds.width; let height = self.bounds.height; for digit in 0..<endpoints_original.count { for pointIndex in 0..<endpoints_original[digit].count { endpoints_scaled[digit][pointIndex][0] = (endpoints_original[digit][pointIndex][0] / 1000.0 * 1.4 - 0.2) * width; endpoints_scaled[digit][pointIndex][1] = (endpoints_original[digit][pointIndex][1] / 800.0 * 0.6 + 0.2) * height; if pointIndex < 4 { controlPoints1_scaled[digit][pointIndex][0] = (controlPoints1_original[digit][pointIndex][0] / 1000.0 * 1.4 - 0.2) * width; controlPoints1_scaled[digit][pointIndex][1] = (controlPoints1_original[digit][pointIndex][1] / 800.0 * 0.6 + 0.2) * height; controlPoints2_scaled[digit][pointIndex][0] = (controlPoints2_original[digit][pointIndex][0] / 1000.0 * 1.4 - 0.2) * width; controlPoints2_scaled[digit][pointIndex][1] = (controlPoints2_original[digit][pointIndex][1] / 800.0 * 0.6 + 0.2) * height; } } // for pointIndex } // for digit } private func initializePaths() { paths.removeAll(); for digit in 0...9 { paths.append(UIBezierPath()); var p = endpoints_scaled[digit]; var cp1 = controlPoints1_scaled[digit]; var cp2 = controlPoints2_scaled[digit]; paths[digit].moveToPoint(CGPoint(x: p[0][0], y: p[0][1])); for i in 1..<p.count { let endpoint = CGPoint(x: p[i][0], y: p[i][1]); let cp1 = CGPoint(x: cp1[i-1][0], y: cp1[i-1][1]); let cp2 = CGPoint(x: cp2[i-1][0], y: cp2[i-1][1]); paths[digit].addCurveToPoint(endpoint, controlPoint1: cp1, controlPoint2: cp2); } } } // ************************************************************************************************* // * Interpolators for rate of change of animation // ************************************************************************************************* public class LinearInterpolator: InterpolatorProtocol { public init() { } public func getInterpolation(x: CGFloat) -> CGFloat { return x; } } public class OvershootInterpolator: InterpolatorProtocol { private var tension: CGFloat; public convenience init() { self.init(tension: 2.0); } public init(tension: CGFloat) { self.tension = tension; } public func getInterpolation(x: CGFloat) -> CGFloat { let x2 = x - 1.0; return x2 * x2 * ((tension + 1) * x2 + tension) + 1.0; } } public class SpringInterpolator: InterpolatorProtocol { private var tension: CGFloat; private let PI = CGFloat(M_PI); public convenience init() { self.init(tension: 0.3); } public init(tension: CGFloat) { self.tension = tension; } public func getInterpolation(x: CGFloat) -> CGFloat { return pow(2, -10 * x) * sin((x - tension / 4) * (2 * PI) / tension) + 1; } } public class BounceInterpolator: InterpolatorProtocol { public init() { } func bounce(t: CGFloat) -> CGFloat { return t * t * 8; } public func getInterpolation(x: CGFloat) -> CGFloat { if (x < 0.3535) { return bounce(x) } else if (x < 0.7408) { return bounce(x - 0.54719) + 0.7; } else if (x < 0.9644) { return bounce(x - 0.8526) + 0.9; } else { return bounce(x - 1.0435) + 0.95; } } } public class AnticipateOvershootInterpolator: InterpolatorProtocol { private var tension: CGFloat = 2.0; public convenience init() { self.init(tension: 2.0); } public init(tension: CGFloat) { self.tension = tension; } private func anticipate(x: CGFloat, tension: CGFloat) -> CGFloat { return x * x * ((tension + 1) * x - tension); } private func overshoot(x: CGFloat, tension: CGFloat) -> CGFloat { return x * x * ((tension + 1) * x + tension); } public func getInterpolation(x: CGFloat) -> CGFloat { if x < 0.5 { return 0.5 * anticipate(x * 2.0, tension: tension); } else { return 0.5 * (overshoot(x * 2.0 - 2.0, tension: tension) + 2.0); } } } public class CubicHermiteInterpolator: InterpolatorProtocol { private var tangent0: CGFloat; private var tangent1: CGFloat; public convenience init() { self.init(tangent0: 2.2, tangent1: 2.2); } public init(tangent0: CGFloat, tangent1: CGFloat) { self.tangent0 = tangent0; self.tangent1 = tangent1; } func cubicHermite(t: CGFloat, start: CGFloat, end: CGFloat, tangent0: CGFloat, tangent1: CGFloat) -> CGFloat { let t2 = t * t; let t3 = t2 * t; return (2 * t3 - 3 * t2 + 1) * start + (t3 - 2 * t2 + t) * tangent0 + (-2 * t3 + 3 * t2) * end + (t3 - t2) * tangent1; } public func getInterpolation(x: CGFloat) -> CGFloat { return cubicHermite(x, start: 0, end: 1, tangent0: tangent0, tangent1: tangent1); } } }
mit
5cc958af18aad2d27feff073de4af164
38.187764
156
0.511763
4.190165
false
false
false
false
ILI4S/RingBuffer
RingBufferSources/RingBuffer.swift
2
5081
import TPCircularBuffer // MARK: Implementation public final class RingBuffer<T> { /// The total number of elements the instance may contain public let capacity: Int /// The size of an element in bytes private let elementSize: Int32 = Int32(MemoryLayout<T>.size) /// The underlying circular buffer instance private var tpCircularBuffer = TPCircularBuffer() /// The capacity the instance has remaining available public var availableCapacity: Int { var availableBytes: Int32 = 0 let _ = TPCircularBufferTail(&tpCircularBuffer, &availableBytes)?.assumingMemoryBound(to: T.self) return capacity - min(Int(availableBytes / elementSize), capacity) } /// The number of elements contained in the instance public var count: Int { var availableBytes: Int32 = 0 let _ = TPCircularBufferTail(&tpCircularBuffer, &availableBytes)?.assumingMemoryBound(to: T.self) return min(Int(availableBytes / elementSize), capacity) } /// The front of the buffer for writing public var head: UnsafeMutableBufferPointer<T>? { get { var availableBytes: Int32 = 0 guard let bufferHead = TPCircularBufferHead(&tpCircularBuffer, &availableBytes)?.assumingMemoryBound(to: T.self) else { return nil } // We don't use available bytes as the underlying TPCircularBuffer // may have overallocated memory in order to accomodate page sizes. return UnsafeMutableBufferPointer(start: bufferHead, count: availableCapacity) } } /// The end of the buffer for reading public var tail: UnsafeBufferPointer<T>? { var availableBytes: Int32 = 0 guard let bufferTail = TPCircularBufferTail(&tpCircularBuffer, &availableBytes)?.assumingMemoryBound(to: T.self) else { return nil } let count = min(Int(availableBytes / elementSize), capacity) return UnsafeBufferPointer(start: bufferTail, count: count) } /// Inserts an element at the start of the instance's tail /// /// If the ring buffer lacks space, this method will discard the last /// element in its memory (ie. "tail"). /// public func feed(_ element: T) { if availableCapacity == 0 { free() } var element = element TPCircularBufferProduceBytes(&tpCircularBuffer, &element, elementSize) } /// Inserts up to as many elements as the instance may contain at once /// /// If the ring buffer lacks space, this method will discard as many /// elements from its memory (ie. "tail") as necessary. /// public func feed<CollectionType>(contentsOf elements: CollectionType) where CollectionType: Collection, CollectionType.Iterator.Element == T, CollectionType.IndexDistance == Int { if availableCapacity < elements.count { free(min(elements.count - availableCapacity, count)) } var elements = Array<T>(Array<T>(elements)[max(elements.count - capacity, 0) ..< elements.count]) let size = Int32(MemoryLayout<T>.size * elements.count) TPCircularBufferProduceBytes(&tpCircularBuffer, &elements, size) } /// Discards elements from memory (ie. "tail") /// public func free(_ n: Int = 1) { assert(n <= count) TPCircularBufferConsume(&tpCircularBuffer, Int32(n) * elementSize) } // MARK: Initialization & deinitialization public init?(capacity: Int) { precondition(capacity > 0) self.capacity = capacity let byteSize = capacity * Int(elementSize) precondition(byteSize < Int(INT32_MAX)) if !_TPCircularBufferInit(&tpCircularBuffer, Int32(byteSize), MemoryLayout<TPCircularBuffer>.size) { // _TPCircularBufferInit typically returns false with the message: // Buffer allocation: (os/kern) no space available return nil } } deinit { TPCircularBufferCleanup(&tpCircularBuffer) } } // MARK: << "Feed" operator extension RingBuffer { public static func <<(lhs: RingBuffer<T>, rhs: T) -> RingBuffer<T> { lhs.feed(rhs) return lhs } public static func <<<CollectionType>(lhs: RingBuffer<T>, rhs: CollectionType) -> RingBuffer<T> where CollectionType: Collection, CollectionType.Iterator.Element == T, CollectionType.IndexDistance == Int { lhs.feed(contentsOf: rhs) return lhs } } // MARK: CustomStringConvertible adoption extension RingBuffer: CustomStringConvertible { public var description: String { guard let tail = tail else { return [].description } return Array<T>(tail).description } } // MARK: CustomDebugStringConvertible adoption extension RingBuffer: CustomDebugStringConvertible { public var debugDescription: String { return "\(count)/\(capacity) elements: \(description)" } }
mit
42395bfad39e4b68f79c81da67700945
31.363057
210
0.645739
4.775376
false
false
false
false
qualaroo/QualarooSDKiOS
QualarooTests/Filters/ActiveFilterSpec.swift
1
1058
// // ActiveFilterSpec.swift // QualarooTests // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation import Quick import Nimble @testable import Qualaroo class ActiveFilterSpec: QuickSpec { override func spec() { super.spec() describe("ActiveFilter") { let filter = ActiveFilter() it("shows active survey") { var dict = JsonLibrary.survey() dict["active"] = true let survey = try! SurveyFactory(with: dict).build() let result = filter.shouldShow(survey: survey) expect(result).to(beTrue()) } it("doesn't show inactive survey") { var dict = JsonLibrary.survey() dict["active"] = false let survey = try! SurveyFactory(with: dict).build() let result = filter.shouldShow(survey: survey) expect(result).to(beFalse()) } } } }
mit
1ba5a1f159b3d7476bfef2925d217362
24.190476
68
0.614367
4.14902
false
false
false
false
Tomikes/eidolon
KioskTests/Bid Fulfillment/RegistrationPasswordViewControllerTests.swift
7
2459
import Quick import Nimble @testable import Kiosk import ReactiveCocoa import Nimble_Snapshots import Moya class RegistrationPasswordViewControllerTests: QuickSpec { func testSubject(emailExists emailExists: Bool = false) -> RegistrationPasswordViewController { class TestViewModel: RegistrationPasswordViewModel { init (emailExists: Bool = false) { super.init(passwordSignal: RACSignal.empty(), manualInvocationSignal: RACSignal.empty(), finishedSubject: RACSubject(), email: "") emailExistsSignal = RACSignal.`return`(emailExists).replay() } } let subject = RegistrationPasswordViewController.instantiateFromStoryboard(fulfillmentStoryboard) subject.bidDetails = BidDetails.stubbedBidDetails() subject.viewModel = TestViewModel(emailExists: emailExists) return subject } override func spec() { it("looks right by default") { let subject = self.testSubject() expect(subject).to( haveValidSnapshot() ) } it("looks right with an existing email") { let subject = self.testSubject(emailExists: true) expect(subject).to( haveValidSnapshot() ) } it("looks right with a valid password") { let subject = self.testSubject() subject.loadViewProgrammatically() subject.passwordTextField.text = "password" expect(subject).to( haveValidSnapshot() ) } it("looks right with an invalid password") { let subject = self.testSubject() subject.loadViewProgrammatically() subject.passwordTextField.text = "short" expect(subject).to( haveValidSnapshot() ) } it("unbinds bidDetails on viewWillDisappear:") { let runLifecycleOfViewController = { (bidDetails: BidDetails) -> RegistrationPasswordViewController in let subject = RegistrationPasswordViewController.instantiateFromStoryboard(fulfillmentStoryboard) subject.bidDetails = bidDetails subject.loadViewProgrammatically() subject.viewWillDisappear(false) return subject } let bidDetails = testBidDetails() runLifecycleOfViewController(bidDetails) expect { runLifecycleOfViewController(bidDetails) }.toNot( raiseException() ) } } }
mit
87c2accf161383e79937a247e7e81af3
35.701493
146
0.648231
5.758782
false
true
false
false
jacobwhite/firefox-ios
Extensions/ShareTo/InitialViewController.swift
1
3154
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SnapKit import Deferred import Shared import Storage /* The initial view controller is full-screen and is the only one with a valid extension context. It is just a wrapper with a semi-transparent background to darken the screen that embeds the share view controller which is designed to look like a popup. The share view controller is embedded using a navigation controller to get a nav bar and standard iOS navigation behaviour. */ class EmbeddedNavController { weak var parent: UIViewController? var controllers = [UIViewController]() var navigationController: UINavigationController init (parent: UIViewController, rootViewController: UIViewController) { self.parent = parent navigationController = UINavigationController(rootViewController: rootViewController) parent.addChildViewController(navigationController) parent.view.addSubview(navigationController.view) let width = min(UIScreen.main.bounds.width, CGFloat(UX.topViewWidth)) navigationController.view.snp.makeConstraints { make in make.center.equalToSuperview() make.width.equalTo(width) make.height.equalTo(UX.topViewHeight) } navigationController.view.layer.cornerRadius = UX.dialogCornerRadius navigationController.view.layer.masksToBounds = true } deinit { navigationController.view.removeFromSuperview() navigationController.removeFromParentViewController() } } @objc(InitialViewController) class InitialViewController: UIViewController { var embedController: EmbeddedNavController! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white: 0.0, alpha: UX.alphaForFullscreenOverlay) let popupView = ShareViewController() popupView.delegate = self embedController = EmbeddedNavController(parent: self, rootViewController: popupView) } } extension InitialViewController: ShareControllerDelegate { func finish(afterDelay: TimeInterval) { UIView.animate(withDuration: 0.2, delay: afterDelay, options: [], animations: { self.view.alpha = 0 }, completion: { _ in self.extensionContext?.completeRequest(returningItems: [], completionHandler: nil) }) } func getValidExtensionContext() -> NSExtensionContext? { return extensionContext } func getShareItem() -> Deferred<ShareItem?> { let deferred = Deferred<ShareItem?>() ExtensionUtils.extractSharedItemFromExtensionContext(extensionContext, completionHandler: { item, error in if let item = item, error == nil { deferred.fill(item) } else { deferred.fill(nil) self.extensionContext?.completeRequest(returningItems: [], completionHandler: nil) } }) return deferred } }
mpl-2.0
bd7b66988af340f383843b869254a4b3
34.438202
114
0.702283
5.30084
false
false
false
false
cao903775389/OLNetwork
OLNetwork/Classes/HttpNetwork/OLHttpRequest.swift
1
8737
// // OLHttpRequest.swift // BeautyHttpNetwork // 网络请求信息体封装 // Created by 逢阳曹 on 2016/10/18. // Copyright © 2016年 逢阳曹. All rights reserved. // import UIKit import Foundation import AFNetworking //网络请求方式 public enum OLHttpMethod: UInt { case GET = 0 case POST = 1 case UPLOAD = 2 case DOWNLOAD = 3 } //请求发起序列化方式 public enum OLHttpRequestSerializerType: Int { case HTTP case JSON } //请求响应序列化方式 public enum OLHttpResponseSerializerType: Int { case HTTP case JSON case XML } //请求结果校验 enum OLHttpRequestValidationError: Int { case InvalidStatusCode = -10000//URLResponse状态码异常 case InvalidJSONFormat = -10001//JSON数据验证异常 case InvalidErrorCode = -10002//服务器ErrorCode异常 } //ErrorDimain let OLHttpRequestValidationErrorDomain = "com.ol.request.validation" //网络请求信息包装类 public class OLHttpRequest: NSObject, OLHttpRequestAccessory { /** * !@brief 请求体相关 */ //NSURLSessionTask 实际请求的发起类 (iOS7之后NSURLConnection的替代) public var requestTask: URLSessionTask? //请求url public var requestUrl: String! //请求参数 public var requestArgument: [String: Any]? //请求头信息 public var requestHeaders: [String: Any]? //请求附加信息 不传默认为空 public var requestUserInfo: [String: Any]? //流文件上传请求回调(图片 视频 表单 等流文件上传时使用) public var constructingBlock: ((AFMultipartFormData) -> Void)? //流文件下载请求目标路径(仅在使用断点续传下载请求时使用) public var resumableDownloadPath: String? //请求的接口号 public var requestCode: OLCode! //请求超时时间 public var requestTimeoutInterval: TimeInterval! //请求发起序列化方式 public var requestSerializerType: OLHttpRequestSerializerType! //请求响应序列化方式 public var responseSerializerType: OLHttpResponseSerializerType! //请求签名认证的用户名和密码(在某些情况下需要 如登录 注册) public var requestAuthorizationHeaderFieldArray: [String]? //请求方式 public var requestMethod: OLHttpMethod! /** * !@brief 返回体相关 */ //请求返回体 public var response: HTTPURLResponse? { get { return self.requestTask?.response as? HTTPURLResponse } } //返回体头信息 public var responseHeaders: NSDictionary? { get { return self.response?.allHeaderFields as NSDictionary? } } //返回体状态码 public var statusCode: Int? { get { return self.response?.statusCode } } //服务器错误码 public var errorCode: Int? //服务器错误信息 public var errorMsg: String? //返回体JSON对象(JSON数据 如果是下载任务 那么该值返回的是文件下载成功后被保存的URL路径) public var responseObject: AnyObject? //请求完成回调 public weak var delegate: OLHttpRequestDelegate? //MARK: initialize //普通请求(POST GET) public convenience init(delegate: OLHttpRequestDelegate?, requestMethod: OLHttpMethod = OLHttpMethod.POST, requestUrl: String, requestArgument: [String: Any]?, OL_CODE: OLCode) { self.init(delegate: delegate, requestMethod: requestMethod, requestUrl: requestUrl, requestArgument: requestArgument, requestHeaders: nil, OL_CODE: OL_CODE, requestSerializerType: OLHttpRequestSerializerType.HTTP, responseSerializerType: OLHttpResponseSerializerType.JSON, requestTimeoutInterval: 30, requestAuthorizationHeaderFieldArray: nil, constructingBlock: nil, resumableDownloadPath: nil) } //上传请求(UPLOAD) public convenience init(delegate: OLHttpRequestDelegate?, requestMethod: OLHttpMethod = OLHttpMethod.UPLOAD, requestUrl: String, requestArgument: [String: Any]?, constructingBlock: @escaping (AFMultipartFormData) -> Void, OL_CODE: OLCode) { self.init(delegate: delegate, requestMethod: requestMethod, requestUrl: requestUrl, requestArgument: requestArgument, requestHeaders: nil, OL_CODE: OL_CODE, requestSerializerType: OLHttpRequestSerializerType.HTTP, responseSerializerType: OLHttpResponseSerializerType.JSON, requestTimeoutInterval: 30, requestAuthorizationHeaderFieldArray: nil, constructingBlock: constructingBlock, resumableDownloadPath: nil) } //下载请求(DOWMLOAD) public convenience init(delegate: OLHttpRequestDelegate?, requestMethod: OLHttpMethod = OLHttpMethod.DOWNLOAD, requestUrl: String, requestArgument: [String: Any]?, resumableDownloadPath: String, OL_CODE: OLCode) { self.init(delegate: delegate, requestMethod: requestMethod, requestUrl: requestUrl, requestArgument: requestArgument, requestHeaders: nil, OL_CODE: OL_CODE, requestSerializerType: OLHttpRequestSerializerType.HTTP, responseSerializerType: OLHttpResponseSerializerType.JSON, requestTimeoutInterval: 30, requestAuthorizationHeaderFieldArray: nil, constructingBlock: nil, resumableDownloadPath: resumableDownloadPath) } //MARK: Public public func start() { OLHttpRequestManager.sharedOLHttpRequestManager.sendHttpRequest(request: self) } public func cancleDelegateAndRequest() { self.delegate = nil OLHttpRequestManager.sharedOLHttpRequestManager.cancleHttpRequest(request: self) } //MARK: - OLHttpRequestAccessory public func ol_requestCustomArgument(requestArgument: [String : Any]?) -> [String: Any]? { //子类overload此方法实现参数自定义 return nil } public func ol_requestCustomHTTPHeaderfileds(headerfileds: [String : Any]?) -> [String : Any]? { //子类overload此方法实现header头信息自定义 return nil } public func ol_requestCustomJSONValidator() -> Bool { //子类overload此方法实现ResponseJSON格式校验 return true } //MARK: Private public override init() { super.init() self.setUp() } //如果需要自定义更多内容可以使用该方法 public convenience init(delegate: OLHttpRequestDelegate?, requestMethod: OLHttpMethod = OLHttpMethod.POST, requestUrl: String, requestArgument: [String: Any]?, requestHeaders: [String: Any]?, OL_CODE: OLCode, requestSerializerType: OLHttpRequestSerializerType = OLHttpRequestSerializerType.HTTP, responseSerializerType: OLHttpResponseSerializerType = OLHttpResponseSerializerType.JSON, requestTimeoutInterval: TimeInterval = 30, requestAuthorizationHeaderFieldArray: [String]?, constructingBlock: ((AFMultipartFormData) -> Void)?, resumableDownloadPath: String?) { self.init() self.delegate = delegate self.requestUrl = requestUrl self.requestCode = OL_CODE self.requestArgument = self.ol_requestCustomArgument(requestArgument: requestArgument) self.requestAuthorizationHeaderFieldArray = requestAuthorizationHeaderFieldArray self.constructingBlock = constructingBlock self.resumableDownloadPath = resumableDownloadPath self.requestSerializerType = requestSerializerType self.responseSerializerType = responseSerializerType self.requestTimeoutInterval = requestTimeoutInterval self.requestMethod = requestMethod self.requestHeaders = self.ol_requestCustomHTTPHeaderfileds(headerfileds: requestHeaders) } private func setUp() { self.requestSerializerType = OLHttpRequestSerializerType.HTTP self.responseSerializerType = OLHttpResponseSerializerType.JSON self.requestTimeoutInterval = 30 self.requestMethod = OLHttpMethod.POST } }
mit
35997f203c39fc4bc1e385d76b3b4a7c
34.122807
421
0.651474
4.79234
false
false
false
false
grifas/AGNavigationBarShape
AGNavigationBarShape/Classes/AGNavigationBarShape.swift
1
4641
// // AGNavigationBarShape.swift // AGNavigationBarShape // // Created by Aurelien Grifasi on 14/05/16. // Copyright © 2016 Aurelien Grifasi. All rights reserved. // import UIKit // Availables Shapes public enum ShapeMode: Int { case zigzag = 0 case wave case square } public class AGNavigationBarShape: UINavigationBar { @IBInspectable public var color: UIColor = UIColor(red: (251.0/255.0), green: (101.0/255), blue: (68.0/255.0), alpha: 1.0) @IBInspectable public var cycles: Int = 9 @IBInspectable public var shapeMode: Int = 0 { didSet { self.shapeMode = ShapeMode(rawValue: self.shapeMode)?.rawValue ?? 0 } } @IBInspectable public var heightShape: Int = 10 { didSet { self.heightShape = self.heightShape >= 0 ? self.heightShape : 0 } } override public func draw(_ rect: CGRect) { let bezierPath: UIBezierPath = UIBezierPath() // Apply color on status bar if let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as? UIView { if statusBar.responds(to: #selector(setter: UIView.backgroundColor)) { statusBar.backgroundColor = self.color } } // Draw Shape switch ShapeMode(rawValue: self.shapeMode)! { case .wave: self.drawWave(bezierPath) case .square: self.drawSquare(bezierPath) default: self.drawZigzag(bezierPath) } // Fill Shape self.color.setFill() bezierPath.fill() // Mask to Path let shapeLayer = CAShapeLayer() shapeLayer.path = bezierPath.cgPath self.layer.mask = shapeLayer // Display Shape thanks to layer shadow self.layer.shadowPath = bezierPath.cgPath self.layer.shadowColor = self.color.cgColor self.layer.shadowOpacity = 1 self.layer.shadowOffset = CGSize(width: 0, height: 5) self.layer.shouldRasterize = true } /* Add a Zigzag shape to the navigation bar */ func drawZigzag(_ bezierPath: UIBezierPath) { let width = self.layer.frame.width let height = self.layer.frame.height bezierPath.move(to: CGPoint(x: 0, y: 0)) bezierPath.addLine(to: CGPoint(x: 0, y: height)) let cycleSizeHalf: CGFloat = (width / CGFloat(self.cycles)) / 2 var x: CGFloat = 0 for _ in 1...(self.cycles * 2) { x = x + cycleSizeHalf bezierPath.addLine(to: CGPoint(x: x, y: height + CGFloat(self.heightShape))) x = x + cycleSizeHalf bezierPath.addLine(to: CGPoint(x: x, y: height)) } bezierPath.addLine(to: CGPoint(x: width, y: 0)) bezierPath.close() } /* Add a Wave shape to the navigation bar */ func drawWave(_ bezierPath: UIBezierPath) { let width = self.layer.frame.width let height = self.layer.frame.height // Mandatory Odd number if self.cycles % 2 == 0 { self.cycles += 1 } bezierPath.move(to: CGPoint(x: 0, y: 0)) bezierPath.addLine(to: CGPoint(x: 0, y: height)) let cycleSize = width / CGFloat(self.cycles) var x: CGFloat = 0 let arcHeight = CGFloat(self.heightShape) / 2 let y: CGFloat = height + arcHeight for i in 0..<self.cycles { if (i % 2) == 0 { if (i + 1) == self.cycles { bezierPath.addQuadCurve(to: CGPoint(x: x + cycleSize, y: height), controlPoint: CGPoint(x: x + cycleSize / 2, y: y + arcHeight)) } else { bezierPath.addQuadCurve(to: CGPoint(x: x + cycleSize, y: y), controlPoint: CGPoint(x: x + cycleSize / 2, y: y + arcHeight)) } } else { bezierPath.addQuadCurve(to: CGPoint(x: x + cycleSize, y: y), controlPoint: CGPoint(x: x + cycleSize / 2, y: y - arcHeight)) } x += cycleSize } bezierPath.addLine(to: CGPoint(x: width, y: 0)) bezierPath.close() } /* Add a Square shape to the navigation bar */ func drawSquare(_ bezierPath: UIBezierPath) { let width = self.layer.frame.width let height = self.layer.frame.height bezierPath.move(to: CGPoint(x: 0, y: 0)) bezierPath.addLine(to: CGPoint(x: 0, y: height)) let cycleSize: CGFloat = width / CGFloat(self.cycles * 2) let xOffset = cycleSize / 2 var x = xOffset bezierPath.addLine(to: CGPoint(x: xOffset, y: height)) for i in 0..<self.cycles { bezierPath.addLine(to: CGPoint(x: x, y: height + CGFloat(self.heightShape))) x = x + cycleSize bezierPath.addLine(to: CGPoint(x: x, y: height + CGFloat(self.heightShape))) bezierPath.addLine(to: CGPoint(x: x, y: height)) if (i + 1) != self.cycles { x = x + cycleSize bezierPath.addLine(to: CGPoint(x: x, y: height)) } } x = x + xOffset bezierPath.addLine(to: CGPoint(x: x, y: height)) bezierPath.addLine(to: CGPoint(x: width, y: 0)) bezierPath.close() } }
mit
a8d3bf33dbf8fca3fe6447bf14f78dff
28
133
0.649353
3.316655
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Gutenberg/Layout Picker/CategorySectionTableViewCell.swift
1
7803
import UIKit import Gutenberg protocol CategorySectionTableViewCellDelegate: AnyObject { func didSelectItemAt(_ position: Int, forCell cell: CategorySectionTableViewCell, slug: String) func didDeselectItem(forCell cell: CategorySectionTableViewCell) func accessibilityElementDidBecomeFocused(forCell cell: CategorySectionTableViewCell) func saveHorizontalScrollPosition(forCell cell: CategorySectionTableViewCell, xPosition: CGFloat) var selectedPreviewDevice: PreviewDeviceSelectionViewController.PreviewDevice { get } } protocol Thumbnail { var urlDesktop: String? { get } var urlTablet: String? { get } var urlMobile: String? { get } var slug: String { get } } protocol CategorySection { var categorySlug: String { get } var caption: String? { get } var title: String { get } var emoji: String? { get } var description: String? { get } var thumbnails: [Thumbnail] { get } var thumbnailSize: CGSize { get } } class CategorySectionTableViewCell: UITableViewCell { static let cellReuseIdentifier = "\(CategorySectionTableViewCell.self)" static let nib = UINib(nibName: "\(CategorySectionTableViewCell.self)", bundle: Bundle.main) static let defaultThumbnailSize = CGSize(width: 160, height: 240) static let cellVerticalPadding: CGFloat = 70 @IBOutlet weak var categoryTitle: UILabel! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var collectionViewHeight: NSLayoutConstraint! @IBOutlet weak var categoryCaptionLabel: UILabel! weak var delegate: CategorySectionTableViewCellDelegate? private var thumbnails = [Thumbnail]() { didSet { collectionView.reloadData() } } var section: CategorySection? = nil { didSet { thumbnails = section?.thumbnails ?? [] categoryTitle.text = section?.title setCaption() if let section = section { collectionViewHeight.constant = section.thumbnailSize.height setNeedsUpdateConstraints() } } } var categoryTitleFont: UIFont? { didSet { categoryTitle.font = categoryTitleFont ?? WPStyleGuide.serifFontForTextStyle(UIFont.TextStyle.headline, fontWeight: .semibold) } } private func setCaption() { guard let caption = section?.caption else { categoryCaptionLabel.isHidden = true return } categoryCaptionLabel.isHidden = false categoryCaptionLabel.setText(caption) } var isGhostCell: Bool = false var ghostThumbnailSize: CGSize = defaultThumbnailSize { didSet { collectionViewHeight.constant = ghostThumbnailSize.height setNeedsUpdateConstraints() } } var showsCheckMarkWhenSelected = true var horizontalScrollOffset: CGFloat = .zero { didSet { collectionView.contentOffset.x = horizontalScrollOffset } } override func prepareForReuse() { delegate = nil super.prepareForReuse() collectionView.contentOffset.x = 0 categoryTitleFont = nil } override func awakeFromNib() { super.awakeFromNib() collectionView.register(CollapsableHeaderCollectionViewCell.nib, forCellWithReuseIdentifier: CollapsableHeaderCollectionViewCell.cellReuseIdentifier) categoryTitle.font = categoryTitleFont ?? WPStyleGuide.serifFontForTextStyle(UIFont.TextStyle.headline, fontWeight: .semibold) categoryTitle.layer.masksToBounds = true categoryTitle.layer.cornerRadius = 4 categoryCaptionLabel.font = WPStyleGuide.fontForTextStyle(.footnote, fontWeight: .regular) setCaption() } private func deselectItem(_ indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) collectionView(collectionView, didDeselectItemAt: indexPath) } func deselectItems() { guard let selectedItems = collectionView.indexPathsForSelectedItems else { return } selectedItems.forEach { (indexPath) in collectionView.deselectItem(at: indexPath, animated: true) } } func selectItemAt(_ position: Int) { collectionView.selectItem(at: IndexPath(item: position, section: 0), animated: false, scrollPosition: []) } } extension CategorySectionTableViewCell: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { if collectionView.cellForItem(at: indexPath)?.isSelected ?? false { deselectItem(indexPath) return false } return true } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let slug = section?.categorySlug else { return } delegate?.didSelectItemAt(indexPath.item, forCell: self, slug: slug) } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { delegate?.didDeselectItem(forCell: self) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { delegate?.saveHorizontalScrollPosition(forCell: self, xPosition: scrollView.contentOffset.x) } } extension CategorySectionTableViewCell: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return section?.thumbnailSize ?? ghostThumbnailSize } } extension CategorySectionTableViewCell: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return isGhostCell ? 1 : thumbnails.count } func collectionView(_ LayoutPickerCategoryTableViewCell: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cellReuseIdentifier = CollapsableHeaderCollectionViewCell.cellReuseIdentifier guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath) as? CollapsableHeaderCollectionViewCell else { fatalError("Expected the cell with identifier \"\(cellReuseIdentifier)\" to be a \(CollapsableHeaderCollectionViewCell.self). Please make sure the collection view is registering the correct nib before loading the data") } guard !isGhostCell else { cell.startGhostAnimation(style: GhostCellStyle.muriel) return cell } let thumbnail = thumbnails[indexPath.row] cell.previewURL = thumbnailUrl(forThumbnail: thumbnail) cell.showsCheckMarkWhenSelected = showsCheckMarkWhenSelected cell.isAccessibilityElement = true cell.accessibilityLabel = thumbnail.slug return cell } private func thumbnailUrl(forThumbnail thumbnail: Thumbnail) -> String? { guard let delegate = delegate else { return thumbnail.urlDesktop } switch delegate.selectedPreviewDevice { case .desktop: return thumbnail.urlDesktop case .tablet: return thumbnail.urlTablet case .mobile: return thumbnail.urlMobile } } } /// Accessibility extension CategorySectionTableViewCell { override func accessibilityElementDidBecomeFocused() { delegate?.accessibilityElementDidBecomeFocused(forCell: self) } } class AccessibleCollectionView: UICollectionView { override func accessibilityElementCount() -> Int { guard let dataSource = dataSource else { return 0 } return dataSource.collectionView(self, numberOfItemsInSection: 0) } }
gpl-2.0
40fb6be960b00b15d9e3340c3bfa418d
36.695652
231
0.706139
5.767184
false
false
false
false
johnno1962b/swift-corelibs-foundation
TestFoundation/TestDateFormatter.swift
3
18888
// 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 // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestDateFormatter: XCTestCase { let DEFAULT_LOCALE = "en_US" let DEFAULT_TIMEZONE = "GMT" static var allTests : [(String, (TestDateFormatter) -> () throws -> Void)] { return [ ("test_BasicConstruction", test_BasicConstruction), ("test_dateStyleShort", test_dateStyleShort), ("test_dateStyleMedium", test_dateStyleMedium), ("test_dateStyleLong", test_dateStyleLong), ("test_dateStyleFull", test_dateStyleFull), ("test_customDateFormat", test_customDateFormat), ("test_setLocalizedDateFormatFromTemplate", test_setLocalizedDateFormatFromTemplate), ("test_dateFormatString", test_dateFormatString), ] } func test_BasicConstruction() { let symbolDictionaryOne = ["eraSymbols" : ["BC", "AD"], "monthSymbols" : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], "shortMonthSymbols" : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], "weekdaySymbols" : ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], "shortWeekdaySymbols" : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], "longEraSymbols" : ["Before Christ", "Anno Domini"], "veryShortMonthSymbols" : ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"], "standaloneMonthSymbols" : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], "shortStandaloneMonthSymbols" : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], "veryShortStandaloneMonthSymbols" : ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]] let symbolDictionaryTwo = ["veryShortWeekdaySymbols" : ["S", "M", "T", "W", "T", "F", "S"], "standaloneWeekdaySymbols" : ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], "shortStandaloneWeekdaySymbols" : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], "veryShortStandaloneWeekdaySymbols" : ["S", "M", "T", "W", "T", "F", "S"], "quarterSymbols" : ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"], "shortQuarterSymbols" : ["Q1", "Q2", "Q3", "Q4"], "standaloneQuarterSymbols" : ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"], "shortStandaloneQuarterSymbols" : ["Q1", "Q2", "Q3", "Q4"]] let f = DateFormatter() XCTAssertNotNil(f) XCTAssertNotNil(f.timeZone) XCTAssertNotNil(f.locale) f.timeZone = TimeZone(identifier: DEFAULT_TIMEZONE) f.locale = Locale(identifier: DEFAULT_LOCALE) // Assert default values are set properly XCTAssertFalse(f.generatesCalendarDates) XCTAssertNotNil(f.calendar) XCTAssertFalse(f.isLenient) XCTAssertEqual(f.twoDigitStartDate!, Date(timeIntervalSince1970: -631152000)) XCTAssertNil(f.defaultDate) XCTAssertEqual(f.eraSymbols, symbolDictionaryOne["eraSymbols"]!) XCTAssertEqual(f.monthSymbols, symbolDictionaryOne["monthSymbols"]!) XCTAssertEqual(f.shortMonthSymbols, symbolDictionaryOne["shortMonthSymbols"]!) XCTAssertEqual(f.weekdaySymbols, symbolDictionaryOne["weekdaySymbols"]!) XCTAssertEqual(f.shortWeekdaySymbols, symbolDictionaryOne["shortWeekdaySymbols"]!) XCTAssertEqual(f.amSymbol, "AM") XCTAssertEqual(f.pmSymbol, "PM") XCTAssertEqual(f.longEraSymbols, symbolDictionaryOne["longEraSymbols"]!) XCTAssertEqual(f.veryShortMonthSymbols, symbolDictionaryOne["veryShortMonthSymbols"]!) XCTAssertEqual(f.standaloneMonthSymbols, symbolDictionaryOne["standaloneMonthSymbols"]!) XCTAssertEqual(f.shortStandaloneMonthSymbols, symbolDictionaryOne["shortStandaloneMonthSymbols"]!) XCTAssertEqual(f.veryShortStandaloneMonthSymbols, symbolDictionaryOne["veryShortStandaloneMonthSymbols"]!) XCTAssertEqual(f.veryShortWeekdaySymbols, symbolDictionaryTwo["veryShortWeekdaySymbols"]!) XCTAssertEqual(f.standaloneWeekdaySymbols, symbolDictionaryTwo["standaloneWeekdaySymbols"]!) XCTAssertEqual(f.shortStandaloneWeekdaySymbols, symbolDictionaryTwo["shortStandaloneWeekdaySymbols"]!) XCTAssertEqual(f.veryShortStandaloneWeekdaySymbols, symbolDictionaryTwo["veryShortStandaloneWeekdaySymbols"]!) XCTAssertEqual(f.quarterSymbols, symbolDictionaryTwo["quarterSymbols"]!) XCTAssertEqual(f.shortQuarterSymbols, symbolDictionaryTwo["shortQuarterSymbols"]!) XCTAssertEqual(f.standaloneQuarterSymbols, symbolDictionaryTwo["standaloneQuarterSymbols"]!) XCTAssertEqual(f.shortStandaloneQuarterSymbols, symbolDictionaryTwo["shortStandaloneQuarterSymbols"]!) XCTAssertEqual(f.gregorianStartDate, Date(timeIntervalSince1970: -12219292800)) XCTAssertFalse(f.doesRelativeDateFormatting) } // ShortStyle // locale stringFromDate example // ------ -------------- -------- // en_US M/d/yy h:mm a 12/25/15 12:00 AM func test_dateStyleShort() { let timestamps = [ -31536000 : "1/1/69, 12:00 AM" , 0.0 : "1/1/70, 12:00 AM", 31536000 : "1/1/71, 12:00 AM", 2145916800 : "1/1/38, 12:00 AM", 1456272000 : "2/24/16, 12:00 AM", 1456358399 : "2/24/16, 11:59 PM", 1452574638 : "1/12/16, 4:57 AM", 1455685038 : "2/17/16, 4:57 AM", 1458622638 : "3/22/16, 4:57 AM", 1459745838 : "4/4/16, 4:57 AM", 1462597038 : "5/7/16, 4:57 AM", 1465534638 : "6/10/16, 4:57 AM", 1469854638 : "7/30/16, 4:57 AM", 1470718638 : "8/9/16, 4:57 AM", 1473915438 : "9/15/16, 4:57 AM", 1477285038 : "10/24/16, 4:57 AM", 1478062638 : "11/2/16, 4:57 AM", 1482641838 : "12/25/16, 4:57 AM" ] let f = DateFormatter() f.dateStyle = .short f.timeStyle = .short // ensure tests give consistent results by setting specific timeZone and locale f.timeZone = TimeZone(identifier: DEFAULT_TIMEZONE) f.locale = Locale(identifier: DEFAULT_LOCALE) for (timestamp, stringResult) in timestamps { let testDate = Date(timeIntervalSince1970: timestamp) let sf = f.string(from: testDate) XCTAssertEqual(sf, stringResult) } } // MediumStyle // locale stringFromDate example // ------ -------------- ------------ // en_US MMM d, y, h:mm:ss a Dec 25, 2015, 12:00:00 AM func test_dateStyleMedium() { let timestamps = [ -31536000 : "Jan 1, 1969, 12:00:00 AM" , 0.0 : "Jan 1, 1970, 12:00:00 AM", 31536000 : "Jan 1, 1971, 12:00:00 AM", 2145916800 : "Jan 1, 2038, 12:00:00 AM", 1456272000 : "Feb 24, 2016, 12:00:00 AM", 1456358399 : "Feb 24, 2016, 11:59:59 PM", 1452574638 : "Jan 12, 2016, 4:57:18 AM", 1455685038 : "Feb 17, 2016, 4:57:18 AM", 1458622638 : "Mar 22, 2016, 4:57:18 AM", 1459745838 : "Apr 4, 2016, 4:57:18 AM", 1462597038 : "May 7, 2016, 4:57:18 AM", 1465534638 : "Jun 10, 2016, 4:57:18 AM", 1469854638 : "Jul 30, 2016, 4:57:18 AM", 1470718638 : "Aug 9, 2016, 4:57:18 AM", 1473915438 : "Sep 15, 2016, 4:57:18 AM", 1477285038 : "Oct 24, 2016, 4:57:18 AM", 1478062638 : "Nov 2, 2016, 4:57:18 AM", 1482641838 : "Dec 25, 2016, 4:57:18 AM" ] let f = DateFormatter() f.dateStyle = .medium f.timeStyle = .medium f.timeZone = TimeZone(identifier: DEFAULT_TIMEZONE) f.locale = Locale(identifier: DEFAULT_LOCALE) for (timestamp, stringResult) in timestamps { let testDate = Date(timeIntervalSince1970: timestamp) let sf = f.string(from: testDate) XCTAssertEqual(sf, stringResult) } } // LongStyle // locale stringFromDate example // ------ -------------- ----------------- // en_US MMMM d, y 'at' h:mm:ss a zzz December 25, 2015 at 12:00:00 AM GMT func test_dateStyleLong() { let timestamps = [ -31536000 : "January 1, 1969 at 12:00:00 AM GMT" , 0.0 : "January 1, 1970 at 12:00:00 AM GMT", 31536000 : "January 1, 1971 at 12:00:00 AM GMT", 2145916800 : "January 1, 2038 at 12:00:00 AM GMT", 1456272000 : "February 24, 2016 at 12:00:00 AM GMT", 1456358399 : "February 24, 2016 at 11:59:59 PM GMT", 1452574638 : "January 12, 2016 at 4:57:18 AM GMT", 1455685038 : "February 17, 2016 at 4:57:18 AM GMT", 1458622638 : "March 22, 2016 at 4:57:18 AM GMT", 1459745838 : "April 4, 2016 at 4:57:18 AM GMT", 1462597038 : "May 7, 2016 at 4:57:18 AM GMT", 1465534638 : "June 10, 2016 at 4:57:18 AM GMT", 1469854638 : "July 30, 2016 at 4:57:18 AM GMT", 1470718638 : "August 9, 2016 at 4:57:18 AM GMT", 1473915438 : "September 15, 2016 at 4:57:18 AM GMT", 1477285038 : "October 24, 2016 at 4:57:18 AM GMT", 1478062638 : "November 2, 2016 at 4:57:18 AM GMT", 1482641838 : "December 25, 2016 at 4:57:18 AM GMT" ] let f = DateFormatter() f.dateStyle = .long f.timeStyle = .long f.timeZone = TimeZone(identifier: DEFAULT_TIMEZONE) f.locale = Locale(identifier: DEFAULT_LOCALE) for (timestamp, stringResult) in timestamps { let testDate = Date(timeIntervalSince1970: timestamp) let sf = f.string(from: testDate) XCTAssertEqual(sf, stringResult) } } // FullStyle // locale stringFromDate example // ------ -------------- ------------------------- // en_US EEEE, MMMM d, y 'at' h:mm:ss a zzzz Friday, December 25, 2015 at 12:00:00 AM Greenwich Mean Time func test_dateStyleFull() { #if os(OSX) // timestyle .full is currently broken on Linux, the timezone should be 'Greenwich Mean Time' not 'GMT' let timestamps: [TimeInterval:String] = [ // Negative time offsets are still buggy on macOS -31536000 : "Wednesday, January 1, 1969 at 12:00:00 AM GMT", 0.0 : "Thursday, January 1, 1970 at 12:00:00 AM Greenwich Mean Time", 31536000 : "Friday, January 1, 1971 at 12:00:00 AM Greenwich Mean Time", 2145916800 : "Friday, January 1, 2038 at 12:00:00 AM Greenwich Mean Time", 1456272000 : "Wednesday, February 24, 2016 at 12:00:00 AM Greenwich Mean Time", 1456358399 : "Wednesday, February 24, 2016 at 11:59:59 PM Greenwich Mean Time", 1452574638 : "Tuesday, January 12, 2016 at 4:57:18 AM Greenwich Mean Time", 1455685038 : "Wednesday, February 17, 2016 at 4:57:18 AM Greenwich Mean Time", 1458622638 : "Tuesday, March 22, 2016 at 4:57:18 AM Greenwich Mean Time", 1459745838 : "Monday, April 4, 2016 at 4:57:18 AM Greenwich Mean Time", 1462597038 : "Saturday, May 7, 2016 at 4:57:18 AM Greenwich Mean Time", 1465534638 : "Friday, June 10, 2016 at 4:57:18 AM Greenwich Mean Time", 1469854638 : "Saturday, July 30, 2016 at 4:57:18 AM Greenwich Mean Time", 1470718638 : "Tuesday, August 9, 2016 at 4:57:18 AM Greenwich Mean Time", 1473915438 : "Thursday, September 15, 2016 at 4:57:18 AM Greenwich Mean Time", 1477285038 : "Monday, October 24, 2016 at 4:57:18 AM Greenwich Mean Time", 1478062638 : "Wednesday, November 2, 2016 at 4:57:18 AM Greenwich Mean Time", 1482641838 : "Sunday, December 25, 2016 at 4:57:18 AM Greenwich Mean Time" ] let f = DateFormatter() f.dateStyle = .full f.timeStyle = .full f.timeZone = TimeZone(identifier: DEFAULT_TIMEZONE) f.locale = Locale(identifier: DEFAULT_LOCALE) for (timestamp, stringResult) in timestamps { let testDate = Date(timeIntervalSince1970: timestamp) let sf = f.string(from: testDate) XCTAssertEqual(sf, stringResult) } #endif } // Custom Style // locale stringFromDate example // ------ -------------- ------------------------- // en_US EEEE, MMMM d, y 'at' hh:mm:ss a zzzz Friday, December 25, 2015 at 12:00:00 AM Greenwich Mean Time func test_customDateFormat() { let timestamps = [ // Negative time offsets are still buggy on macOS -31536000 : "Wednesday, January 1, 1969 at 12:00:00 AM GMT", 0.0 : "Thursday, January 1, 1970 at 12:00:00 AM Greenwich Mean Time", 31536000 : "Friday, January 1, 1971 at 12:00:00 AM Greenwich Mean Time", 2145916800 : "Friday, January 1, 2038 at 12:00:00 AM Greenwich Mean Time", 1456272000 : "Wednesday, February 24, 2016 at 12:00:00 AM Greenwich Mean Time", 1456358399 : "Wednesday, February 24, 2016 at 11:59:59 PM Greenwich Mean Time", 1452574638 : "Tuesday, January 12, 2016 at 04:57:18 AM Greenwich Mean Time", 1455685038 : "Wednesday, February 17, 2016 at 04:57:18 AM Greenwich Mean Time", 1458622638 : "Tuesday, March 22, 2016 at 04:57:18 AM Greenwich Mean Time", 1459745838 : "Monday, April 4, 2016 at 04:57:18 AM Greenwich Mean Time", 1462597038 : "Saturday, May 7, 2016 at 04:57:18 AM Greenwich Mean Time", 1465534638 : "Friday, June 10, 2016 at 04:57:18 AM Greenwich Mean Time", 1469854638 : "Saturday, July 30, 2016 at 04:57:18 AM Greenwich Mean Time", 1470718638 : "Tuesday, August 9, 2016 at 04:57:18 AM Greenwich Mean Time", 1473915438 : "Thursday, September 15, 2016 at 04:57:18 AM Greenwich Mean Time", 1477285038 : "Monday, October 24, 2016 at 04:57:18 AM Greenwich Mean Time", 1478062638 : "Wednesday, November 2, 2016 at 04:57:18 AM Greenwich Mean Time", 1482641838 : "Sunday, December 25, 2016 at 04:57:18 AM Greenwich Mean Time" ] let f = DateFormatter() f.timeZone = TimeZone(identifier: DEFAULT_TIMEZONE) f.locale = Locale(identifier: DEFAULT_LOCALE) #if os(OSX) // timestyle zzzz is currently broken on Linux f.dateFormat = "EEEE, MMMM d, y 'at' hh:mm:ss a zzzz" for (timestamp, stringResult) in timestamps { let testDate = Date(timeIntervalSince1970: timestamp) let sf = f.string(from: testDate) XCTAssertEqual(sf, stringResult) } #endif let quarterTimestamps: [Double : String] = [ 1451679712 : "1", 1459542112 : "2", 1467404512 : "3", 1475353312 : "4" ] f.dateFormat = "Q" for (timestamp, stringResult) in quarterTimestamps { let testDate = Date(timeIntervalSince1970: timestamp) let sf = f.string(from: testDate) XCTAssertEqual(sf, stringResult) } // Check .dateFormat resets when style changes let testDate = Date(timeIntervalSince1970: 1457738454) f.dateStyle = .medium f.timeStyle = .medium XCTAssertEqual(f.string(from: testDate), "Mar 11, 2016, 11:20:54 PM") XCTAssertEqual(f.dateFormat, "MMM d, y, h:mm:ss a") f.dateFormat = "dd-MM-yyyy" XCTAssertEqual(f.string(from: testDate), "11-03-2016") } func test_setLocalizedDateFormatFromTemplate() { let locale = Locale(identifier: DEFAULT_LOCALE) let template = "EEEE MMMM d y hhmmss a zzzz" let f = DateFormatter() f.locale = locale f.setLocalizedDateFormatFromTemplate(template) let dateFormat = DateFormatter.dateFormat(fromTemplate: template, options: 0, locale: locale) XCTAssertEqual(f.dateFormat, dateFormat) } func test_dateFormatString() { let f = DateFormatter() f.timeZone = TimeZone(abbreviation: DEFAULT_TIMEZONE) //.full cases have been commented out as they're not working correctly on Linux let formats: [String: (DateFormatter.Style, DateFormatter.Style)] = [ "": (.none, .none), "h:mm a": (.none, .short), "h:mm:ss a": (.none, .medium), "h:mm:ss a z": (.none, .long), // "h:mm:ss a zzzz": (.none, .full), "M/d/yy": (.short, .none), "M/d/yy, h:mm a": (.short, .short), "M/d/yy, h:mm:ss a": (.short, .medium), "M/d/yy, h:mm:ss a z": (.short, .long), // "M/d/yy, h:mm:ss a zzzz": (.short, .full), "MMM d, y": (.medium, .none), //These tests currently fail, there seems to be a difference in behavior in the CoreFoundation methods called to construct the format strings. // "MMM d, y 'at' h:mm a": (.medium, .short), // "MMM d, y 'at' h:mm:ss a": (.medium, .medium), // "MMM d, y 'at' h:mm:ss a z": (.medium, .long), // "MMM d, y 'at' h:mm:ss a zzzz": (.medium, .full), "MMMM d, y": (.long, .none), "MMMM d, y 'at' h:mm a": (.long, .short), "MMMM d, y 'at' h:mm:ss a": (.long, .medium), "MMMM d, y 'at' h:mm:ss a z": (.long, .long), // "MMMM d, y 'at' h:mm:ss a zzzz": (.long, .full), // "EEEE, MMMM d, y": (.full, .none), // "EEEE, MMMM d, y 'at' h:mm a": (.full, .short), // "EEEE, MMMM d, y 'at' h:mm:ss a": (.full, .medium), // "EEEE, MMMM d, y 'at' h:mm:ss a z": (.full, .long), // "EEEE, MMMM d, y 'at' h:mm:ss a zzzz": (.full, .full), ] for (dateFormat, styles) in formats { f.dateStyle = styles.0 f.timeStyle = styles.1 XCTAssertEqual(f.dateFormat, dateFormat) } } }
apache-2.0
4f5930545e794ada3299fbe7c455eaa2
54.552941
178
0.583122
4.002543
false
true
false
false
lenssss/whereAmI
Whereami/Controller/Chat/ChatMainViewSearchResultViewController.swift
1
4191
// // ChatMainViewSearchResultViewController.swift // Whereami // // Created by WuQifei on 16/2/25. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit typealias NewConversation = (conversion:AVIMConversation,hostUser:ChattingUserModel,guestUser:ChattingUserModel)->() class ChatMainViewSearchResultViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchResultsUpdating { var tableView:UITableView? = nil var searchText:String? = nil var conversations:[ConversationModel]? = nil var results:[ConversationModel]? = nil var newConversationHasDone:NewConversation? = nil override func viewDidLoad() { super.viewDidLoad() self.setConfig() self.tableView = UITableView() self.view.addSubview(self.tableView!) self.tableView?.separatorStyle = .None self.tableView?.delegate = self self.tableView?.dataSource = self self.tableView?.registerClass(ChatItemTableViewCell.self, forCellReuseIdentifier: "ChatItemTableViewCell") self.tableView?.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)) // Do any additional setup after loading the view. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if results != nil { return results!.count } return 0 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 70.0; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:ChatItemTableViewCell = tableView.dequeueReusableCellWithIdentifier("ChatItemTableViewCell", forIndexPath: indexPath) as! ChatItemTableViewCell cell.selectionStyle = .None let conversationModel = results![indexPath.row] let avatarUrl = conversationModel.guestModel?.headPortrait != nil ? conversationModel.guestModel?.headPortrait : "" cell.avatar?.kf_setImageWithURL(NSURL(string:avatarUrl!)!, placeholderImage: UIImage(named: "avator.png"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) cell.chatName?.text = conversationModel.guestModel?.nickname cell.lastMsg?.text = conversationModel.lattestMsg let date = (conversationModel.lastTime?.timeIntervalSince1970)!*1000 cell.lastMsgTime?.text = TimeManager.sharedInstance.getDateStringFromString("\(date)") cell.msgSum?.hidden = true if conversationModel.unreadCount != 0{ cell.msgSum?.hidden = false cell.msgSum?.text = "\(conversationModel.unreadCount! as Int)" } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let conversationModel = results![indexPath.row] CoreDataConversationManager.sharedInstance.clearUnreadCountByConversationId((conversationModel.avConversation?.conversationId)!) self.dismissViewControllerAnimated(false) { self.newConversationHasDone!(conversion: conversationModel.avConversation!, hostUser: conversationModel.hostModel!, guestUser: conversationModel.guestModel!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateSearchResultsForSearchController(searchController: UISearchController) { searchController.searchBar.enablesReturnKeyAutomatically = true let searchText = searchController.searchBar.text if searchText != "" && conversations != nil && conversations?.count != 0 { let filterArray = conversations?.filter({($0.guestModel?.nickname?.contains(searchText!))!}) guard filterArray != nil else { results = [ConversationModel]() self.tableView?.reloadData() return } results = filterArray self.tableView?.reloadData() } } }
mit
03c27b5283edb7af6f36710b292223c7
41.734694
176
0.689828
5.467363
false
false
false
false