hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
487ddf0514913f1ab7ace7024087125e8e4ae725
3,145
// // IFUploadPhotoService.swift // AnimationDemo // // Created by lieon on 2020/12/16. // Copyright © 2020 lieon. All rights reserved. // import Foundation import Photos class IFUploadPhotoService { fileprivate lazy var photos: [PHAsset] = [] fileprivate var currentTokenStr: String = "" fileprivate lazy var queue = OperationQueue() fileprivate lazy var group = DispatchGroup() fileprivate lazy var isStop = false var totoal: Int { return photos.count } var uploadedCount: Int = 0 func startUpload() { if currentTokenStr.isEmpty { getQiniuToken("name", callback: {[weak self] token in guard let weakSelf = self, let token = token else { return } weakSelf.currentTokenStr = token }) } else { } } func stopUpload() { isStop = true group.leave() group.notify(queue: .main) { } } } extension IFUploadPhotoService { func upload() { isStop = false let queue = DispatchQueue(label: "upload", qos: .default, attributes: .concurrent) queue.async { let semaphore = DispatchSemaphore(value: 3) let lock = NSLock() self.group.enter() for photo in 0 ..< 20 { semaphore.wait() self.group.enter() self.uploadSingle(PHAsset(), callback: { progress, url in if let url = url { lock.lock() self.uploadedCount += 1 print(self.uploadedCount) lock.unlock() } else { } self.group.leave() semaphore.signal() }) } self.group.notify(queue: .main) { } } } fileprivate func uploadSingle(_ asset: PHAsset, callback: ((_ progress: Float, _ url: String?) -> Void)?) { if isStop { return } DispatchQueue.main.asyncAfter(deadline: .now() + 1) { callback?(1.0, "adsf") } // loadImage(asset, size: CGSize(width: 100, height: 100), complection: {[weak self]pic in // guard let weakSelf = self else { // return // } // guard let data = pic?.jpegData(compressionQuality: 0.8) else { // return // } // weakSelf.uploadQiniu(asset.burstIdentifier ?? "", fileData: data, callback: callback) // }) } /// 上传资源 fileprivate func uploadQiniu(_ fileName: String, fileData: Data, callback: ((_ progress: Float, _ url: String?) -> Void)) { } /// 获取七牛token fileprivate func getQiniuToken(_ fileName: String, callback: ((_ token: String?) -> Void)) { } /// 获取图片 fileprivate func loadImage(_ asset: PHAsset, size: CGSize, complection: ((UIImage?)-> Void)) { } }
28.853211
126
0.498887
79c80816014bea5dc0a0f6069523d6523cea346a
7,207
// // DetailViewController.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Alamofire import UIKit class DetailViewController: UITableViewController { enum Sections: Int { case headers, body } var request: Request? { didSet { oldValue?.cancel() title = request?.description request?.onURLRequestCreation { [weak self] _ in self?.title = self?.request?.description } refreshControl?.endRefreshing() headers.removeAll() body = nil elapsedTime = nil } } var headers: [String: String] = [:] var body: String? var elapsedTime: TimeInterval? var segueIdentifier: String? static let numberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal return formatter }() // MARK: View Lifecycle override func awakeFromNib() { super.awakeFromNib() refreshControl?.addTarget(self, action: #selector(DetailViewController.refresh), for: .valueChanged) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) refresh() } // MARK: IBActions @IBAction func refresh() { guard let request = request else { return } refreshControl?.beginRefreshing() let start = CACurrentMediaTime() let requestComplete: (HTTPURLResponse?, Result<String, AFError>) -> Void = { response, result in let end = CACurrentMediaTime() self.elapsedTime = end - start if let response = response { for (field, value) in response.allHeaderFields { self.headers["\(field)"] = "\(value)" } } if let segueIdentifier = self.segueIdentifier { switch segueIdentifier { case "GET", "POST", "PUT", "DELETE": if case let .success(value) = result { self.body = value } case "DOWNLOAD": self.body = self.downloadedBodyString() default: break } } self.tableView.reloadData() self.refreshControl?.endRefreshing() } if let request = request as? DataRequest { request.responseString { response in requestComplete(response.response, response.result) } } else if let request = request as? DownloadRequest { request.responseString { response in requestComplete(response.response, response.result) } } } private func downloadedBodyString() -> String { let fileManager = FileManager.default let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] do { let contents = try fileManager.contentsOfDirectory(at: cachesDirectory, includingPropertiesForKeys: nil, options: .skipsHiddenFiles) if let fileURL = contents.first, let data = try? Data(contentsOf: fileURL) { let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) let prettyData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) if let prettyString = String(data: prettyData, encoding: String.Encoding.utf8) { try fileManager.removeItem(at: fileURL) return prettyString } } } catch { // No-op } return "" } } // MARK: - UITableViewDataSource extension DetailViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch Sections(rawValue: section)! { case .headers: return headers.count case .body: return body == nil ? 0 : 1 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch Sections(rawValue: indexPath.section)! { case .headers: let cell = tableView.dequeueReusableCell(withIdentifier: "Header")! let field = headers.keys.sorted(by: <)[indexPath.row] let value = headers[field] cell.textLabel?.text = field cell.detailTextLabel?.text = value return cell case .body: let cell = tableView.dequeueReusableCell(withIdentifier: "Body")! cell.textLabel?.text = body return cell } } } // MARK: - UITableViewDelegate extension DetailViewController { override func numberOfSections(in tableView: UITableView) -> Int { 2 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if self.tableView(tableView, numberOfRowsInSection: section) == 0 { return "" } switch Sections(rawValue: section)! { case .headers: return "Headers" case .body: return "Body" } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch Sections(rawValue: indexPath.section)! { case .body: return 300 default: return tableView.rowHeight } } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { if Sections(rawValue: section) == .body, let elapsedTime = elapsedTime { let elapsedTimeText = DetailViewController.numberFormatter.string(from: elapsedTime as NSNumber) ?? "???" return "Elapsed Time: \(elapsedTimeText) sec" } return "" } }
33.52093
117
0.601637
f4a9939f8ac54c6cf14d4403e6f0f0e80207e417
2,282
// 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 // extension MassFormatter { public enum Unit : Int { case gram case kilogram case ounce case pound case stone } } public class MassFormatter : Formatter { public required init?(coder: NSCoder) { NSUnimplemented() } /*@NSCopying*/ public var numberFormatter: NumberFormatter! // default is NSNumberFormatter with NSNumberFormatterDecimalStyle public var unitStyle: UnitStyle // default is NSFormattingUnitStyleMedium public var isForPersonMassUse: Bool // default is NO; if it is set to YES, the number argument for -stringFromKilograms: and -unitStringFromKilograms: is considered as a person’s mass // Format a combination of a number and an unit to a localized string. public func string(fromValue value: Double, unit: Unit) -> String { NSUnimplemented() } // Format a number in kilograms to a localized string with the locale-appropriate unit and an appropriate scale (e.g. 1.2kg = 2.64lb in the US locale). public func string(fromKilograms numberInKilograms: Double) -> String { NSUnimplemented() } // Return a localized string of the given unit, and if the unit is singular or plural is based on the given number. public func unitString(fromValue value: Double, unit: Unit) -> String { NSUnimplemented() } // Return the locale-appropriate unit, the same unit used by -stringFromKilograms:. public func unitString(fromKilograms numberInKilograms: Double, usedUnit unitp: UnsafeMutablePointer<Unit>?) -> String { NSUnimplemented() } /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future public override func objectValue(_ string: String) throws -> AnyObject? { return nil } }
46.571429
187
0.719106
1ca8288758e33bcb0ae28e9af49c08b944e0facc
14,398
// // UserTableViewController.swift // Harvey // // Created by Sean Hart on 9/9/17. // Copyright © 2017 TangoJ Labs, LLC. All rights reserved. // import UIKit class UserTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, UIGestureRecognizerDelegate, AWSRequestDelegate { // Save device settings to adjust view if needed var screenSize: CGRect! var statusBarHeight: CGFloat! var navBarHeight: CGFloat! var viewFrameY: CGFloat! var vcHeight: CGFloat! var vcOffsetY: CGFloat! // The views to hold major components of the view controller var statusBarView: UIView! var viewContainer: UIView! var userTableView: UITableView! lazy var refreshControl: UIRefreshControl = UIRefreshControl() var tableGestureRecognizer: UITapGestureRecognizer! var users = Constants.Data.allUsers override func viewDidLoad() { super.viewDidLoad() prepVcLayout() self.automaticallyAdjustsScrollViewInsets = false // Add the view container to hold all other views (allows for shadows on all subviews) viewContainer = UIView(frame: CGRect(x: 0, y: vcOffsetY, width: self.view.bounds.width, height: vcHeight)) viewContainer.backgroundColor = Constants.Colors.standardBackgroundGrayUltraLight self.view.addSubview(viewContainer) // A tableview will hold all users userTableView = UITableView(frame: CGRect(x: 0, y: 0, width: viewContainer.frame.width, height: viewContainer.frame.height)) userTableView.dataSource = self userTableView.delegate = self userTableView.register(SpotTableViewCell.self, forCellReuseIdentifier: Constants.Strings.userTableViewCellReuseIdentifier) userTableView.separatorStyle = .none userTableView.backgroundColor = Constants.Colors.standardBackground userTableView.isScrollEnabled = true userTableView.bounces = true userTableView.alwaysBounceVertical = true userTableView.allowsSelection = false userTableView.showsVerticalScrollIndicator = false // userTableView.isUserInteractionEnabled = true // userTableView.allowsSelection = true userTableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) viewContainer.addSubview(userTableView) tableGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UserTableViewController.tableGesture(_:))) tableGestureRecognizer.delegate = self userTableView.addGestureRecognizer(tableGestureRecognizer) // Create a refresh control for the CollectionView and add a subview to move the refresh control where needed refreshControl = UIRefreshControl() refreshControl.attributedTitle = NSAttributedString(string: "") refreshControl.addTarget(self, action: #selector(UserTableViewController.refreshDataManually), for: UIControlEvents.valueChanged) userTableView.addSubview(refreshControl) userTableView.contentOffset = CGPoint(x: 0, y: -self.refreshControl.frame.size.height) NotificationCenter.default.addObserver(self, selector: #selector(MapViewController.statusBarHeightChange(_:)), name: Notification.Name("UIApplicationWillChangeStatusBarFrameNotification"), object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: LAYOUT METHODS func statusBarHeightChange(_ notification: Notification) { prepVcLayout() statusBarView.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: statusBarHeight) viewContainer.frame = CGRect(x: 0, y: vcOffsetY, width: screenSize.width, height: vcHeight) userTableView.frame = CGRect(x: 0, y: 0, width: viewContainer.frame.width, height: viewContainer.frame.height) } func prepVcLayout() { // Record the status bar settings to adjust the view if needed UIApplication.shared.isStatusBarHidden = false UIApplication.shared.statusBarStyle = Constants.Settings.statusBarStyle statusBarHeight = UIApplication.shared.statusBarFrame.size.height // Navigation Bar settings navBarHeight = 44.0 if let navController = self.navigationController { navController.isNavigationBarHidden = false navBarHeight = navController.navigationBar.frame.height navController.navigationBar.barTintColor = Constants.Colors.colorOrangeOpaque } viewFrameY = self.view.frame.minY screenSize = UIScreen.main.bounds vcHeight = screenSize.height - statusBarHeight - navBarHeight vcOffsetY = statusBarHeight + navBarHeight if statusBarHeight == 40 { vcHeight = screenSize.height - 76 vcOffsetY = 56 } } // MARK: TABLE VIEW DATA SOURCE func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Constants.Data.allUsers.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return Constants.Dim.userTableCellHeight } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { print("UTVC - CREATING CELL: \(indexPath.row)") let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Strings.userTableViewCellReuseIdentifier, for: indexPath) as! UserTableViewCell // Store the user for this cell for reference let cellUser = Constants.Data.allUsers[indexPath.row] // Remove all subviews for subview in cell.subviews { subview.removeFromSuperview() } // Start animating the activity indicator cell.activityIndicator.startAnimating() // Assign the user image to the image if available - if not, assign the thumbnail until the real image downloads if let image = cellUser.image { print("STVC - ADDING IMAGE FOR USER: \(cellUser.userID)") cell.userImageView.image = image // Stop animating the activity indicator cell.activityIndicator.stopAnimating() } else if let thumbnail = cellUser.thumbnail { print("STVC - ADDING THUMBNAIL FOR USER: \(cellUser.userID)") cell.userImageView.image = thumbnail // Stop animating the activity indicator cell.activityIndicator.stopAnimating() } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("UTVC - SELECTED CELL: \(indexPath.row)") } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { } func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) { } func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) { } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let userSelect = users[indexPath.row] // Determine which block setting and title should be used var blockTitle = "BLOCK" var alertTitle = "BLOCK USER" var alertMessage = "Are you sure you want to block \(String(describing: userSelect.name))?" var connectionUpdateValue = "block" if userSelect.connection == "block" { blockTitle = "Unblock" alertTitle = "Unblock User" alertMessage = "Are you sure you want to unblock \(String(describing: userSelect.name))?" connectionUpdateValue = "na" } let block = UITableViewRowAction(style: .normal, title: blockTitle) { action, index in print("UTVC-ACTION-BLOCK") // Ensure the user wants to flag the content "Are you sure you want to report this image as objectionable or inaccurate?" let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.alert) let yesAction = UIAlertAction(title: "Yes", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in // change the user social status, refresh the table, and send the block user status change put request if blockTitle == "BLOCK" { Constants.Data.allUserBlockList.append(userSelect.userID) for user in Constants.Data.allUsers { if user.userID == userSelect.userID { user.connection = "block" } } } else { for (bIndex, blockedUserID) in Constants.Data.allUserBlockList.enumerated() { if blockedUserID == userSelect.userID { Constants.Data.allUserBlockList.remove(at: bIndex) } } for user in Constants.Data.allUsers { if user.userID == userSelect.userID { user.connection = "na" } } } self.reloadDataManually() // Upload the change AWSPrepRequest(requestToCall: AWSUserConnectionPut(targetUserID: userSelect.userID, connection: connectionUpdateValue), delegate: self as AWSRequestDelegate).prepRequest() } let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in print("UTVC - BLOCK / UNBLOCK CANCELLED") } alertController.addAction(cancelAction) alertController.addAction(yesAction) self.present(alertController, animated: true, completion: nil) } block.backgroundColor = Constants.Colors.colorGrayDark return [block] } // MARK: SCROLL VIEW DELEGATE METHODS func scrollViewDidScroll(_ scrollView: UIScrollView) { } // MARK: GESTURE RECOGNIZERS func tableGesture(_ gesture: UITapGestureRecognizer) { // if gesture.state == UIGestureRecognizerState.ended // { // let tapLocation = gesture.location(in: self.userTableView) // print("UTVC - TAP LOCATION: \(tapLocation)") // if let tappedIndexPath = userTableView.indexPathForRow(at: tapLocation) // { // print("UTVC - TAPPED INDEX PATH: \(tappedIndexPath)") // if let tappedCell = self.userTableView.cellForRow(at: tappedIndexPath) as? UserTableViewCell // { // let cellTapLocation = gesture.location(in: tappedCell) // if tappedCell.userImageView.frame.contains(cellTapLocation) // { // // } // } // } // } } // MARK: CUSTOM METHODS // Dismiss the latest View Controller presented from this VC // This version is used when the top VC is popped from a Nav Bar button func popViewController(_ sender: UIBarButtonItem) { self.navigationController!.popViewController(animated: true) } func popViewController() { self.navigationController!.popViewController(animated: true) } func refreshTable() { DispatchQueue.main.async(execute: { if self.userTableView != nil { // Reload the TableView self.userTableView.performSelector(onMainThread: #selector(UITableView.reloadData), with: nil, waitUntilDone: true) } }) } // Reload the local list from the global list func reloadDataManually() { users = Constants.Data.allUsers refreshTable() } // Request fresh data from the server func refreshDataManually() { refreshTable() } // MARK: AWS DELEGATE METHODS func showLoginScreen() { print("UTVC - SHOW LOGIN SCREEN") // Load the LoginVC let loginVC = LoginViewController() self.navigationController!.pushViewController(loginVC, animated: true) } func processAwsReturn(_ objectType: AWSRequestObject, success: Bool) { DispatchQueue.main.async(execute: { // Process the return data based on the method used switch objectType { case _ as AWSSpotContentStatusUpdate: if success { print("UTVC - AWSSpotContentStatusUpdate - SUCCESS") } else { // Show the error message let alertController = UtilityFunctions().createAlertOkView("Network Error", message: "I'm sorry, you appear to be having network issues. Please try again.") self.present(alertController, animated: true, completion: nil) } default: print("STVC-DEFAULT: THERE WAS AN ISSUE WITH THE DATA RETURNED FROM AWS") // Show the error message let alertController = UtilityFunctions().createAlertOkView("Network Error", message: "I'm sorry, you appear to be having network issues. Please try again.") self.present(alertController, animated: true, completion: nil) } }) } }
38.704301
209
0.610988
75b3ae459a1af1dc9ebdb55a341e2b3b5a529c9f
3,947
// // ViewController.swift // AR Portal // // Created by Noel Konagai on 12/13/17. // Copyright © 2017 Noel Konagai. All rights reserved. // import UIKit import ARKit class ViewController: UIViewController, ARSCNViewDelegate { @IBOutlet weak var planeDetected: UILabel! @IBOutlet weak var sceneView: ARSCNView! let configuration = ARWorldTrackingConfiguration() override func viewDidLoad() { super.viewDidLoad() self.sceneView.debugOptions = [ARSCNDebugOptions.showWorldOrigin, ARSCNDebugOptions.showFeaturePoints] self.configuration.planeDetection = .horizontal self.sceneView.session.run(configuration) self.sceneView.delegate = self let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap)) self.sceneView.addGestureRecognizer(tapGestureRecognizer) // Do any additional setup after loading the view, typically from a nib. } @objc func handleTap(sender: UITapGestureRecognizer) { guard let sceneView = sender.view as? ARSCNView else {return} let touchLocation = sender.location(in: sceneView) let hitTestResult = sceneView.hitTest(touchLocation, types: .existingPlaneUsingExtent) if !hitTestResult.isEmpty { self.addPortal(hitTestResult: hitTestResult.first!) } else { //// } } func addPortal(hitTestResult: ARHitTestResult) { let portalScene = SCNScene(named: "Portal.scnassets/Portal.scn") let portalNode = portalScene!.rootNode.childNode(withName: "Portal", recursively: false)! let transform = hitTestResult.worldTransform let planeXposition = transform.columns.3.x let planeYposition = transform.columns.3.y let planeZposition = transform.columns.3.z portalNode.position = SCNVector3(planeXposition, planeYposition, planeZposition) self.sceneView.scene.rootNode.addChildNode(portalNode) self.addPlane(nodeName: "roof", portalNode: portalNode, imageName: "top") self.addPlane(nodeName: "floor", portalNode: portalNode, imageName: "bottom") self.addWalls(nodeName: "backWall", portalNode: portalNode, imageName: "back") self.addWalls(nodeName: "sideWallA", portalNode: portalNode, imageName: "sideA") self.addWalls(nodeName: "sideWallB", portalNode: portalNode, imageName: "sideB") self.addWalls(nodeName: "sideDoorA", portalNode: portalNode, imageName: "sideDoorA") self.addWalls(nodeName: "sideDoorB", portalNode: portalNode, imageName: "sideDoorB") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { guard anchor is ARPlaneAnchor else {return} DispatchQueue.main.async { self.planeDetected.isHidden = false } DispatchQueue.main.asyncAfter(deadline: .now() + 3) { self.planeDetected.isHidden = true } } func addWalls(nodeName: String, portalNode: SCNNode, imageName: String) { let child = portalNode.childNode(withName: nodeName, recursively: true) child?.geometry?.firstMaterial?.diffuse.contents = UIImage(named: "Portal.scnassets/\(imageName).png") child?.renderingOrder = 200 if let mask = child?.childNode(withName: "mask", recursively: false) { mask.geometry?.firstMaterial?.transparency = 0.000001 } } func addPlane(nodeName: String, portalNode: SCNNode, imageName: String) { let child = portalNode.childNode(withName: nodeName, recursively: true) child?.geometry?.firstMaterial?.diffuse.contents = UIImage(named: "Portal.scnassets/\(imageName).png") child?.renderingOrder = 200 } }
43.373626
110
0.684317
71c9162add66a7d0e134b8c8383325768afdc9cf
643
// // JewelsAndStones.swift // LeetCodeDemo // // Created by Apple on 2021/1/28. // import Foundation /* 宝石和石头 给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。 J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/jewels-and-stones 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ class JewelsAndStones { func numJewelsInStones(_ jewels: String, _ stones: String) -> Int { let jSet = Set(jewels) var cnt = 0 for c in stones { if jSet.contains(c) { cnt += 1 } } return cnt } }
19.484848
75
0.625194
5d1cb07501dd7500fc6cc430203fc98e0beda94c
111,140
// // Copyright 2018 Esri. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import QuartzCore import ArcGIS // MARK: - Time Slider Control public class TimeSlider: UIControl { // MARK: - Enumerations /** Controls how labels on the slider are displayed. */ public enum LabelMode { case none case thumbs case ticks } /** Playback direction when time is being animated. */ public enum PlaybackDirection { case forward case backward } /** The looping behavior of the slider when time is being animated. */ public enum LoopMode { case none case `repeat`(PlaybackDirection) case reverse(PlaybackDirection) var playbackDirection: PlaybackDirection? { switch self { case .none: return nil case .`repeat`(let direction), .reverse(let direction): return direction } } } /** Different color themes of the slider. */ public enum Theme { case black case blue case oceanBlue } /** Different date styles of the slider. */ public enum DateStyle { case dayShortMonthYear /*!< Date with d MMM y */ case longDate /*!< Date with EEEE, MMMM d, y */ case longMonthDayYear /*!< Date with MMMM d y */ case longMonthYear /*!< Date with MMMM y */ case shortDate /*!< Date with M/d/y */ case shortDateLongTime /*!< Date with M/d/y h:mm:ss a */ case shortDateLongTime24 /*!< Date with M/d/y H:mm:ss */ case shortDateShortTime /*!< Date with M/d/y h:mm a*/ case shortDateShortTime24 /*!< Date with M/d/y H:mm */ case shortMonthYear /*!< Date with MMM y */ case year /*!< Date with y */ case unknown } // MARK: - Public Properties // MARK: Current Extent Properties /** The current time window or time instant of the slider */ public var currentExtent: AGSTimeExtent? { didSet { if let startTime = currentExtent?.startTime, let endTime = currentExtent?.endTime { // // Update current extent start and end time updateCurrentExtentStartTime(startTime) updateCurrentExtentEndTime(endTime) // Update flag only if it's not an internal update if !internalUpdate { // // Range is enabled only if both times are not same. isRangeEnabled = (startTime != endTime) } } // This means there is only one thumb needs to be displayed and current extent start and end times are same. else if let startTime = currentExtent?.startTime, currentExtent?.endTime == nil { // // Only one thumb should be displayed // so set range to false isRangeEnabled = false // Update current extent start time updateCurrentExtentStartTime(startTime) // Start and end time must be same. currentExtentEndTime = currentExtentStartTime } // This means there is only one thumb needs to be displayed and current extent start and end times are same. else if let endTime = currentExtent?.endTime, currentExtent?.startTime == nil { // // Only one thumb should be displayed // so set range to false isRangeEnabled = false // Update current extent start time updateCurrentExtentStartTime(endTime) // Start and end time must be same. currentExtentEndTime = currentExtentStartTime } // Set start and end time to nil if current extent is nil // or it's start and end times are nil else if currentExtent == nil || (currentExtent?.startTime == nil && currentExtent?.endTime == nil) { currentExtentStartTime = nil currentExtentEndTime = nil } // Refresh the view setNeedsLayout() } } /** The color used to tint the current extent of the slider. */ public var currentExtentFillColor = UIColor.black { didSet { trackLayer.setNeedsDisplay() } } /** The current extent label color. */ public var currentExtentLabelColor = UIColor.darkText { didSet { currentExtentStartTimeLabel.foregroundColor = currentExtentLabelColor.cgColor currentExtentEndTimeLabel.foregroundColor = currentExtentLabelColor.cgColor } } /** The current extent label font. */ public var currentExtentLabelFont = UIFont.systemFont(ofSize: 12.0) { didSet { currentExtentStartTimeLabel.font = currentExtentLabelFont as CFTypeRef currentExtentStartTimeLabel.fontSize = currentExtentLabelFont.pointSize currentExtentEndTimeLabel.font = currentExtentLabelFont as CFTypeRef currentExtentEndTimeLabel.fontSize = currentExtentLabelFont.pointSize } } /** The date style to use for the labels showing the start and end of the current time extent. */ public var currentExtentLabelDateStyle: DateStyle = .shortDateLongTime { didSet { updateCurrentExtentLabelFrames() } } /** A Boolean value that indicates whether the start time of the currentExtent can be manipulated through user interaction or moves when time is being animated. */ public var isStartTimePinned = false { didSet { lowerThumbLayer.isPinned = isStartTimePinned } } /** A Boolean value that indicates whether the end time of the currentExtent can be manipulated through user interaction or moves when time is being animated. */ public var isEndTimePinned = false { didSet { if isRangeEnabled { upperThumbLayer.isPinned = isEndTimePinned } else { isStartTimePinned = isEndTimePinned lowerThumbLayer.isPinned = isEndTimePinned upperThumbLayer.isPinned = isEndTimePinned } } } // MARK: Full Extent Properties /** The full extent time window on the slider. */ public var fullExtent: AGSTimeExtent? { didSet { // // Set current extent if it's nil. if currentExtent == nil, let fullExtent = fullExtent { currentExtent = fullExtent } else if fullExtent == nil { timeSteps?.removeAll() tickMarks.removeAll() removeTickMarkLabels() currentExtent = fullExtent } else { // // It is possible that the current extent times are outside of the range of // new full extent times. Adjust and sanp them to the tick marks. if let startTime = currentExtentStartTime, let endTime = currentExtentEndTime { updateCurrentExtentStartTime(startTime) updateCurrentExtentEndTime(endTime) } } setNeedsLayout() } } /** The color used to tint the full extent border of the slider. */ public var fullExtentBorderColor = UIColor.black { didSet { trackLayer.setNeedsDisplay() } } /** The border width of the full extent of the slider. */ public var fullExtentBorderWidth: CGFloat = 1.0 { didSet { trackLayer.setNeedsDisplay() } } /** The color used to tint the full extent of the slider. */ public var fullExtentFillColor = UIColor.white { didSet { trackLayer.setNeedsDisplay() } } /** The full extent label color. */ public var fullExtentLabelColor = UIColor.darkText { didSet { fullExtentStartTimeLabel.foregroundColor = fullExtentLabelColor.cgColor fullExtentEndTimeLabel.foregroundColor = fullExtentLabelColor.cgColor } } /** The full extent label font. */ public var fullExtentLabelFont = UIFont.systemFont(ofSize: 12.0) { didSet { fullExtentStartTimeLabel.font = fullExtentLabelFont as CFTypeRef fullExtentStartTimeLabel.fontSize = fullExtentLabelFont.pointSize fullExtentEndTimeLabel.font = fullExtentLabelFont as CFTypeRef fullExtentEndTimeLabel.fontSize = fullExtentLabelFont.pointSize } } /** A Boolean value that indicates whether the full extent labels are visible or not. Default if True. */ public var fullExtentLabelsVisible = true { didSet { fullExtentStartTimeLabel.isHidden = !fullExtentLabelsVisible fullExtentEndTimeLabel.isHidden = !fullExtentLabelsVisible if fullExtentLabelsVisible { updateFullExtentLabelFrames() } } } /** The date style to use for the labels showing the start and end of the slider's entire time extent (full extent). */ public var fullExtentLabelDateStyle: DateStyle = .shortDateLongTime { didSet { updateFullExtentLabelFrames() } } // MARK: Time Step Properties /** The time steps calculated along the time slider. These are calculated based on the full extent and time step interval. */ public private(set) var timeSteps: [Date]? /** The interval at which users can move forward and back through the slider's full extent. */ public var timeStepInterval: AGSTimeValue? { didSet { calculateTimeSteps() setNeedsLayout() } } /** The date style used for the labels showing the slider's time step intervals (tick labels). */ public var timeStepIntervalLabelDateStyle: DateStyle = .shortDateLongTime { didSet { positionTickMarks() } } /** The time interval or tick mark label color. */ public var timeStepIntervalLabelColor = UIColor.darkText { didSet { tickMarkLabels.forEach { (tickMarkLabel) in tickMarkLabel.foregroundColor = timeStepIntervalLabelColor.cgColor } } } /** The current extent label font. */ public var timeStepIntervalLabelFont = UIFont.systemFont(ofSize: 12.0) { didSet { tickMarkLabels.forEach { (tickMarkLabel) in tickMarkLabel.font = timeStepIntervalLabelFont as CFTypeRef tickMarkLabel.fontSize = timeStepIntervalLabelFont.pointSize } } } /** The color used to tint the full extent of the slider. */ public var timeStepIntervalTickColor = UIColor.black { didSet { tickMarkLayer.setNeedsDisplay() } } /** Controls how labels on the slider are displayed. The default is thumbs. */ public var labelMode: LabelMode = .thumbs { didSet { switch labelMode { case .none, .ticks: // // Hide current extent labels currentExtentStartTimeLabel.isHidden = true currentExtentEndTimeLabel.isHidden = true case .thumbs: // // Show current extent labels // only if slider is visible. if isSliderVisible { currentExtentStartTimeLabel.isHidden = false currentExtentEndTimeLabel.isHidden = isRangeEnabled ? false : true updateCurrentExtentLabelFrames() } } // All above cases require to remove // existing tick marks and reposition // them (none will not add it) removeTickMarkLabels() positionTickMarks() } } // MARK: Thumb Properties /** The color used to tint the thumbs. */ public var thumbFillColor = UIColor.white { didSet { lowerThumbLayer.setNeedsDisplay() upperThumbLayer.setNeedsDisplay() } } /** The color used to tint the thumb's border. */ public var thumbBorderColor = UIColor.black { didSet { lowerThumbLayer.setNeedsDisplay() upperThumbLayer.setNeedsDisplay() } } /** The border width of the thumb. */ public var thumbBorderWidth: CGFloat = 1.0 { didSet { lowerThumbLayer.setNeedsDisplay() upperThumbLayer.setNeedsDisplay() } } /** The size of the thumb. */ public var thumbSize = CGSize(width: 25.0, height: 25.0) { didSet { // // More than 50 width and height // is too big for the iOS control. // So, restrict it. if thumbSize.width > maximumThumbSize { thumbSize.width = maximumThumbSize } if thumbSize.height > maximumThumbSize { thumbSize.height = maximumThumbSize } // Set side padding of the track layer for the new thumb size // so thumb has enough space to go all the way to end. trackLayerSidePadding = (thumbSize.width / 2.0) + labelSidePadding // Refresh the view. setNeedsLayout() } } /** The corner radius of the thumb. */ public var thumbCornerRadius = 1.0 { didSet { lowerThumbLayer.setNeedsDisplay() upperThumbLayer.setNeedsDisplay() } } // MARK: Playback Properties /** A Boolean value indicating whether playback buttons are visible or not. Default is true. */ public var playbackButtonsVisible = true { didSet { playPauseButton.isHidden = !playbackButtonsVisible forwardButton.isHidden = !playbackButtonsVisible backButton.isHidden = !playbackButtonsVisible invalidateIntrinsicContentSize() setNeedsLayout() } } /** The color used to tint the thumb's border. */ public var playbackButtonsFillColor = UIColor.black { didSet { // // Set new button images created with new fill color playPauseButton.tintColor = playbackButtonsFillColor forwardButton.tintColor = playbackButtonsFillColor backButton.tintColor = playbackButtonsFillColor } } /** The looping behavior of the slider when time is being animated. */ public var playbackLoopMode: LoopMode = .repeat(.forward) /** The amount of time during playback that will elapse before the slider advances to the next time step. If geoView is available then playback will wait until geoView's drawing (drawStatus) is completed before advances to the next time step. */ public var playbackInterval: TimeInterval = 1 /** A Boolean value indicating whether playback is currently running. */ public var isPlaying = false { didSet { if isPlaying { // // Set the button state playPauseButton.isSelected = true // Invalidate timer, in case this button is tapped multiple times timer?.invalidate() // Start the timer with specified playback interval timer = Timer.scheduledTimer(timeInterval: playbackInterval, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true) } else { // // Set the button state playPauseButton.isSelected = false // Invalidate and nil out timer. timer?.invalidate() timer = nil } } } // MARK: Other Properties /** The geoView used to initialize the time slider properties. */ public private(set) var geoView: AGSGeoView? /** A Boolean value indicating whether changes (change in layers and time extent) in geoView should be observed by the time slider. */ public var observeGeoView = false { didSet { if observeGeoView { addObservers() } else { removeObservers() } } } /** Time zone of the slider. */ public var timeZone = TimeZone.current { didSet { updateCurrentExtentLabelFrames() updateFullExtentLabelFrames() positionTickMarks() } } /** A Boolean value indicating whether slider is visible or not. Default is true. */ public var isSliderVisible = true { didSet { lowerThumbLayer.isHidden = !isSliderVisible upperThumbLayer.isHidden = !isSliderVisible trackLayer.isHidden = !isSliderVisible tickMarkLayer.isHidden = !isSliderVisible fullExtentStartTimeLabel.isHidden = !isSliderVisible fullExtentEndTimeLabel.isHidden = !isSliderVisible currentExtentStartTimeLabel.isHidden = !isSliderVisible currentExtentEndTimeLabel.isHidden = !isSliderVisible tickMarkLabels.forEach { (tickMarkLabel) in tickMarkLabel.isHidden = !isSliderVisible } invalidateIntrinsicContentSize() setNeedsLayout() } } /** The color used to tint the layer extent of the slider. */ public var layerExtentFillColor = UIColor.gray { didSet { trackLayer.setNeedsDisplay() } } /** The height of the slider track. */ public var trackHeight: CGFloat = 6.0 { didSet { setNeedsLayout() } } /** Different color themes of the slider. */ public var theme: Theme = .black { didSet { // // Set the color based on // selected option var tintColor: UIColor switch theme { case .black: tintColor = UIColor.black backgroundColor = UIColor.lightGray.withAlphaComponent(0.6) case .blue: tintColor = UIColor.customBlue backgroundColor = UIColor.lightSkyBlue.withAlphaComponent(0.3) case .oceanBlue: tintColor = UIColor.oceanBlue backgroundColor = UIColor.white.withAlphaComponent(0.6) } // Set colors of the components currentExtentFillColor = tintColor currentExtentLabelColor = tintColor fullExtentBorderColor = tintColor fullExtentFillColor = UIColor.white fullExtentLabelColor = tintColor timeStepIntervalLabelColor = tintColor timeStepIntervalTickColor = tintColor thumbFillColor = UIColor.white thumbBorderColor = tintColor layerExtentFillColor = tintColor.withAlphaComponent(0.4) pinnedThumbFillColor = tintColor playbackButtonsFillColor = tintColor } } /** A Boolean value indicating whether changes in the slider’s value generate continuous update events. Default is True. */ public var isContinuous: Bool = true // MARK: - Private Properties private var currentExtentStartTime: Date? private var currentExtentEndTime: Date? private var previousCurrentExtentStartTime: Date? private var previousCurrentExtentEndTime: Date? private var startTimeStepIndex: Int = -1 private var endTimeStepIndex: Int = -1 private var internalUpdate: Bool = false fileprivate var layerExtent: AGSTimeExtent? private let trackLayer = TimeSliderTrackLayer() private let tickMarkLayer = TimeSliderTickMarkLayer() private let lowerThumbLayer = TimeSliderThumbLayer() private let upperThumbLayer = TimeSliderThumbLayer() private let fullExtentStartTimeLabel = CATextLayer() private let fullExtentEndTimeLabel = CATextLayer() private let currentExtentStartTimeLabel = CATextLayer() private let currentExtentEndTimeLabel = CATextLayer() private let minimumFrameWidth: CGFloat = 250.0 private let maximumThumbSize: CGFloat = 50.0 private var trackLayerSidePadding: CGFloat = 30.0 private let labelSidePadding: CGFloat = 10.0 private let labelPadding: CGFloat = 3.0 private let paddingBetweenLabels: CGFloat = 5.0 private var tickMarkLabels = [CATextLayer]() fileprivate var tickMarks = [TickMark]() private let playPauseButton = UIButton(type: .custom) private let forwardButton = UIButton(type: .custom) private let backButton = UIButton(type: .custom) fileprivate var pinnedThumbFillColor = UIColor.black // If set to True, it will show two thumbs, otherwise only one. Default is True. fileprivate var isRangeEnabled: Bool = true { didSet { upperThumbLayer.isHidden = !isRangeEnabled currentExtentEndTimeLabel.isHidden = !isRangeEnabled } } private var timer: Timer? private var map: AGSMap? private var scene: AGSScene? private var isObserving: Bool = false private var reInitializeTimeProperties: Bool = false private var mapLayersObservation: NSKeyValueObservation? private var sceneLayersObservation: NSKeyValueObservation? private var timeExtentObservation: NSKeyValueObservation? // MARK: - Override Functions public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public var frame: CGRect { didSet { // // Check for minimum width and height if frame.size.width < minimumFrameWidth { frame.size.width = minimumFrameWidth } if frame.size.height < intrinsicContentSize.height { frame.size.height = intrinsicContentSize.height } setNeedsLayout() } } override init(frame: CGRect) { super.init(frame: frame) setupUI() } override public func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { // // Stop playing isPlaying = false // Set preview location from touch let location = touch.location(in: self) // Hit test the thumb layers. // If the thumb is pinned then it should not allow the interaction. if !lowerThumbLayer.isPinned && lowerThumbLayer.frame.contains(location) { lowerThumbLayer.isHighlighted = true } if !upperThumbLayer.isPinned && isRangeEnabled && upperThumbLayer.frame.contains(location) { upperThumbLayer.isHighlighted = true } // If both thumbs are highlighted and are at full extent's start time then return only highlighted upper thumb layer if let fullExtentStartTime = fullExtent?.startTime, let currentExtentStartTime = currentExtentStartTime, let currentExtentEndTime = currentExtentEndTime, (currentExtentStartTime, currentExtentEndTime) == (currentExtentEndTime, fullExtentStartTime), lowerThumbLayer.isHighlighted, upperThumbLayer.isHighlighted { lowerThumbLayer.isHighlighted = false upperThumbLayer.isHighlighted = true } return lowerThumbLayer.isHighlighted || upperThumbLayer.isHighlighted } override public func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { // // Get the touch location let location = touch.location(in: self) // Get the selected value let selectedValue = value(for: Double(location.x)) // Set values based on selected thumb if lowerThumbLayer.isHighlighted { updateCurrentExtentStartTime(Date(timeIntervalSince1970: selectedValue)) } else if upperThumbLayer.isHighlighted { updateCurrentExtentEndTime(Date(timeIntervalSince1970: selectedValue)) } // If range is not enabled // then both values are same if !isRangeEnabled { currentExtentEndTime = currentExtentStartTime } // Set current extent updateCurrentExtent(AGSTimeExtent(startTime: currentExtentStartTime, endTime: currentExtentEndTime)) // Notify that the value is changed if isContinuous { notifyChangeOfCurrentExtent() } return true } override public func endTracking(_ touch: UITouch?, with event: UIEvent?) { // // Un-highlight thumbs lowerThumbLayer.isHighlighted = false upperThumbLayer.isHighlighted = false // Notify that the value is changed if !isContinuous { notifyChangeOfCurrentExtent() } } // Refresh the slider when requried override public func layoutSubviews() { // // Calculate time steps if timeSteps == nil || timeSteps?.isEmpty == true { calculateTimeSteps() } // Update frames updateLayerFrames() // Update labels updateFullExtentLabelFrames() updateCurrentExtentLabelFrames() } // Set intrinsic content size override public var intrinsicContentSize: CGSize { let intrinsicHeight: CGFloat if isSliderVisible { if playbackButtonsVisible { intrinsicHeight = 136 } else { intrinsicHeight = 100 } } else { intrinsicHeight = 60 } return CGSize(width: UIView.noIntrinsicMetric, height: intrinsicHeight) } // Deinit deinit { removeObservers() } // MARK: Public Functions /** This will look for all time aware layers which are visible and are participating in time based filtering to initialize slider's fullExtent, currentExtent and timeStepInterval properties. Setting observeGeoView to true will observe changes in operational layers and time extent of geoView. */ // swiftlint:disable cyclomatic_complexity public func initializeTimeProperties(geoView: AGSGeoView, observeGeoView: Bool, completion: @escaping (Error?) -> Void) { // // Set operational layers guard let operationalLayers = geoView.operationalLayers, !operationalLayers.isEmpty else { completion(NSError(domain: AGSErrorDomain, code: AGSErrorCode.commonNoData.rawValue, userInfo: [NSLocalizedDescriptionKey: "There are no time aware layers to initialize time slider."])) return } // Set geoview and it's properties on the slider // it will initialize required properties. self.geoView = geoView // Set map/scene if let mapView = geoView as? AGSMapView { map = mapView.map } else if let sceneView = geoView as? AGSSceneView { scene = sceneView.scene } // Set observeGeoView after // setting map and scene self.observeGeoView = observeGeoView // // Loop through all time aware layers which are visible and are participating in time based filtering // and initialize slider's fullExtent, currentExtent and timeStepInterval properties var timeAwareLayersFullExtent: AGSTimeExtent? var timeAwareLayersStepInterval: AGSTimeValue? var supportsRangeTimeFiltering = true // // This will help in waiting for all layer/sublayers // to be loaded to gather requried information // to load time properties let dispatchGroup = DispatchGroup() // Load all operational layers to initialize slider properties AGSLoadObjects(operationalLayers) { [weak self] (loaded) in // // Bail out if layers // are not loaded guard loaded else { return } // Make sure self is around guard let self = self else { return } // Once, all layers are loaded, // loop through all of them. operationalLayers.forEach { (layer) in // // The layer must be time aware, supports time filtering and time filtering is enabled. guard let timeAwareLayer = layer as? AGSTimeAware, timeAwareLayer.supportsTimeFiltering, timeAwareLayer.isTimeFilteringEnabled else { return } // // Get the layer's full time extent and combine with other layer's full extent. if let fullTimeExtent = timeAwareLayer.fullTimeExtent { timeAwareLayersFullExtent = timeAwareLayersFullExtent == nil ? timeAwareLayer.fullTimeExtent : timeAwareLayersFullExtent?.union(otherTimeExtent: fullTimeExtent) } // This is an async operation to find out time step interval and // whether range time filtering is supported by the layer. dispatchGroup.enter() self.findTimeStepIntervalAndIsRangeTimeFilteringSupported(for: timeAwareLayer) { (timeInterval, supportsRangeFiltering) in // // Set the range filtering value supportsRangeTimeFiltering = supportsRangeFiltering // We are looking for the greater time interval than we already have it. if let timeInterval = timeInterval { if let layersTimeInterval = timeAwareLayersStepInterval { if timeInterval > layersTimeInterval { timeAwareLayersStepInterval = timeInterval } } else { timeAwareLayersStepInterval = timeInterval } } // We got all information required. // Leave the group so we can set time // properties and notify dispatchGroup.leave() } } dispatchGroup.notify(queue: DispatchQueue.main) { // // If full extent or time step interval is not available then // we cannot initialize the slider. Finish with error. guard let layersFullExtent = timeAwareLayersFullExtent else { completion(NSError(domain: AGSErrorDomain, code: AGSErrorCode.commonNoData.rawValue, userInfo: [NSLocalizedDescriptionKey: "There are no time aware layers to initialize time slider."])) return } // // Set calculated full extent and time step interval self.fullExtent = layersFullExtent // Layer extent should be same as full extent. self.layerExtent = self.fullExtent // Set the time step interval. If it is not available then // calculate using default timeStepCount if let timeStepInterval = timeAwareLayersStepInterval { self.timeStepInterval = timeStepInterval } else { self.timeStepInterval = self.calculateTimeStepInterval(for: layersFullExtent, timeStepCount: 0) } // If the geoview has a time extent defined and we are not re-initializing, use that. Otherwise, set the // current extent to either the full extent's start (if range filtering is not supported), or to the entire full extent. if let geoViewTimeExtent = self.geoView?.timeExtent, !self.reInitializeTimeProperties { self.currentExtent = geoViewTimeExtent } else { if let fullExtentStartTime = self.fullExtent?.startTime, let fullExtentEndTime = self.fullExtent?.endTime { self.currentExtent = supportsRangeTimeFiltering ? AGSTimeExtent(startTime: fullExtentStartTime, endTime: fullExtentEndTime) : AGSTimeExtent(timeInstant: fullExtentStartTime) } } completion(nil) } } } // swiftlint:enable cyclomatic_complexity /** This will initialize slider's fullExtent, currentExtent and timeStepInterval properties if the layer is visible and participate in time based filtering. */ public func initializeTimeProperties(timeAwareLayer: AGSTimeAware, completion: @escaping (Error?) -> Void) { // // The layer must be loadable. guard let layer = timeAwareLayer as? AGSLoadable else { completion(NSError(domain: AGSErrorDomain, code: AGSErrorCode.commonNoData.rawValue, userInfo: [NSLocalizedDescriptionKey: "The layer is not loadable to initialize time slider."])) return } layer.load { [weak self] (error) in // // If layer fails to load then // return with an error. guard error == nil else { completion(error) return } // The layer must support time filtering and it should enabled // then only we can initialize the time slider. guard timeAwareLayer.supportsTimeFiltering, timeAwareLayer.isTimeFilteringEnabled else { completion(NSError(domain: AGSErrorDomain, code: AGSErrorCode.commonNoData.rawValue, userInfo: [NSLocalizedDescriptionKey: "The layer either does not support time filtering or is not enabled."])) return } // Make sure self is around guard let self = self else { return } // // This is an async operation to find out time step interval and // whether range time filtering is supported by the layer. self.findTimeStepIntervalAndIsRangeTimeFilteringSupported(for: timeAwareLayer) { [weak self] (timeInterval, supportsRangeTimeFiltering) in // // Make sure self is around guard let self = self else { return } // If either full extent or time step interval is not // available then the layer does not have information // required to initialize time slider. Finish with an error. guard let fullTimeExtent = timeAwareLayer.fullTimeExtent else { completion(NSError(domain: AGSErrorDomain, code: AGSErrorCode.commonNoData.rawValue, userInfo: [NSLocalizedDescriptionKey: "The layer does not have time information to initialize time slider."])) return } // Set full extent of the layer self.fullExtent = fullTimeExtent // Layer extent should be same as full extent. self.layerExtent = self.fullExtent // Set the time step interval. If it is not available then // calculate using default timeStepCount if let timeInterval = timeInterval { self.timeStepInterval = timeInterval } else { self.timeStepInterval = self.calculateTimeStepInterval(for: fullTimeExtent, timeStepCount: 0) } // Set the current extent to either the full extent's start (if range filtering is not supported), or to the entire full extent. if let fullExtentStartTime = self.fullExtent?.startTime, let fullExtentEndTime = self.fullExtent?.endTime { self.currentExtent = supportsRangeTimeFiltering ? AGSTimeExtent(startTime: fullExtentStartTime, endTime: fullExtentEndTime) : AGSTimeExtent(timeInstant: fullExtentStartTime) } // Slider is loaded successfully. completion(nil) } } } /** This will initialize slider's fullExtent, currentExtent and timeStepInterval properties based on provided step count and full extent. The current extent will be set to a time instant. */ public func initializeTimeSteps(timeStepCount: Int, fullExtent: AGSTimeExtent, completion: @escaping (Error?) -> Void) { // // There should be at least two time steps // for time slider to work correctly. guard timeStepCount >= 2 else { completion(NSError(domain: AGSErrorDomain, code: AGSErrorCode.commonNoData.rawValue, userInfo: [NSLocalizedDescriptionKey: "fullExtent is not available to calculate time steps."])) return } // Full extent's start and end time must be available for time slider to work correctly. guard let fullExtentStartTime = fullExtent.startTime, fullExtent.endTime != nil else { completion(NSError(domain: AGSErrorDomain, code: AGSErrorCode.commonNoData.rawValue, userInfo: [NSLocalizedDescriptionKey: "fullExtent is not available to calculate time steps."])) return } // Set current extent as time instant currentExtent = AGSTimeExtent(timeInstant: fullExtentStartTime) // Set full extent self.fullExtent = fullExtent // Calculate time step interval timeStepInterval = calculateTimeStepInterval(for: fullExtent, timeStepCount: timeStepCount) // Slider is loaded successfully. completion(nil) } /** Moves the slider thumbs forward with provided time steps. */ @discardableResult public func stepForward(timeSteps: Int) -> Bool { // // Time steps must be greater than 0 if timeSteps > 0 { return moveTimeStep(timeSteps: timeSteps) } return false } /** Moves the slider thumbs back with provided time steps. */ @discardableResult public func stepBack(timeSteps: Int) -> Bool { // // Time steps must be greater than 0 if timeSteps > 0 { return moveTimeStep(timeSteps: -timeSteps) } return false } // MARK: - Actions @objc private func forwardAction(_ sender: UIButton) { isPlaying = false stepForward(timeSteps: 1) } @objc private func backAction(_ sender: UIButton) { isPlaying = false stepBack(timeSteps: 1) } @objc private func playPauseAction(_ sender: UIButton) { isPlaying.toggle() } @discardableResult private func moveTimeStep(timeSteps: Int) -> Bool { // // Time steps must be between 1 and count of calculated time steps if let ts = self.timeSteps, timeSteps < ts.count, let startTime = currentExtentStartTime, let endTime = currentExtentEndTime { // // Bail out if start and end both times are pinned if isStartTimePinned && isEndTimePinned { isPlaying = false return false } // Set the start time step index if it's not set if startTimeStepIndex <= 0 { if let (index, date) = closestTimeStep(for: startTime) { currentExtentStartTime = date startTimeStepIndex = index } } // Set the end time step index if it's not set if endTimeStepIndex <= 0 { if let (index, date) = closestTimeStep(for: endTime) { currentExtentEndTime = date endTimeStepIndex = index } } // Get the minimum and maximum allowable time step indexes. This is not necessarily the end of the time slider since // the start and end times may be pinned. let minTimeStepIndex = !isStartTimePinned ? 0 : startTimeStepIndex let maxTimeStepIndex = !isEndTimePinned ? ts.count - 1 : endTimeStepIndex // Get the number of steps by which to move the current time. If the number specified in the method call would move the current time extent // beyond the valid range, clamp the number of steps to the maximum number that the extent can move in the specified direction. var validTimeStepDelta = 0 if timeSteps > 0 { validTimeStepDelta = startTimeStepIndex + timeSteps <= maxTimeStepIndex ? timeSteps : maxTimeStepIndex - startTimeStepIndex } else { validTimeStepDelta = endTimeStepIndex + timeSteps >= minTimeStepIndex ? timeSteps : minTimeStepIndex - endTimeStepIndex } // Get the new start time step index let positiveDeltaChange = validTimeStepDelta > 0 || startTimeStepIndex + validTimeStepDelta >= minTimeStepIndex let deltaChangeResultIsNotGreaterThanMaxIndex = (endTimeStepIndex + validTimeStepDelta <= maxTimeStepIndex) || isEndTimePinned let newStartTimeStepIndex = !isStartTimePinned && positiveDeltaChange && deltaChangeResultIsNotGreaterThanMaxIndex ? startTimeStepIndex + validTimeStepDelta : startTimeStepIndex // Get the new end time step index let negativeDeltaChange = validTimeStepDelta < 0 || endTimeStepIndex + validTimeStepDelta <= maxTimeStepIndex let deltaChangeResultIsNotLessThanMinIndex = (startTimeStepIndex + validTimeStepDelta >= minTimeStepIndex) || isStartTimePinned let newEndTimeStepIndex = !isEndTimePinned && negativeDeltaChange && deltaChangeResultIsNotLessThanMinIndex ? endTimeStepIndex + validTimeStepDelta : endTimeStepIndex // Evaluate how many time steps the start and end were moved by and whether they were able to be moved by the requested number of steps let startDelta = newStartTimeStepIndex - startTimeStepIndex let endDelta = newEndTimeStepIndex - endTimeStepIndex let canMoveStartAndEndByTimeSteps = startDelta == timeSteps && endDelta == timeSteps let canMoveStartOrEndByTimeSteps = startDelta == timeSteps || endDelta == timeSteps let isRequestedMoveValid = canMoveStartAndEndByTimeSteps || canMoveStartOrEndByTimeSteps // Apply the new extent if the new time indexes represent a valid change if isRequestedMoveValid && newStartTimeStepIndex < ts.count && newEndTimeStepIndex < ts.count { // Set new times and time step indexes currentExtentStartTime = ts[newStartTimeStepIndex] startTimeStepIndex = newStartTimeStepIndex currentExtentEndTime = ts[newEndTimeStepIndex] endTimeStepIndex = newEndTimeStepIndex // If range is not enabled // then both values are same if !isRangeEnabled { currentExtentEndTime = currentExtentStartTime } // Set current extent updateCurrentExtent(AGSTimeExtent(startTime: currentExtentStartTime, endTime: currentExtentEndTime)) // Notify the chagne in current extent notifyChangeOfCurrentExtent() } return isRequestedMoveValid } return false } @objc private func timerAction() { if let geoView = self.geoView { if geoView.drawStatus == .completed { handlePlaying() } } else { handlePlaying() } } private func handlePlaying() { switch playbackLoopMode { case .none: isPlaying = false case .repeat(.forward): var timeStepsToMove = 1 let moveTimeStepResult = moveTimeStep(timeSteps: timeStepsToMove) if !moveTimeStepResult { timeStepsToMove = !isStartTimePinned ? -startTimeStepIndex : -(endTimeStepIndex - startTimeStepIndex) moveTimeStep(timeSteps: timeStepsToMove) } case .repeat(.backward): var timeStepsToMove = -1 let moveTimeStepResult = moveTimeStep(timeSteps: timeStepsToMove) if !moveTimeStepResult { if let ts = timeSteps { timeStepsToMove = !isEndTimePinned ? ts.count - endTimeStepIndex - 1 : endTimeStepIndex - startTimeStepIndex - 1 moveTimeStep(timeSteps: timeStepsToMove) } } case .reverse(.forward): let moveTimeStepResult = moveTimeStep(timeSteps: 1) if !moveTimeStepResult { playbackLoopMode = .reverse(.backward) } case .reverse(.backward): let moveTimeStepResult = moveTimeStep(timeSteps: -1) if !moveTimeStepResult { playbackLoopMode = .reverse(.forward) } } } // MARK: - Private Functions private func setupUI() { // // Set background color backgroundColor = UIColor.lightGray.withAlphaComponent(0.7) // Set corner radius layer.cornerRadius = 10 // Set the content mode contentMode = .redraw // Add track layer trackLayer.timeSlider = self trackLayer.contentsScale = UIScreen.main.scale layer.addSublayer(trackLayer) // Add tick layer tickMarkLayer.timeSlider = self tickMarkLayer.contentsScale = UIScreen.main.scale layer.addSublayer(tickMarkLayer) // Add lower thumb layer lowerThumbLayer.timeSlider = self lowerThumbLayer.contentsScale = UIScreen.main.scale layer.addSublayer(lowerThumbLayer) // Add upper thumb layer upperThumbLayer.timeSlider = self upperThumbLayer.contentsScale = UIScreen.main.scale layer.addSublayer(upperThumbLayer) // Add the minimum value label fullExtentStartTimeLabel.isHidden = !(fullExtentLabelsVisible && isSliderVisible) fullExtentStartTimeLabel.foregroundColor = fullExtentLabelColor.cgColor fullExtentStartTimeLabel.alignmentMode = .center fullExtentStartTimeLabel.frame = CGRect.zero fullExtentStartTimeLabel.contentsScale = UIScreen.main.scale fullExtentStartTimeLabel.font = fullExtentLabelFont as CFTypeRef fullExtentStartTimeLabel.fontSize = fullExtentLabelFont.pointSize layer.addSublayer(fullExtentStartTimeLabel) // Add the minimum value label fullExtentEndTimeLabel.isHidden = !(fullExtentLabelsVisible && isSliderVisible) fullExtentEndTimeLabel.foregroundColor = fullExtentLabelColor.cgColor fullExtentEndTimeLabel.alignmentMode = CATextLayerAlignmentMode.center fullExtentEndTimeLabel.frame = CGRect.zero fullExtentEndTimeLabel.contentsScale = UIScreen.main.scale fullExtentEndTimeLabel.font = fullExtentLabelFont as CFTypeRef fullExtentEndTimeLabel.fontSize = fullExtentLabelFont.pointSize layer.addSublayer(fullExtentEndTimeLabel) // Add the lower value label currentExtentStartTimeLabel.isHidden = !(labelMode == .thumbs && isSliderVisible) currentExtentStartTimeLabel.foregroundColor = currentExtentLabelColor.cgColor currentExtentStartTimeLabel.alignmentMode = CATextLayerAlignmentMode.center currentExtentStartTimeLabel.frame = CGRect.zero currentExtentStartTimeLabel.contentsScale = UIScreen.main.scale currentExtentStartTimeLabel.font = currentExtentLabelFont as CFTypeRef currentExtentStartTimeLabel.fontSize = currentExtentLabelFont.pointSize layer.addSublayer(currentExtentStartTimeLabel) // Add the upper value label currentExtentEndTimeLabel.isHidden = !(labelMode == .thumbs && isSliderVisible) currentExtentEndTimeLabel.foregroundColor = currentExtentLabelColor.cgColor currentExtentEndTimeLabel.alignmentMode = CATextLayerAlignmentMode.center currentExtentEndTimeLabel.frame = CGRect.zero currentExtentEndTimeLabel.contentsScale = UIScreen.main.scale currentExtentEndTimeLabel.font = currentExtentLabelFont as CFTypeRef currentExtentEndTimeLabel.fontSize = currentExtentLabelFont.pointSize layer.addSublayer(currentExtentEndTimeLabel) // Create the images let bundle = Bundle(for: type(of: self)) let playImage = UIImage(named: "Play", in: bundle, compatibleWith: nil) let pauseImage = UIImage(named: "Pause", in: bundle, compatibleWith: nil) let forwardImage = UIImage(named: "Forward", in: bundle, compatibleWith: nil) let backImage = UIImage(named: "Back", in: bundle, compatibleWith: nil) // Setup Play/Pause button playPauseButton.setImage(playImage, for: .normal) playPauseButton.setImage(pauseImage, for: .selected) playPauseButton.tintColor = playbackButtonsFillColor playPauseButton.addTarget(self, action: #selector(TimeSlider.playPauseAction(_:)), for: .touchUpInside) playPauseButton.showsTouchWhenHighlighted = true addSubview(playPauseButton) // Setup forward button forwardButton.setImage(forwardImage, for: .normal) forwardButton.tintColor = playbackButtonsFillColor forwardButton.addTarget(self, action: #selector(TimeSlider.forwardAction(_:)), for: .touchUpInside) forwardButton.showsTouchWhenHighlighted = true addSubview(forwardButton) // Setup back button backButton.setImage(backImage, for: .normal) backButton.tintColor = playbackButtonsFillColor backButton.addTarget(self, action: #selector(TimeSlider.backAction(_:)), for: .touchUpInside) backButton.showsTouchWhenHighlighted = true addSubview(backButton) } private func updateLayerFrames() { // // Begin the transaction CATransaction.begin() CATransaction.setDisableActions(true) // Set frames for slider components // only if slider is visible if isSliderVisible { // var trackLayerOriginY = bounds.midY + 24 if !playbackButtonsVisible { trackLayerOriginY = bounds.midY - (trackHeight / 2.0) } // Set track layer frame let trackLayerOrigin = CGPoint(x: trackLayerSidePadding, y: trackLayerOriginY) let trackLayerSize = CGSize(width: bounds.width - trackLayerSidePadding * 2, height: trackHeight) let trackLayerFrame = CGRect(origin: trackLayerOrigin, size: trackLayerSize) trackLayer.frame = trackLayerFrame trackLayer.setNeedsDisplay() // Set track layer frame let tickMarkLayerFrame = trackLayerFrame.insetBy(dx: 0.0, dy: -10.0) tickMarkLayer.frame = tickMarkLayerFrame tickMarkLayer.setNeedsDisplay() // Update tick marks positionTickMarks() // Set lower thumb layer frame if let startTime = currentExtentStartTime, fullExtent != nil { let lowerThumbCenter = CGFloat(position(for: startTime.timeIntervalSince1970)) let lowerThumbOrigin = CGPoint(x: trackLayerSidePadding + lowerThumbCenter - thumbSize.width / 2.0, y: trackLayerFrame.midY - thumbSize.height / 2.0) let lowerThumbFrame = CGRect(origin: lowerThumbOrigin, size: thumbSize) lowerThumbLayer.isHidden = !isSliderVisible lowerThumbLayer.frame = lowerThumbFrame lowerThumbLayer.setNeedsDisplay() } else { lowerThumbLayer.isHidden = true } // Set upper thumb layer frame if let endTime = currentExtentEndTime, isRangeEnabled, fullExtent != nil { let upperThumbCenter = CGFloat(position(for: endTime.timeIntervalSince1970)) let upperThumbOrigin = CGPoint(x: trackLayerSidePadding + upperThumbCenter - thumbSize.width / 2.0, y: trackLayerFrame.midY - thumbSize.height / 2.0) let upperThumbFrame = CGRect(origin: upperThumbOrigin, size: thumbSize) upperThumbLayer.isHidden = !isSliderVisible upperThumbLayer.frame = upperThumbFrame upperThumbLayer.setNeedsDisplay() } else { upperThumbLayer.isHidden = true } } // Set frames for playback buttons // if they are visible if playbackButtonsVisible { // // Set frames for buttons let paddingBetweenButtons: CGFloat = 2.0 let buttonSize = CGSize(width: 44, height: 44) // Set frame for play pause button var playPauseButtonOrigin = CGPoint(x: bounds.midX - buttonSize.width / 2.0, y: bounds.minY + 12) if !isSliderVisible { playPauseButtonOrigin = CGPoint(x: bounds.midX - buttonSize.width / 2.0, y: bounds.midY - buttonSize.height / 2.0) } playPauseButton.frame = CGRect(origin: playPauseButtonOrigin, size: buttonSize) // Set frame for forward button let forwardButtonOrigin = CGPoint(x: playPauseButtonOrigin.x + buttonSize.width + paddingBetweenButtons, y: playPauseButtonOrigin.y) forwardButton.frame = CGRect(origin: forwardButtonOrigin, size: buttonSize) // Set frame for back button let backButtonOrigin = CGPoint(x: playPauseButtonOrigin.x - paddingBetweenButtons - buttonSize.width, y: playPauseButtonOrigin.y) backButton.frame = CGRect(origin: backButtonOrigin, size: buttonSize) } // Commit the transaction CATransaction.commit() } private func updateFullExtentLabelFrames() { // // If full extent labels are not // visible then bail out. if !fullExtentLabelsVisible { return } // // Begin the transaction CATransaction.begin() CATransaction.setDisableActions(true) // // Update full extent start time label if let fullExtentStartTime = fullExtent?.startTime { // let startTimeString = string(for: fullExtentStartTime, style: fullExtentLabelDateStyle) fullExtentStartTimeLabel.string = startTimeString fullExtentStartTimeLabel.isHidden = !(fullExtentLabelsVisible && isSliderVisible) let startTimeLabelSize = startTimeString.size(withAttributes: [.font: fullExtentLabelFont]) var startTimeLabelX = trackLayer.frame.minX - (startTimeLabelSize.width / 2.0) if startTimeLabelX < bounds.minX + labelSidePadding { startTimeLabelX = bounds.minX + labelSidePadding } let thumbStartTimeLabelY = lowerThumbLayer.frame.maxY + labelPadding let tickLayerStartTimeLabelY = tickMarkLayer.frame.maxY + labelPadding let startTimeLabelY = max(thumbStartTimeLabelY, tickLayerStartTimeLabelY) fullExtentStartTimeLabel.frame = CGRect(x: startTimeLabelX, y: startTimeLabelY, width: startTimeLabelSize.width, height: startTimeLabelSize.height) } else { fullExtentStartTimeLabel.string = "" fullExtentStartTimeLabel.isHidden = true } // Update full extent end time label if let fullExtentEndTime = fullExtent?.endTime { // let endTimeString = string(for: fullExtentEndTime, style: fullExtentLabelDateStyle) fullExtentEndTimeLabel.string = endTimeString fullExtentEndTimeLabel.isHidden = !(fullExtentLabelsVisible && isSliderVisible) let endTimeLabelSize: CGSize = endTimeString.size(withAttributes: [kCTFontAttributeName as NSAttributedString.Key: fullExtentLabelFont]) var endTimeLabelX = trackLayer.frame.maxX - (fullExtentEndTimeLabel.frame.width / 2.0) if endTimeLabelX + endTimeLabelSize.width > bounds.maxX - labelSidePadding { endTimeLabelX = bounds.maxX - endTimeLabelSize.width - labelSidePadding } let thumbEndTimeLabelY = lowerThumbLayer.frame.maxY + labelPadding let tickLayerEndTimeLabelY = tickMarkLayer.frame.maxY + labelPadding let endTimeLabelY = max(thumbEndTimeLabelY, tickLayerEndTimeLabelY) fullExtentEndTimeLabel.frame = CGRect(x: endTimeLabelX, y: endTimeLabelY, width: endTimeLabelSize.width, height: endTimeLabelSize.height) } else { fullExtentEndTimeLabel.string = "" fullExtentEndTimeLabel.isHidden = true } // Commit the transaction CATransaction.commit() } // swiftlint:disable cyclomatic_complexity private func updateCurrentExtentLabelFrames() { // // If label mode is not thumbs then // hide the current extent labels and // bail out. if labelMode != .thumbs { currentExtentStartTimeLabel.isHidden = true currentExtentEndTimeLabel.isHidden = true return } // // Begin the transaction CATransaction.begin() CATransaction.setDisableActions(true) // // Update current extent start time label if let startTime = currentExtentStartTime, fullExtent != nil { let startTimeString = string(for: startTime, style: currentExtentLabelDateStyle) currentExtentStartTimeLabel.string = startTimeString let startTimeLabelSize: CGSize = startTimeString.size(withAttributes: [kCTFontAttributeName as NSAttributedString.Key: currentExtentLabelFont]) var startTimeLabelX = lowerThumbLayer.frame.midX - startTimeLabelSize.width / 2.0 currentExtentStartTimeLabel.isHidden = !isSliderVisible if startTimeLabelX < bounds.origin.x + labelSidePadding { startTimeLabelX = bounds.origin.x + labelSidePadding if let fullExtentStartTime = fullExtent?.startTime, fullExtentStartTime == startTime { currentExtentStartTimeLabel.isHidden = true } } else if startTimeLabelX + startTimeLabelSize.width > bounds.maxX - labelSidePadding { startTimeLabelX = bounds.maxX - startTimeLabelSize.width - labelSidePadding if let fullExtentEndTime = fullExtent?.endTime, fullExtentEndTime == startTime { currentExtentStartTimeLabel.isHidden = true } } else if !currentExtentEndTimeLabel.isHidden && currentExtentEndTimeLabel.frame.origin.x >= 0.0 && startTimeLabelX + startTimeLabelSize.width > currentExtentEndTimeLabel.frame.origin.x { startTimeLabelX = currentExtentEndTimeLabel.frame.origin.x - startTimeLabelSize.width - paddingBetweenLabels } let thumbStartTimeLabelY = lowerThumbLayer.frame.minY - currentExtentStartTimeLabel.frame.height - labelPadding let tickLayerStartTimeLabelY = tickMarkLayer.frame.minY - currentExtentStartTimeLabel.frame.height - labelPadding let startTimeLabelY = min(thumbStartTimeLabelY, tickLayerStartTimeLabelY) currentExtentStartTimeLabel.frame = CGRect(x: startTimeLabelX, y: startTimeLabelY, width: startTimeLabelSize.width, height: startTimeLabelSize.height) } else { currentExtentStartTimeLabel.string = "" currentExtentStartTimeLabel.isHidden = true } // Update current extent end time label if let endTime = currentExtentEndTime, isRangeEnabled, fullExtent != nil { let endTimeString = string(for: endTime, style: currentExtentLabelDateStyle) currentExtentEndTimeLabel.string = endTimeString let endTimeLabelSize: CGSize = endTimeString.size(withAttributes: [kCTFontAttributeName as NSAttributedString.Key: currentExtentLabelFont]) var endTimeLabelX = upperThumbLayer.frame.midX - endTimeLabelSize.width / 2.0 currentExtentEndTimeLabel.isHidden = !isSliderVisible if endTimeLabelX < bounds.origin.x + labelSidePadding { endTimeLabelX = bounds.origin.x + labelSidePadding if let fullExtentStartTime = fullExtent?.startTime, fullExtentStartTime == endTime { currentExtentEndTimeLabel.isHidden = true } } else if endTimeLabelX + endTimeLabelSize.width > bounds.maxX - labelSidePadding { endTimeLabelX = bounds.maxX - endTimeLabelSize.width - labelSidePadding if let fullExtentEndTime = fullExtent?.endTime, fullExtentEndTime == endTime { currentExtentEndTimeLabel.isHidden = true } } else if !currentExtentStartTimeLabel.isHidden && endTimeLabelX < currentExtentStartTimeLabel.frame.origin.x + currentExtentStartTimeLabel.frame.width { endTimeLabelX = currentExtentStartTimeLabel.frame.origin.x + currentExtentStartTimeLabel.frame.width + paddingBetweenLabels } let thumbEndTimeLabelY = upperThumbLayer.frame.minY - currentExtentEndTimeLabel.frame.height - labelPadding let tickLayerEndTimeLabelY = tickMarkLayer.frame.minY - currentExtentEndTimeLabel.frame.height - labelPadding let endTimeLabelY = min(thumbEndTimeLabelY, tickLayerEndTimeLabelY) currentExtentEndTimeLabel.frame = CGRect(x: endTimeLabelX, y: endTimeLabelY, width: endTimeLabelSize.width, height: endTimeLabelSize.height) } else { currentExtentEndTimeLabel.string = "" currentExtentEndTimeLabel.isHidden = true } // Commit the transaction CATransaction.commit() } // swiftlint:enable cyclomatic_complexity // swiftlint:disable cyclomatic_complexity private func positionTickMarks() { // // Bail out if time steps are not available guard let timeSteps = timeSteps, !timeSteps.isEmpty, isSliderVisible else { return } // Create tick marks based on // time steps and it's calculated // position on the slider let tms = timeSteps.map { timeStep -> TickMark in let tickX = CGFloat(position(for: timeStep.timeIntervalSince1970)) return TickMark(originX: tickX, value: timeStep) } // If label mode is ticks then we need to // find out the major/minor ticks and // add labels for major ticks if labelMode == .ticks { var majorTickInterval = 2 var doMajorTickLabelsCollide = false var firstMajorTickIndex = 0 let tickCount = tms.count // Calculate the largest number of ticks to allow between major ticks. This prevents scenarios where // there are two major ticks placed undesirably close to the end. let maxMajorTickInterval = Int((Double(tickCount) / 2).rounded(.up)) // If maxMajorTickInterval is not greater than majorTickInterval // then we can not do further calculation if maxMajorTickInterval >= majorTickInterval { // // Calculate the number of ticks between each major tick and the index of the first major tick for i in majorTickInterval..<maxMajorTickInterval { let prospectiveInterval = i var allowsEqualNumberOfTicksOnEnds = false // Check that the prospective interval between major ticks results in // an equal number of minor ticks on both ends. for m in stride(from: prospectiveInterval, to: tickCount, by: prospectiveInterval) { let totalNumberOfTicksOnEnds = tickCount - m + 1 // If the total number of minor ticks on both ends (i.e. before and after the // first and last major ticks) is less than the major tick interval being tested, then we've // found the number of minor ticks that would be on the ends if we use this major tick interval. // If that total is divisible by two, then the major tick interval under test allows for an // equal number of minor ticks on the ends. if totalNumberOfTicksOnEnds / 2 < prospectiveInterval && totalNumberOfTicksOnEnds % 2 == 0 { allowsEqualNumberOfTicksOnEnds = true break } } // Only consider intervals that leave an equal number of ticks on the ends if !allowsEqualNumberOfTicksOnEnds { continue } // Calculate the tick index of the first major tick if we were to use the prospective interval. // The index is calculated such that there will be an equal number of minor ticks before and // after the first and last major tick mark. firstMajorTickIndex = Int(trunc((Double(tickCount - 1).truncatingRemainder(dividingBy: Double(prospectiveInterval))) / 2.0)) // With the given positioning of major tick marks, check whether their labels will overlap. for j in stride(from: firstMajorTickIndex, to: tickCount - prospectiveInterval, by: i) { // // Get the current tick and it's label let currentTick = tms[j] var currentTickLabelFrame: CGRect? if let currentTickDate = currentTick.value, let currentTickXPosition = currentTick.originX { let currentTickLabelString = string(for: currentTickDate, style: timeStepIntervalLabelDateStyle) let currentTickLabel = tickMarkLabel(with: currentTickLabelString, originX: currentTickXPosition) currentTickLabelFrame = currentTickLabel.frame } // Get the next tick and it's label let nextTick = tms[j + i] var nextTickLabelFrame: CGRect? if let nextTickDate = nextTick.value, let nextTickXPosition = nextTick.originX { let nextTickLabelString = string(for: nextTickDate, style: timeStepIntervalLabelDateStyle) let nextTickLabel = tickMarkLabel(with: nextTickLabelString, originX: nextTickXPosition) nextTickLabelFrame = nextTickLabel.frame } // Check whether labels overlap with each other or not. if let currentTickLabelFrame = currentTickLabelFrame, let nextTickLabelFrame = nextTickLabelFrame { if currentTickLabelFrame.maxX + paddingBetweenLabels > nextTickLabelFrame.minX { doMajorTickLabelsCollide = true break } } } if !doMajorTickLabelsCollide { // // The ticks don't at the given interval, so use that majorTickInterval = prospectiveInterval break } } if doMajorTickLabelsCollide { // // Multiple major tick labels won't fit without overlapping. // Display one major tick in the middle instead majorTickInterval = tickCount // Calculate the index of the middle tick. Note that, if there are an even number of ticks, there // is not one perfectly centered. This logic takes the one before the true center of the slider. if tickCount % 2 == 0 { firstMajorTickIndex = Int(trunc(Double(tickCount) / 2) - 1) } else { firstMajorTickIndex = Int(trunc(Double(tickCount) / 2)) } } } // Remove existing tick mark labels // from layer so we can add new ones. removeTickMarkLabels() // Add tick mark labels except // start and end tick marks. for i in 1..<tickCount - 1 { // // Get the tick mark let tickMark = tms[i] // Calculate whether it is a major tick or not. tickMark.isMajorTick = (i - firstMajorTickIndex) % majorTickInterval == 0 // Get the label for tick mark and add it to the display. if let tickMarkDate = tickMark.value, let tickMarkXPosition = tickMark.originX, tickMark.isMajorTick { let tickMarkLabelString = string(for: tickMarkDate, style: timeStepIntervalLabelDateStyle) let label = tickMarkLabel(with: tickMarkLabelString, originX: tickMarkXPosition) tickMarkLabels.append(label) layer.addSublayer(label) } } } // Set tick marks array tickMarks = tms } // swiftlint:enable cyclomatic_complexity // MARK: - Observer private func addObservers() { if isObserving { removeObservers() } // Observe operationalLayers of map mapLayersObservation = map?.observe(\.operationalLayers, options: [.new, .old]) { [weak self] (_, change) in // // Handle the change in operationalLayers self?.handleOperationalLayers(change: change) } // Observe operationalLayers of map sceneLayersObservation = scene?.observe(\.operationalLayers, options: [.new, .old]) { [weak self] (_, change) in // // Handle the change in operationalLayers self?.handleOperationalLayers(change: change) } timeExtentObservation = geoView?.observe(\.timeExtent, options: .new) { [weak self] (_, _) in // // Make sure self is around guard let self = self else { return } // Update slider's currentExtent with geoView's timeExtent if let geoViewTimeExtent = self.geoView?.timeExtent, let currentExtent = self.currentExtent { if geoViewTimeExtent.startTime?.timeIntervalSince1970 != currentExtent.startTime?.timeIntervalSince1970 || geoViewTimeExtent.endTime?.timeIntervalSince1970 != currentExtent.endTime?.timeIntervalSince1970 { self.currentExtent = geoViewTimeExtent } } } // Set the flag isObserving = true } private func removeObservers() { if isObserving { mapLayersObservation?.invalidate() mapLayersObservation = nil sceneLayersObservation?.invalidate() sceneLayersObservation = nil timeExtentObservation?.invalidate() timeExtentObservation = nil isObserving = false } } // MARK: - Helper Functions private func value(for position: Double) -> Double { // // Bail out if full extent start and end times are not available var resultValue: Double = 0.0 guard let fullExtentStartTime = fullExtent?.startTime, let fullExtentEndTime = fullExtent?.endTime else { return resultValue } // Find percentage of the position on the slider let percentage: CGFloat = (CGFloat(position) - trackLayer.bounds.minX - (thumbSize.width / 2.0)) / (trackLayer.bounds.maxX + (thumbSize.width / 2.0) - trackLayer.bounds.minX - (thumbSize.width / 2.0)) // Calculate the value based on percentage if !percentage.isNaN { resultValue = Double(percentage) * (fullExtentEndTime.timeIntervalSince1970 - fullExtentStartTime.timeIntervalSince1970) + fullExtentStartTime.timeIntervalSince1970 } // Return result return resultValue } fileprivate func position(for value: Double) -> Double { // // Bail out if full extent start and end times are not available var resultPosition: Double = 0.0 guard let fullExtentStartTime = fullExtent?.startTime, let fullExtentEndTime = fullExtent?.endTime, fullExtentStartTime != fullExtentEndTime else { return resultPosition } // Calculate the position based on value let position = Double(trackLayer.bounds.width) * (value - fullExtentStartTime.timeIntervalSince1970) / (fullExtentEndTime.timeIntervalSince1970 - fullExtentStartTime.timeIntervalSince1970) if !position.isNaN { resultPosition = position } // Return result return resultPosition } private func boundCurrentExtentStartTime(value: Double) -> Double { // // Result value var resultValue: Double = 0.0 // If range is enabled valid value needs to be between // full extent start time and current extent end time. if isRangeEnabled { // // Bail out if start and end times are not available guard let startTime = fullExtent?.startTime, let endTime = currentExtent?.endTime else { return resultValue } // Get the result value resultValue = min(max(value, startTime.timeIntervalSince1970), endTime.timeIntervalSince1970) } else { // Else, the valid value needs to be between full extent start and end times. // // Bail out if start and end times are not available guard let startTime = fullExtent?.startTime, let endTime = fullExtent?.endTime else { return resultValue } // Get the result value resultValue = min(max(value, startTime.timeIntervalSince1970), endTime.timeIntervalSince1970) } // Return result return resultValue } private func boundCurrentExtentEndTime(value: Double) -> Double { // // The valid value needs to be between current // extent start and full extent end times. // Bail out if they are not available. var resultValue: Double = 0.0 guard let startTime = currentExtent?.startTime, let endTime = fullExtent?.endTime else { return resultValue } // Get the result value resultValue = min(max(value, startTime.timeIntervalSince1970), endTime.timeIntervalSince1970) // Return result return resultValue } private func calculateTimeSteps() { // // To calculate the time steps, full extent's start time, end time and valid time step interval must be available. // Bail out if they are not available. guard let fullExtentStartTime = fullExtent?.startTime, let fullExtentEndTime = fullExtent?.endTime, let timeInterval = timeStepInterval, timeInterval.duration > 0.0, let (duration, component) = timeInterval.toCalenderComponents() else { return } // Get the date range from the start and end times. let calendar = Calendar(identifier: .gregorian) let dateRange = calendar.dateRange(startDate: fullExtentStartTime, endDate: fullExtentEndTime, component: component, step: Int(duration)) // Set time steps from the date range timeSteps = Array(dateRange) } private func tickMarkLabel(with string: String, originX: CGFloat) -> CATextLayer { // // Set label properties let tickMarkLabel = CATextLayer() tickMarkLabel.foregroundColor = timeStepIntervalLabelColor.cgColor tickMarkLabel.alignmentMode = CATextLayerAlignmentMode.center tickMarkLabel.frame = CGRect.zero tickMarkLabel.contentsScale = UIScreen.main.scale tickMarkLabel.font = timeStepIntervalLabelFont as CFTypeRef tickMarkLabel.fontSize = timeStepIntervalLabelFont.pointSize tickMarkLabel.string = string // Calculate the size of the label based on the string and font let tickMarkLabelSize: CGSize = string.size(withAttributes: [kCTFontAttributeName as NSAttributedString.Key: timeStepIntervalLabelFont]) // Calculate label's x position let tickMarkLayerOriginDifference = tickMarkLayer.frame.minX - layer.frame.minX let labelOriginX = (originX + tickMarkLayerOriginDifference + labelSidePadding) - (tickMarkLabelSize.width / 2.0) // The tick mark labels are displayed on the top side of the slider track. // So, it's y position needs to be minimum value of calculated either based on // tick mark layer or thumb size. let layerOriginY = tickMarkLayer.frame.minY - tickMarkLabelSize.height - labelPadding let thumbOriginY = lowerThumbLayer.frame.minY - tickMarkLabelSize.height - labelPadding let originY = min(layerOriginY, thumbOriginY) // Set the label frame tickMarkLabel.frame = CGRect(x: labelOriginX, y: originY, width: tickMarkLabelSize.width, height: tickMarkLabelSize.height) // Return label return tickMarkLabel } private func closestTimeStep(for date: Date) -> (index: Int, date: Date)? { // // Return nil if not able to find the closest time step for the provided date. guard let closest = timeSteps?.enumerated().min( by: { abs($0.1.timeIntervalSince1970 - date.timeIntervalSince1970) < abs($1.1.timeIntervalSince1970 - date.timeIntervalSince1970) }) else { return nil } // Return closes date and it's index return (closest.offset, closest.element) } private func removeTickMarkLabels() { // // Remove layers from the view tickMarkLabels.forEach { (tickMarkLabel) in tickMarkLabel.removeFromSuperlayer() } // Clear the array tickMarkLabels.removeAll() } // Notifies the change in value of current extent private func notifyChangeOfCurrentExtent() { // // Notify only if current date are different than previous dates. if previousCurrentExtentStartTime != currentExtentStartTime || previousCurrentExtentEndTime != currentExtentEndTime { // // Update previous values previousCurrentExtentStartTime = currentExtentStartTime previousCurrentExtentEndTime = currentExtentEndTime // Notify the change of dates sendActions(for: .valueChanged) // If geoView is available and is being observed // then update it's time extent if let geoView = geoView, observeGeoView { geoView.timeExtent = currentExtent } } } private func updateCurrentExtent(_ timeExtent: AGSTimeExtent) { // // Set a flag that this is an internal update // so we don't update the isRangeEnabled flag internalUpdate = true currentExtent = timeExtent internalUpdate = false } private func updateCurrentExtentStartTime(_ startTime: Date) { // // Make sure the time is within full extent let startTime = Date(timeIntervalSince1970: boundCurrentExtentStartTime(value: startTime.timeIntervalSince1970)) // If time steps are available then snap it to the closest time step and set the index. if let ts = timeSteps, !ts.isEmpty { if let (index, date) = closestTimeStep(for: startTime) { currentExtentStartTime = date startTimeStepIndex = index } } else { currentExtentStartTime = startTime startTimeStepIndex = -1 } } private func updateCurrentExtentEndTime(_ endTime: Date) { // // Make sure the time is within full extent let endTime = Date(timeIntervalSince1970: boundCurrentExtentEndTime(value: endTime.timeIntervalSince1970)) // If time steps are available then snap it to the closest time step and set the index. if let ts = timeSteps, !ts.isEmpty { if let (index, date) = closestTimeStep(for: endTime) { currentExtentEndTime = date endTimeStepIndex = index } } else { currentExtentEndTime = endTime endTimeStepIndex = -1 } } // This function returns time step interval and whether given layer supports range time filtering or not. // swiftlint:disable cyclomatic_complexity private func findTimeStepIntervalAndIsRangeTimeFilteringSupported(for timeAwareLayer: AGSTimeAware, completion: @escaping ((timeStepInterval: AGSTimeValue?, supportsRangeTimeFiltering: Bool)) -> Void) { // // The default is false var supportsRangeTimeFiltering = false // Get the time interval of the layer var timeStepInterval = timeAwareLayer.timeInterval // If the layer is map image layer then we need to find out details from the // sublayers. Let's load all sublayers and check whether sub layers supports // range time filtering and largets time step interval. if let mapImageLayer = timeAwareLayer as? AGSArcGISMapImageLayer { AGSLoadObjects(mapImageLayer.mapImageSublayers as! [AGSLoadable]) { [weak self] (loaded) in // Make sure self is around guard let self = self else { return } if loaded { var timeInterval: AGSTimeValue? for i in 0..<mapImageLayer.mapImageSublayers.count { if let sublayer = mapImageLayer.mapImageSublayers[i] as? AGSArcGISSublayer, sublayer.isVisible, let timeInfo = self.timeInfo(for: sublayer) { // // If either start or end time field name is not available then // set supportsRangeTimeFiltering to false if timeInfo.startTimeField.isEmpty || timeInfo.endTimeField.isEmpty { supportsRangeTimeFiltering = false } // Need to find the largest time step interval from // sub layers only if it is not available on the layer. if timeStepInterval == nil, let interval1 = timeInfo.interval { if let interval2 = timeInterval { if interval1 > interval2 { timeInterval = interval1 } } else { timeInterval = interval1 } } } } // Update largest time step interval // found from sub layers. if timeStepInterval == nil, let timeInterval = timeInterval { timeStepInterval = timeInterval } } completion((timeStepInterval, supportsRangeTimeFiltering)) } } else { // // If layer is not map image layer then find layer supports // range time filtering or not and set time step interval // from timeInfo if not available on the layer. if let timeAwareLayer = timeAwareLayer as? AGSLoadable, let timeInfo = timeInfo(for: timeAwareLayer) { if timeInfo.startTimeField.isEmpty || timeInfo.endTimeField.isEmpty { supportsRangeTimeFiltering = false } } completion((timeStepInterval, supportsRangeTimeFiltering)) } } // swiftlint:enable cyclomatic_complexity // Returns layer's time info if available. The parameter cannot be of type AGSLayer because // ArcGISSublayer does not inherit from AGSLayer. It is expected that this function is // called on already loaded object private func timeInfo(for layer: AGSLoadable) -> AGSLayerTimeInfo? { // // The timeInfo is available on only raster, feature or sub layer. // // It is expected that this function is // called on already loaded object if layer.loadStatus == .loaded { if let sublayer = layer as? AGSArcGISSublayer { return sublayer.mapServiceSublayerInfo?.timeInfo } else if let featureLayer = layer as? AGSFeatureLayer, let featureTable = featureLayer.featureTable as? AGSArcGISFeatureTable { return featureTable.layerInfo?.timeInfo } else if let rasterLayer = layer as? AGSRasterLayer, let imageServiceRaster = rasterLayer.raster as? AGSImageServiceRaster { return imageServiceRaster.serviceInfo?.timeInfo } } return nil } // This function handles change in operationalLayers // and re-initialize time slider if required private func handleOperationalLayers(change: NSKeyValueObservedChange<NSMutableArray>) { // // Make sure change contains time aware layer guard let geoView = geoView, changeContainsTimeAwareLayer(change: change) else { return } // Re initialize time slider reInitializeTimeProperties = true initializeTimeProperties(geoView: geoView, observeGeoView: observeGeoView) { [weak self] (error) in // // Bail out if there is an error guard error == nil else { return } // Set the flag self?.reInitializeTimeProperties = false } } // This function checks whether the observed value of operationalLayers // contains any time aware layer. private func changeContainsTimeAwareLayer(change: NSKeyValueObservedChange<NSMutableArray>) -> Bool { let newValue = change.newValue as? [AGSLayer] let oldValue = change.oldValue as? [AGSLayer] let changedIndexes = change.indexes if let newValue = newValue, newValue.contains(where: { $0 is AGSTimeAware }) { return true } if let oldValue = oldValue, oldValue.contains(where: { $0 is AGSTimeAware }) { return true } if let changedIndexes = changedIndexes, let operationalLayers = geoView?.operationalLayers, changedIndexes.contains(where: { operationalLayers[$0] is AGSTimeAware }) { return true } return false } // This function returns a string for the given date and date style // swiftlint:disable cyclomatic_complexity private func string(for date: Date, style: DateStyle) -> String { // // Create the date formatter to get the string for a date let dateFormatter = DateFormatter() dateFormatter.timeZone = timeZone switch style { case .dayShortMonthYear: dateFormatter.setLocalizedDateFormatFromTemplate("d MMM y") case .longDate: dateFormatter.setLocalizedDateFormatFromTemplate("EEEE, MMMM d, y") case .longMonthDayYear: dateFormatter.setLocalizedDateFormatFromTemplate("MMMM d y") case .longMonthYear: dateFormatter.setLocalizedDateFormatFromTemplate("MMMM y") case .shortDate: dateFormatter.setLocalizedDateFormatFromTemplate("M/d/y") case .shortDateLongTime: dateFormatter.setLocalizedDateFormatFromTemplate("M/d/y h:mm:ss a") case .shortDateLongTime24: dateFormatter.setLocalizedDateFormatFromTemplate("M/d/y H:mm:ss") case .shortDateShortTime: dateFormatter.setLocalizedDateFormatFromTemplate("M/d/y h:mm a") case .shortDateShortTime24: dateFormatter.setLocalizedDateFormatFromTemplate("M/d/y h:mm a") case .shortMonthYear: dateFormatter.setLocalizedDateFormatFromTemplate("MMM y") case .year: dateFormatter.setLocalizedDateFormatFromTemplate("y") case .unknown: dateFormatter.setLocalizedDateFormatFromTemplate("M/d/y h:mm a") } return dateFormatter.string(from: date) } // swiftlint:enable cyclomatic_complexity // Calculates time step interval based on provided time extent and time step count private func calculateTimeStepInterval(for timeExtent: AGSTimeExtent, timeStepCount: Int) -> AGSTimeValue? { if let startTime = timeExtent.startTime, let endTime = timeExtent.endTime { // // Calculate time step interval based on time step count. // // Checking here for count to be greater than 1 to // avoid device-by-zero situation. if timeStepCount > 1 { let timeIntervalInSeconds = ((endTime.timeIntervalSince1970 - startTime.timeIntervalSince1970) / Double(timeStepCount - 1)) + startTime.timeIntervalSince1970 let timeIntervalDate = Date(timeIntervalSince1970: timeIntervalInSeconds) if let (duration, component) = timeIntervalDate.offset(from: startTime) { return AGSTimeValue.fromCalenderComponents(duration: Double(duration), component: component) } } else { if let startTime = timeExtent.startTime, let endTime = timeExtent.endTime { // // Since the time step count is 0 we'll use default duration 1 if let (_, component) = endTime.offset(from: startTime) { return AGSTimeValue.fromCalenderComponents(duration: 1, component: component) } } } } return nil } } // MARK: - Time Slider Thumb Layer private class TimeSliderThumbLayer: CALayer { var isHighlighted = false { didSet { setNeedsDisplay() } } var isPinned = false { didSet { setNeedsDisplay() } } weak var timeSlider: TimeSlider? override func draw(in ctx: CGContext) { guard let slider = timeSlider, slider.isSliderVisible else { return } var thumbFrame = bounds.insetBy(dx: 2.0, dy: 2.0) if isPinned { let size = CGSize(width: 8, height: 30) let origin = CGPoint(x: thumbFrame.midX - size.width / 2.0, y: thumbFrame.midY - size.height / 2.0) thumbFrame = CGRect(origin: origin, size: size) } let cornerRadius = thumbFrame.height * CGFloat(slider.thumbCornerRadius / 2.0) let thumbPath = UIBezierPath(roundedRect: thumbFrame, cornerRadius: cornerRadius) // Fill - with a subtle shadow let shadowColor = slider.thumbBorderColor.withAlphaComponent(0.4) let fillColor = isPinned ? slider.pinnedThumbFillColor.cgColor : slider.thumbFillColor.cgColor ctx.setShadow(offset: CGSize(width: 0.0, height: 1.0), blur: 1.0, color: shadowColor.cgColor) ctx.setFillColor(fillColor) ctx.addPath(thumbPath.cgPath) ctx.fillPath() // Outline ctx.setStrokeColor(slider.thumbBorderColor.cgColor) ctx.setLineWidth(slider.thumbBorderWidth) ctx.addPath(thumbPath.cgPath) ctx.strokePath() if isHighlighted { ctx.setFillColor(UIColor(white: 0.0, alpha: 0.1).cgColor) ctx.addPath(thumbPath.cgPath) ctx.fillPath() } } } // MARK: - Time Slider Track Layer private class TimeSliderTrackLayer: CALayer { weak var timeSlider: TimeSlider? override func draw(in ctx: CGContext) { guard let slider = timeSlider, slider.isSliderVisible else { return } // // Clip let path = UIBezierPath(roundedRect: bounds, cornerRadius: 0.0) ctx.addPath(path.cgPath) // Fill the track ctx.setFillColor(slider.fullExtentFillColor.cgColor) ctx.addPath(path.cgPath) ctx.fillPath() // Outline let outlineWidth = slider.fullExtentBorderWidth ctx.setStrokeColor(slider.fullExtentBorderColor.cgColor) ctx.setLineWidth(outlineWidth) ctx.addPath(path.cgPath) ctx.strokePath() // Fill the layer track if let startTime = slider.layerExtent?.startTime, let endTime = slider.layerExtent?.endTime { let lowerValuePosition = CGFloat(slider.position(for: startTime.timeIntervalSince1970)) let upperValuePosition = CGFloat(slider.position(for: endTime.timeIntervalSince1970)) let rect = CGRect(x: lowerValuePosition, y: outlineWidth / 2.0, width: upperValuePosition - lowerValuePosition, height: bounds.height - outlineWidth) ctx.setFillColor(slider.layerExtentFillColor.cgColor) ctx.fill(rect) } // Fill the highlighted range ctx.setFillColor(slider.currentExtentFillColor.cgColor) if let startTime = slider.currentExtent?.startTime, let endTime = slider.currentExtent?.endTime { let lowerValuePosition = CGFloat(slider.position(for: startTime.timeIntervalSince1970)) let upperValuePosition = CGFloat(slider.position(for: endTime.timeIntervalSince1970)) let rect = CGRect(x: lowerValuePosition, y: outlineWidth, width: upperValuePosition - lowerValuePosition, height: bounds.height - (outlineWidth * 2.0)) ctx.fill(rect) } } } // MARK: - Time Slider Tick Layer private class TimeSliderTickMarkLayer: CALayer { weak var timeSlider: TimeSlider? private let endTickLinWidth: CGFloat = 6.0 private let intermediateTickLinWidth: CGFloat = 2.0 private let paddingBetweenTickMarks: CGFloat = 4.0 override func draw(in ctx: CGContext) { guard let slider = timeSlider, slider.isSliderVisible, slider.tickMarks.isEmpty == false else { return } // // Clip let path = UIBezierPath(rect: bounds) ctx.addPath(path.cgPath) // Get the tick marks count let tickMarksCount = slider.tickMarks.count // Set the tick color ctx.setStrokeColor(slider.timeStepIntervalTickColor.cgColor) // If there is not enough space to // render all tick marks then only // render first and last. if !isThereEnoughSpaceForTickMarks() { ctx.setLineWidth(endTickLinWidth) // Get the first and last tick mark origins var tickMarksOriginX = [CGFloat]() if let firstTickX = slider.tickMarks.first?.originX, let lastTickX = slider.tickMarks.last?.originX { tickMarksOriginX.append(firstTickX) tickMarksOriginX.append(lastTickX) } // Render tick marks tickMarksOriginX.forEach { (tickX) in ctx.beginPath() ctx.move(to: CGPoint(x: CGFloat(tickX), y: bounds.midY - (slider.trackHeight / 2.0))) ctx.addLine(to: CGPoint(x: CGFloat(tickX), y: bounds.midY + bounds.height / 2.0)) ctx.strokePath() } } else { // Loop through all tick marks // and render them. for i in 0..<tickMarksCount { let tickMark = slider.tickMarks[i] if let tickX = tickMark.originX { ctx.beginPath() // First and last tick marks are // rendered differently than others if i == 0 || i == tickMarksCount - 1 { ctx.setLineWidth(endTickLinWidth) ctx.move(to: CGPoint(x: CGFloat(tickX), y: bounds.midY - (slider.trackHeight / 2.0))) ctx.addLine(to: CGPoint(x: CGFloat(tickX), y: bounds.midY + bounds.height / 2.0)) } else { ctx.setLineWidth(intermediateTickLinWidth) ctx.move(to: CGPoint(x: CGFloat(tickX), y: bounds.midY - (slider.trackHeight / 2.0))) let tickY = tickMark.isMajorTick ? bounds.midY - bounds.height / 2.0 : bounds.midY - bounds.height / 3.0 ctx.addLine(to: CGPoint(x: CGFloat(tickX), y: tickY)) } ctx.strokePath() } } } } // Checks whether there is enough space to render all tick marks private func isThereEnoughSpaceForTickMarks() -> Bool { guard let slider = timeSlider, slider.tickMarks.isEmpty == false else { return false } let tickMarksCount = slider.tickMarks.count let requiredSpace = (CGFloat(tickMarksCount - 2) * (intermediateTickLinWidth + paddingBetweenTickMarks)) + (endTickLinWidth * 2.0) let availableSpace = bounds.width if availableSpace > requiredSpace { return true } return false } } // MARK: - Tick Mark private class TickMark { var originX: CGFloat? var value: Date? var isMajorTick: Bool = false init(originX: CGFloat, value: Date) { self.originX = originX self.value = value } } // MARK: - Calendar private extension Calendar { // // Returns a date range between two provided dates with given component and step value func dateRange(startDate: Date, endDate: Date, component: Calendar.Component, step: Int) -> DateRange { let dateRange = DateRange(calendar: self, startDate: startDate, endDate: endDate, component: component, step: step, multiplier: 0, inclusive: true) return dateRange } } // MARK: - Date Range private struct DateRange: Sequence, IteratorProtocol { var calendar: Calendar var startDate: Date var endDate: Date var component: Calendar.Component var step: Int var multiplier: Int var inclusive: Bool private func toSeconds(duration: Double, component: Calendar.Component) -> TimeInterval { switch component { case .year: return TimeInterval(duration * 31556952) case .month: return TimeInterval(duration * 2629746) case .day: return TimeInterval(duration * 86400) case .hour: return TimeInterval(duration * 3600) case .minute: return TimeInterval(duration * 60) case .second: return TimeInterval(duration) case .nanosecond: return TimeInterval(duration / 1000000000) default: break } return 0 } mutating func next() -> Date? { guard let nextDate = calendar.date(byAdding: component, value: step * multiplier, to: startDate) else { return nil } // If next date + half of the step value is greater than end date then return end date. // This will avoid the date being too close to the end date. if nextDate.timeIntervalSince1970 + (toSeconds(duration: Double(step), component: component) / 2.0) >= endDate.timeIntervalSince1970 { if inclusive { inclusive = false return endDate } else { return nil } } else { multiplier += 1 return nextDate } } } // MARK: - Date Extension fileprivate extension Date { // // Returns the amount of years from another date func years(from date: Date) -> Int { return Calendar.current.dateComponents([.year], from: date, to: self).year ?? 0 } // Returns the amount of months from another date func months(from date: Date) -> Int { return Calendar.current.dateComponents([.month], from: date, to: self).month ?? 0 } // Returns the amount of days from another date func days(from date: Date) -> Int { return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0 } // Returns the amount of hours from another date func hours(from date: Date) -> Int { return Calendar.current.dateComponents([.hour], from: date, to: self).hour ?? 0 } // Returns the amount of minutes from another date func minutes(from date: Date) -> Int { return Calendar.current.dateComponents([.minute], from: date, to: self).minute ?? 0 } // Returns the amount of seconds from another date func seconds(from date: Date) -> Int { return Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0 } // Returns the amount of nanoseconds from another date func nanoseconds(from date: Date) -> Int { return Calendar.current.dateComponents([.nanosecond], from: date, to: self).nanosecond ?? 0 } // Returns the a custom time interval and calender component from another date func offset(from date: Date) -> (duration: Int, component: Calendar.Component)? { if years(from: date) > 0 { return (years(from: date), .year) } if months(from: date) > 0 { return (months(from: date), .month) } if seconds(from: date) > 0 { return (seconds(from: date), .second) } if nanoseconds(from: date) > 0 { return (nanoseconds(from: date), .nanosecond) } return nil } } // MARK: - Color Extension extension UIColor { class var oceanBlue: UIColor { return UIColor(red: 0.0, green: 0.475, blue: 0.757, alpha: 1) } class var customBlue: UIColor { return UIColor(red: 0.0, green: 0.45, blue: 0.94, alpha: 1.0) } class var lightSkyBlue: UIColor { return UIColor(red: 0.529, green: 0.807, blue: 0.980, alpha: 1.0) } } // MARK: - Time Extent Extension extension AGSTimeExtent { // // Union of two time extents func union(otherTimeExtent: AGSTimeExtent) -> AGSTimeExtent { guard let startTime = startTime, let endTime = endTime, let otherStartTime = otherTimeExtent.startTime, let otherEndTime = otherTimeExtent.endTime else { return self } let newStartTime = min(startTime, otherStartTime) let newEndTime = max(endTime, otherEndTime) return AGSTimeExtent(startTime: newStartTime, endTime: newEndTime) } } // MARK: - Time Value Extension extension AGSTimeValue: Comparable { // // Converts time value to seconds public var toSeconds: TimeInterval { switch unit { case .unknown: return duration case .centuries: return duration * 3155695200 case .days: return duration * 86400 case .decades: return duration * 315569520 case .hours: return duration * 3600 case .milliseconds: return duration * 0.001 case .minutes: return duration * 60 case .months: return duration * 2629746 case .seconds: return duration case .weeks: return duration * 604800 case .years: return duration * 31556952 @unknown default: fatalError("Unknown AGSTimeValue.unit") } } // Converts time value to the calender component values. // swiftlint:disable cyclomatic_complexity public func toCalenderComponents() -> (duration: Double, component: Calendar.Component)? { switch unit { case .unknown: return nil case .centuries: return (duration * 100, Calendar.Component.year) case .days: return (duration, Calendar.Component.day) case .decades: return (duration * 10, Calendar.Component.year) case .hours: return (duration, Calendar.Component.hour) case .milliseconds: return (duration * 1000000, Calendar.Component.nanosecond) case .minutes: return (duration, Calendar.Component.minute) case .months: return (duration, Calendar.Component.month) case .seconds: return (duration, Calendar.Component.second) case .weeks: return (duration * 7, Calendar.Component.day) case .years: return (duration, Calendar.Component.year) @unknown default: fatalError("Unknown AGSTimeValue.unit") } } // swiftlint:enable cyclomatic_complexity // Returns time value generated from calender component and duration class func fromCalenderComponents(duration: Double, component: Calendar.Component) -> AGSTimeValue? { switch component { case .era: break case .year: return AGSTimeValue(duration: duration, unit: .years) case .month: return AGSTimeValue(duration: duration, unit: .months) case .day: return AGSTimeValue(duration: duration, unit: .days) case .hour: return AGSTimeValue(duration: duration, unit: .hours) case .minute: return AGSTimeValue(duration: duration, unit: .minutes) case .second: return AGSTimeValue(duration: duration, unit: .seconds) case .nanosecond: return AGSTimeValue(duration: duration / 1000000, unit: .milliseconds) default: break } return nil } // MARK: - Comparable public static func < (lhs: AGSTimeValue, rhs: AGSTimeValue) -> Bool { if lhs.unit == rhs.unit { return lhs.duration < rhs.duration } return lhs.toSeconds < rhs.toSeconds } public static func > (lhs: AGSTimeValue, rhs: AGSTimeValue) -> Bool { if lhs.unit == rhs.unit { return lhs.duration > rhs.duration } return lhs.toSeconds > rhs.toSeconds } public static func == (lhs: AGSTimeValue, rhs: AGSTimeValue) -> Bool { if lhs.unit == rhs.unit { return lhs.duration == rhs.duration } return lhs.toSeconds == rhs.toSeconds } } // MARK: - GeoView Extension fileprivate extension AGSGeoView { var operationalLayers: [AGSLayer]? { if let mapView = self as? AGSMapView { if let layers = mapView.map?.operationalLayers as AnyObject as? [AGSLayer] { return layers } } else if let sceneView = self as? AGSSceneView { if let layers = sceneView.scene?.operationalLayers as AnyObject as? [AGSLayer] { return layers } } return nil } }
41.362114
319
0.602456
03975f2fcfd8f0575c449e97a7eb5c2e9ee20b86
12,233
// // StereoViewController.swift // MetalScope // // Created by Jun Tanaka on 2017/01/23. // Copyright © 2017 eje Inc. All rights reserved. // import UIKit import SceneKit open class StereoViewController: UIViewController, SceneLoadable { #if (arch(arm) || arch(arm64)) && os(iOS) public let device: MTLDevice #endif public weak var delegate: SceneLoadingDelegate? open var scene: SCNScene? { didSet { _stereoView?.scene = scene delegate?.sceneDidLoad(scene) } } open var stereoParameters: StereoParametersProtocol = StereoParameters() { didSet { _stereoView?.stereoParameters = stereoParameters } } open var stereoView: StereoView { if !isViewLoaded { loadView() } guard let view = _stereoView else { fatalError("Unexpected context to load stereoView") } return view } open var showsCloseButton: Bool = true { didSet { _closeButton?.isHidden = !showsCloseButton } } open var closeButton: UIButton { if _closeButton == nil { loadCloseButton() } guard let button = _closeButton else { fatalError("Unexpected context to load closeButton") } return button } open var closeButtonHandler: ((_ sender: UIButton) -> Void)? open var showsHelpButton: Bool = false { didSet { _helpButton?.isHidden = !showsHelpButton } } open var helpButton: UIButton { if _helpButton == nil { loadHelpButton() } guard let button = _helpButton else { fatalError("Unexpected context to load helpButton") } return button } open var helpButtonHandler: ((_ sender: UIButton) -> Void)? open var introductionView: UIView? { willSet { introductionView?.removeFromSuperview() } didSet { guard isViewLoaded else { return } if let _ = introductionView { showIntroductionView() } else { hideIntroductionView() } } } private weak var _stereoView: StereoView? private weak var _closeButton: UIButton? private weak var _helpButton: UIButton? private weak var introdutionContainerView: UIView? private var introductionViewUpdateTimer: DispatchSourceTimer? #if (arch(arm) || arch(arm64)) && os(iOS) public init(device: MTLDevice) { self.device = device super.init(nibName: nil, bundle: nil) } #else public init() { super.init(nibName: nil, bundle: nil) } #endif public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func loadView() { #if (arch(arm) || arch(arm64)) && os(iOS) let stereoView = StereoView(device: device) #else let stereoView = StereoView() #endif stereoView.backgroundColor = .black stereoView.scene = scene stereoView.stereoParameters = stereoParameters stereoView.translatesAutoresizingMaskIntoConstraints = false stereoView.isPlaying = false _stereoView = stereoView let introductionContainerView = UIView(frame: stereoView.bounds) introductionContainerView.isHidden = true self.introdutionContainerView = introductionContainerView let view = UIView(frame: stereoView.bounds) view.backgroundColor = .black view.addSubview(stereoView) view.addSubview(introductionContainerView) self.view = view NSLayoutConstraint.activate([ stereoView.topAnchor.constraint(equalTo: view.topAnchor), stereoView.bottomAnchor.constraint(equalTo: view.bottomAnchor), stereoView.leadingAnchor.constraint(equalTo: view.leadingAnchor), stereoView.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) if showsCloseButton { loadCloseButton() } if showsHelpButton { loadHelpButton() } } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() introdutionContainerView!.bounds = view!.bounds introdutionContainerView!.center = CGPoint(x: view!.bounds.midX, y: view!.bounds.midY) introductionView?.frame = introdutionContainerView!.bounds } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if animated { _stereoView?.alpha = 0 } } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) _stereoView?.isPlaying = true if animated { UIView.animate(withDuration: 0.2) { self._stereoView?.alpha = 1 } } if UIDevice.current.orientation != .unknown { showIntroductionView(animated: animated) startIntroductionViewVisibilityUpdates() } } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) _stereoView?.isPlaying = false stopIntroductionViewVisibilityUpdates() } open override var prefersStatusBarHidden: Bool { return true } open override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .landscapeRight } private func loadCloseButton() { if !isViewLoaded { loadView() } let icon = UIImage(named: "icon-close", in: Bundle(for: StereoViewController.self), compatibleWith: nil) let closeButton = UIButton(type: .system) closeButton.setImage(icon, for: .normal) closeButton.isHidden = !showsCloseButton closeButton.contentVerticalAlignment = .top closeButton.contentHorizontalAlignment = .left closeButton.contentEdgeInsets = UIEdgeInsets(top: 11, left: 11, bottom: 0, right: 0) closeButton.translatesAutoresizingMaskIntoConstraints = false _closeButton = closeButton view.addSubview(closeButton) NSLayoutConstraint.activate([ closeButton.widthAnchor.constraint(equalToConstant: 88), closeButton.heightAnchor.constraint(equalToConstant: 88), closeButton.topAnchor.constraint(equalTo: view.topAnchor), closeButton.leadingAnchor.constraint(equalTo: view.leadingAnchor) ]) closeButton.addTarget(self, action: #selector(handleTapOnCloseButton(_:)), for: .touchUpInside) } @objc private func handleTapOnCloseButton(_ sender: UIButton) { if let handler = closeButtonHandler { handler(sender) } else if sender.allTargets.count == 1 { presentingViewController?.dismiss(animated: true, completion: nil) } } private func loadHelpButton() { if !isViewLoaded { loadView() } let icon = UIImage(named: "icon-help", in: Bundle(for: StereoViewController.self), compatibleWith: nil) let helpButton = UIButton(type: .system) helpButton.setImage(icon, for: .normal) helpButton.isHidden = !showsHelpButton helpButton.contentVerticalAlignment = .top helpButton.contentHorizontalAlignment = .right helpButton.contentEdgeInsets = UIEdgeInsets(top: 11, left: 0, bottom: 0, right: 11) helpButton.translatesAutoresizingMaskIntoConstraints = false _helpButton = helpButton view.addSubview(helpButton) NSLayoutConstraint.activate([ helpButton.widthAnchor.constraint(equalToConstant: 88), helpButton.heightAnchor.constraint(equalToConstant: 88), helpButton.topAnchor.constraint(equalTo: view.topAnchor), helpButton.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) helpButton.addTarget(self, action: #selector(handleTapOnHelpButton(_:)), for: .touchUpInside) } @objc private func handleTapOnHelpButton(_ sender: UIButton) { if let handler = helpButtonHandler { handler(sender) } else if sender.allTargets.count == 1 { let url = URL(string: "https://support.google.com/cardboard/answer/6383058")! UIApplication.shared.open(url, options: [:], completionHandler: nil) } } private func showIntroductionView(animated: Bool = false) { precondition(isViewLoaded) guard let introductionView = introductionView, let containerView = introdutionContainerView, let stereoView = _stereoView else { return } if introductionView.superview != containerView { introductionView.frame = containerView.bounds introductionView.autoresizingMask = [] containerView.addSubview(introductionView) } if animated { if containerView.isHidden { containerView.isHidden = false containerView.transform = CGAffineTransform(translationX: 0, y: containerView.bounds.height) } UIView.animate( withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [.beginFromCurrentState], animations: { containerView.transform = .identity stereoView.alpha = 0 }, completion: nil) } else { containerView.isHidden = false containerView.transform = .identity stereoView.alpha = 0 } } private func hideIntroductionView(animated: Bool = false) { precondition(isViewLoaded) guard let containerView = introdutionContainerView, let stereoView = _stereoView else { return } if animated { UIView.animate( withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [.beginFromCurrentState], animations: { containerView.transform = CGAffineTransform(translationX: 0, y: containerView.bounds.height) stereoView.alpha = 1 }, completion: { isFinished in guard isFinished else { return } containerView.isHidden = true containerView.transform = .identity }) } else { containerView.isHidden = true containerView.transform = .identity stereoView.alpha = 1 } } private func startIntroductionViewVisibilityUpdates(withInterval interval: TimeInterval = 3, afterDelay delay: TimeInterval = 3) { precondition(introductionViewUpdateTimer == nil) let timer = DispatchSource.makeTimerSource(queue: .main) timer.schedule(deadline: .now() + delay, repeating: interval) timer.setEventHandler { [weak self] in guard self?.isViewLoaded == true, let _ = self?.introductionView else { return } switch UIDevice.current.orientation { case .landscapeLeft where self?.introdutionContainerView?.isHidden == false: self?.hideIntroductionView(animated: true) case .landscapeRight where self?.introdutionContainerView?.isHidden == true: self?.showIntroductionView(animated: true) default: break } } timer.resume() introductionViewUpdateTimer = timer } private func stopIntroductionViewVisibilityUpdates() { introductionViewUpdateTimer?.cancel() introductionViewUpdateTimer = nil } } extension StereoViewController: ImageLoadable {} #if (arch(arm) || arch(arm64)) && os(iOS) extension StereoViewController: VideoLoadable {} #endif
32.107612
136
0.614894
69cb8c14df10db22f5437850c91447356df6fde0
7,539
// // NewDocumentPhotosViewController.swift // zScanner // // Created by Jakub Skořepa on 14/08/2019. // Copyright © 2019 Institut klinické a experimentální medicíny. All rights reserved. // import UIKit import RxSwift protocol NewDocumentPhotosCoordinator: BaseCoordinator { func savePhotos(_ photos: [UIImage]) func showNextStep() } // MARK: - class NewDocumentPhotosViewController: BaseViewController { // MARK: Instance part private unowned let coordinator: NewDocumentPhotosCoordinator private let viewModel: NewDocumentPhotosViewModel init(viewModel: NewDocumentPhotosViewModel, coordinator: NewDocumentPhotosCoordinator) { self.coordinator = coordinator self.viewModel = viewModel super.init(coordinator: coordinator) } // MARK: Lifecycle override func loadView() { super.loadView() setupView() } override func viewDidLoad() { super.viewDidLoad() setupBindings() } override var rightBarButtonItems: [UIBarButtonItem] { return [ UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(takeNewPicture)) ] } // MARK: Helpers let disposeBag = DisposeBag() @objc private func takeNewPicture() { showActionSheet() } private func showActionSheet() { let alert = UIAlertController(title: "newDocumentPhotos.actioSheet.title".localized, message: nil, preferredStyle: .actionSheet) if UIImagePickerController.isSourceTypeAvailable(.camera) { alert.addAction(UIAlertAction(title: "newDocumentPhotos.actioSheet.cameraAction".localized, style: .default, handler: { _ in self.openCamera() })) } alert.addAction(UIAlertAction(title: "newDocumentPhotos.actioSheet.galleryAction".localized, style: .default, handler: { _ in self.openGallery() })) alert.addAction(UIAlertAction.init(title: "newDocumentPhotos.actioSheet.cancel".localized, style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } private lazy var imagePicker: UIImagePickerController = { let picker = UIImagePickerController() picker.delegate = self return picker }() private func openCamera() { imagePicker.sourceType = .camera present(imagePicker, animated: true, completion: nil) } private func openGallery() { imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true, completion: nil) } private func setupBindings() { viewModel.pictures .bind( to: collectionView.rx.items(cellIdentifier: "PhotoSelectorCollectionViewCell", cellType: PhotoSelectorCollectionViewCell.self), curriedArgument: { [unowned self] (row, image, cell) in cell.setup(with: image, delegate: self) } ) .disposed(by: disposeBag) viewModel.pictures .subscribe(onNext: { [weak self] pictures in self?.collectionView.backgroundView?.isHidden = pictures.count > 0 }) .disposed(by: disposeBag) viewModel.pictures .map({ !$0.isEmpty }) .bind(to: continueButton.rx.isEnabled) .disposed(by: disposeBag) continueButton.rx.tap .subscribe(onNext: { [unowned self] in self.coordinator.savePhotos(self.viewModel.pictures.value) self.coordinator.showNextStep() }) .disposed(by: disposeBag) } private func setupView() { navigationItem.title = "newDocumentPhotos.screen.title".localized view.addSubview(collectionView) collectionView.snp.makeConstraints { make in make.edges.equalToSuperview() } view.addSubview(gradientView) gradientView.snp.makeConstraints { make in make.top.equalTo(safeArea.snp.bottom).offset(-80) make.right.bottom.left.equalToSuperview() } view.addSubview(continueButton) continueButton.snp.makeConstraints { make in make.right.bottom.left.equalTo(safeArea).inset(20) make.height.equalTo(44) } collectionView.backgroundView = emptyView emptyView.addSubview(emptyViewLabel) emptyViewLabel.snp.makeConstraints { make in make.width.equalToSuperview().multipliedBy(0.75) make.centerX.equalToSuperview() make.top.greaterThanOrEqualTo(collectionView.safeAreaLayoutGuide.snp.top) make.centerY.equalToSuperview().multipliedBy(0.666).priority(900) } } private lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout) collectionView.backgroundColor = .white collectionView.register(PhotoSelectorCollectionViewCell.self, forCellWithReuseIdentifier: "PhotoSelectorCollectionViewCell") return collectionView }() private lazy var continueButton: PrimaryButton = { let button = PrimaryButton() button.setTitle("newDocumentPhotos.button.title".localized, for: .normal) button.dropShadow() return button }() private lazy var emptyView = UIView() private lazy var emptyViewLabel: UILabel = { let label = UILabel() label.text = "newDocumentPhotos.emptyView.title".localized label.textColor = .black label.numberOfLines = 0 label.font = .body label.textAlignment = .center return label }() private lazy var gradientView = GradientView() private let margin: CGFloat = 10 private let numberofColumns: CGFloat = 2 private var itemWidth: CGFloat { let screenWidth = UIScreen.main.bounds.width return (screenWidth - (numberofColumns + 1) * margin) / numberofColumns } private lazy var flowLayout: UICollectionViewLayout = { let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: itemWidth, height: itemWidth) layout.scrollDirection = .vertical layout.minimumInteritemSpacing = margin layout.minimumLineSpacing = margin layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin) return layout }() } // MARK: - UIImagePickerControllerDelegate implementation extension NewDocumentPhotosViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { if let pickedImage = info[.originalImage] as? UIImage { viewModel.addImage(pickedImage, fromGallery: picker.sourceType == .photoLibrary) } self.dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { self.dismiss(animated: true, completion: nil) } } // MARK: - PhotoSelectorCellDelegate implementation extension NewDocumentPhotosViewController: PhotoSelectorCellDelegate { func delete(image: UIImage) { viewModel.removeImage(image) } }
34.582569
144
0.653137
67e2ef7d9efa25bb45925a5776d17d9190cc7b9b
317
// // AuthService.swift // Authenticator // // Created by Bastiaan Jansen on 09/12/2020. // import Foundation import LocalAuthentication import SwiftKeychainWrapper class PasscodeAuthService: AuthService { func authenticate(completion: (Bool, Error?) -> Void) { return completion(false, nil) } }
18.647059
59
0.716088
e41a5bd667a47502397b6b2a5eabdb9cfbd8c229
10,580
// // Formatter.swift // // Copyright (c) 2015-2019 Damien (http://delba.io) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // public enum Component { case date(String) case message case level case file(fullPath: Bool, fileExtension: Bool) case line case column case function case location case block(() -> Any?) } open class Formatters {} open class Formatter: Formatters { /// The formatter format. private var format: String /// The formatter components. private var components: [Component] /// The date formatter. private let dateFormatter = DateFormatter() /// The formatter logger. weak var logger: Logger? /// The formatter textual representation. var description: String { return String(format: format, arguments: components.map { (component: Component) -> CVarArg in return String(describing: component).uppercased() }) } /** Creates and returns a new formatter with the specified format and components. - parameter format: The formatter format. - parameter components: The formatter components. - returns: A newly created formatter. */ public convenience init(_ format: String, _ components: Component...) { self.init(format, components) } /** Creates and returns a new formatter with the specified format and components. - parameter format: The formatter format. - parameter components: The formatter components. - returns: A newly created formatter. */ public init(_ format: String, _ components: [Component]) { self.format = format self.components = components } /** Formats a string with the formatter format and components. - parameter level: The severity level. - parameter items: The items to format. - parameter separator: The separator between the items. - parameter terminator: The terminator of the formatted string. - parameter file: The log file path. - parameter line: The log line number. - parameter column: The log column number. - parameter function: The log function. - parameter date: The log date. - returns: A formatted string. */ func format(level: Level, items: [Any], separator: String, terminator: String, file: String, line: Int, column: Int, function: String, date: Date) -> String { let arguments = components.map { (component: Component) -> CVarArg in switch component { case let .date(dateFormat): return format(date: date, dateFormat: dateFormat) case let .file(fullPath, fileExtension): return format(file: file, fullPath: fullPath, fileExtension: fileExtension) case .function: return String(function) case .line: return String(line) case .column: return String(column) case .level: return format(level: level) case .message: return items.map({ String(describing: $0) }).joined(separator: separator) case .location: return format(file: file, line: line) case let .block(block): return block().flatMap({ String(describing: $0) }) ?? "" } } return String(format: format, arguments: arguments) + terminator } /** Formats a string with the formatter format and components. - parameter description: The measure description. - parameter average: The average time. - parameter relativeStandardDeviation: The relative standard description. - parameter file: The log file path. - parameter line: The log line number. - parameter column: The log column number. - parameter function: The log function. - parameter date: The log date. - returns: A formatted string. */ func format(description: String?, average: Double, relativeStandardDeviation: Double, file: String, line: Int, column: Int, function: String, date: Date) -> String { let arguments = components.map { (component: Component) -> CVarArg in switch component { case let .date(dateFormat): return format(date: date, dateFormat: dateFormat) case let .file(fullPath, fileExtension): return format(file: file, fullPath: fullPath, fileExtension: fileExtension) case .function: return String(function) case .line: return String(line) case .column: return String(column) case .level: return format(description: description) case .message: return format(average: average, relativeStandardDeviation: relativeStandardDeviation) case .location: return format(file: file, line: line) case let .block(block): return block().flatMap({ String(describing: $0) }) ?? "" } } return String(format: format, arguments: arguments) } } private extension Formatter { /** Formats a date with the specified date format. - parameter date: The date. - parameter dateFormat: The date format. - returns: A formatted date. */ func format(date: Date, dateFormat: String) -> String { dateFormatter.dateFormat = dateFormat return dateFormatter.string(from: date) } /** Formats a file path with the specified parameters. - parameter file: The file path. - parameter fullPath: Whether the full path should be included. - parameter fileExtension: Whether the file extension should be included. - returns: A formatted file path. */ func format(file: String, fullPath: Bool, fileExtension: Bool) -> String { var file = file if !fullPath { file = file.lastPathComponent } if !fileExtension { file = file.stringByDeletingPathExtension } return file } /** Formats a Location component with a specified file path and line number. - parameter file: The file path. - parameter line: The line number. - returns: A formatted Location component. */ func format(file: String, line: Int) -> String { return [ format(file: file, fullPath: false, fileExtension: true), String(line) ].joined(separator: ":") } /** Formats a Level component. - parameter level: The Level component. - returns: A formatted Level component. */ func format(level: Level) -> String { let text = level.description if let color = logger?.theme?.colors[level] { return text.withColor(color) } return text } /** Formats a measure description. - parameter description: The measure description. - returns: A formatted measure description. */ func format(description: String?) -> String { var text = "MEASURE" if let color = logger?.theme?.colors[.debug] { text = text.withColor(color) } if let description = description { text = "\(text) \(description)" } return text } /** Formats an average time and a relative standard deviation. - parameter average: The average time. - parameter relativeStandardDeviation: The relative standard deviation. - returns: A formatted average time and relative standard deviation. */ func format(average: Double, relativeStandardDeviation: Double) -> String { let average = format(average: average) let relativeStandardDeviation = format(relativeStandardDeviation: relativeStandardDeviation) return "Time: \(average) sec (\(relativeStandardDeviation) STDEV)" } /** Formats an average time. - parameter average: An average time. - returns: A formatted average time. */ func format(average: Double) -> String { return String(format: "%.3f", average) } /** Formats a list of durations. - parameter durations: A list of durations. - returns: A formatted list of durations. */ func format(durations: [Double]) -> String { var format = Array(repeating: "%.6f", count: durations.count).joined(separator: ", ") format = "[\(format)]" return String(format: format, arguments: durations.map { $0 as CVarArg }) } /** Formats a standard deviation. - parameter standardDeviation: A standard deviation. - returns: A formatted standard deviation. */ func format(standardDeviation: Double) -> String { return String(format: "%.6f", standardDeviation) } /** Formats a relative standard deviation. - parameter relativeStandardDeviation: A relative standard deviation. - returns: A formatted relative standard deviation. */ func format(relativeStandardDeviation: Double) -> String { return String(format: "%.3f%%", relativeStandardDeviation) } }
33.481013
169
0.615406
fbb319e63d0c98e7793df44db6c5753b7ada097d
2,456
// // BubbleLongPressGestureRecognizer.swift // Nariko // // Created by Zsolt Papp on 13/06/16. // Copyright © 2016 Nariko. All rights reserved. // import UIKit import UIKit.UIGestureRecognizerSubclass open class BubbleLongPressGestureRecognizer: UILongPressGestureRecognizer, UIGestureRecognizerDelegate { override init(target: Any?, action: Selector?) { super.init(target: target, action: action) self.addTarget(self, action: #selector(tap(_:))) self.minimumPressDuration = 1.5 self.numberOfTouchesRequired = 3 delegate = self } open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return true } open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if touch.view == okButton { NarikoTool.sharedInstance.closeNarikoAlertView() } return true } } extension BubbleLongPressGestureRecognizer { func tap(_ g: UILongPressGestureRecognizer) { if !isOnboarding{ switch g.state { case .began: if NarikoTool.sharedInstance.isAuth { NarikoTool.sharedInstance.setupBubble() } else { let alertController = UIAlertController (title: "Information", message: "Please login in the settings", preferredStyle: .alert) let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) if let url = settingsUrl { UIApplication.shared.openURL(url) } } let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil) alertController.addAction(settingsAction) alertController.addAction(cancelAction) NarikoTool.sharedInstance.APPDELEGATE.window!!.rootViewController!.present(alertController, animated: true, completion: nil); } default: break } } } }
33.643836
147
0.559853
1a4d00e29bd1ecef7688c2787771f87ae41e2e6d
1,472
// // LocaticsModuleFactory.swift // Locatics // // Created by Luke Smith on 06/09/2019. // Copyright © 2019 Luke Smith. All rights reserved. // import Foundation protocol LocaticsModuleFactoryInterface: class { func createLocaticsListModule() -> LocaticsListViewController } class LocaticsModuleFactory: LocaticsModuleFactoryInterface { private let storageManager: StorageManagerInterface private let locaticStorage: LocaticStorageInterface init(storageManager: StorageManagerInterface, locaticStorage: LocaticStorageInterface) { self.storageManager = storageManager self.locaticStorage = locaticStorage } func createLocaticsListModule() -> LocaticsListViewController { let locaticsListModule = LocaticsListViewController() locaticsListModule.locaticsViewModel = createLocaticsViewModel() return locaticsListModule } } private extension LocaticsModuleFactory { func createLocaticsViewModel() -> LocaticsViewModelInterface { let locaticsCollectionViewModel = createLocaticsCollectionViewModel() return LocaticsViewModel(locaticsCollectionViewModel: locaticsCollectionViewModel) } func createLocaticsCollectionViewModel() -> LocaticsCollectionViewModelInterface { let locaticsCollectionViewModel = LocaticsCollectionViewModel() locaticsCollectionViewModel.locaticStorage = locaticStorage return locaticsCollectionViewModel } }
32
90
0.772418
56aa921708e561cb0e8904d9132c89ea5238b6da
1,971
//: Playground - noun: a place where people can play func ZetaAlgorithm(ptrn: String) -> [Int]? { let pattern = Array(ptrn) let patternLength = pattern.count guard patternLength > 0 else { return nil } var zeta = [Int](repeating: 0, count: patternLength) var left = 0 var right = 0 var k_1 = 0 var betaLength = 0 var textIndex = 0 var patternIndex = 0 for k in 1 ..< patternLength { if k > right { patternIndex = 0 while k + patternIndex < patternLength && pattern[k + patternIndex] == pattern[patternIndex] { patternIndex = patternIndex + 1 } zeta[k] = patternIndex if zeta[k] > 0 { left = k right = k + zeta[k] - 1 } } else { k_1 = k - left + 1 betaLength = right - k + 1 if zeta[k_1 - 1] < betaLength { zeta[k] = zeta[k_1 - 1] } else if zeta[k_1 - 1] >= betaLength { textIndex = betaLength patternIndex = right + 1 while patternIndex < patternLength && pattern[textIndex] == pattern[patternIndex] { textIndex = textIndex + 1 patternIndex = patternIndex + 1 } zeta[k] = patternIndex - k left = k right = patternIndex - 1 } } } return zeta } extension String { func indexesOf(pattern: String) -> [Int]? { let patternLength = pattern.count let zeta = ZetaAlgorithm(ptrn: pattern + "💲" + self) guard zeta != nil else { return nil } var indexes: [Int] = [] /* Scan the zeta array to find matched patterns */ for i in 0 ..< zeta!.count { if zeta![i] == patternLength { indexes.append(i - patternLength - 1) } } guard !indexes.isEmpty else { return nil } return indexes } } /* Examples */ let str = "Hello, playground!" str.indexesOf(pattern: "ground") // [11] let traffic = "🚗🚙🚌🚕🚑🚐🚗🚒🚚🚎🚛🚐🏎🚜🚗🏍🚒🚲🚕🚓🚌🚑" traffic.indexesOf(pattern: "🚑") // [4, 21]
21.193548
91
0.55657
33bb7c481fff1218cf6ba235fa8ef0c41e468df0
644
// // UILabel.swift // Concentration // // Created by Vu Kim Duy on 16/1/21. // import UIKit extension UILabel { func applyAttributedLabelText(string: String) { let shadow = NSShadow() shadow.shadowColor = UIColor.systemBackground shadow.shadowBlurRadius = 5 let attributes : [NSMutableAttributedString.Key: Any] = [ .foregroundColor : UIColor.label, .shadow : shadow, ] let attributedLabelText = NSMutableAttributedString(string: string, attributes: attributes) self.attributedText = attributedLabelText } }
25.76
99
0.613354
1626e52af81e62f9ce613fd40fa5417b4f673e9a
1,380
// // YSCoreProtocol.swift // Pods // // Created by yaoshuai on 2020/12/20. // import Foundation /// YSKit核心组件协议 public protocol YSCoreProtocol { /// YSCore关联类型 associatedtype YSCoreType var ys: YSCoreType { get } static var ys: YSCoreType.Type { get } } /// YSKit核心组件协议默认实现 extension YSCoreProtocol { public var ys: YSOriginalObject<Self> { return YSOriginalObject(originalObject: self) } public static var ys: YSOriginalObject<Self>.Type { return YSOriginalObject.self } } // MARK: - 默认遵守 extension YSCoreProtocol where Self: Any { } extension YSCoreProtocol where Self: AnyObject { } extension NSObject: YSCoreProtocol {} extension Array: YSCoreProtocol {} extension Dictionary: YSCoreProtocol {} extension Set: YSCoreProtocol {} #if !os(Linux) extension CGPoint: YSCoreProtocol {} extension CGRect: YSCoreProtocol {} extension CGSize: YSCoreProtocol {} extension CGVector: YSCoreProtocol {} #endif #if os(iOS) || os(tvOS) extension URL: YSCoreProtocol{} extension UIEdgeInsets: YSCoreProtocol {} extension UIOffset: YSCoreProtocol {} extension UIRectEdge: YSCoreProtocol {} extension Int: YSCoreProtocol {} extension Float: YSCoreProtocol {} extension CGFloat: YSCoreProtocol {} extension Double: YSCoreProtocol {} extension Date: YSCoreProtocol {} extension String: YSCoreProtocol {} #endif
22.258065
55
0.730435
6140b34a10ee5610c586ca18bc8517883044d6f3
19,614
// // SettingsMenuViewController.swift // RPGAapp // // Created by Jakub on 09.08.2017. // import Foundation import UIKit import CoreData import Dwifft protocol settingCellDelegate: class { func touchedSwitch(_ sender: UISwitch) func pressedButton(_ sender: UIButton) } class SettingSwitchCell: UITableViewCell { weak var delegate: settingCellDelegate? @IBAction func switchChanged(_ sender: UISwitch) { delegate?.touchedSwitch(sender) } @IBOutlet weak var settingLabel: UILabel! @IBOutlet weak var settingSwitch: UISwitch! } class SettingButtonCell: UITableViewCell { weak var delegate: settingCellDelegate? @IBAction func buttonPressed(_ sender: UIButton) { delegate?.pressedButton(sender) } @IBOutlet weak var settingLabel: UILabel! @IBOutlet weak var settingButton: UIButton! } let settingValues = ["Auto hide menu": false, "Show price": true, "Dodawaj do listy wylosowanych": false, "Schowaj menu pakietów": true, "syncSessionRemoval": false] class SettingMenu: UITableViewController { let keys = Array(UserDefaults.standard.dictionaryWithValues(forKeys: settingValues.map { $0.0 })) var sessions: [Session] = Load.sessions() var currencies: [Currency] = Load.currencies() var visibilities: [Visibility] = Load.visibilities() var documenController: UIDocumentInteractionController! override func viewWillAppear(_ animated: Bool) { NotificationCenter.default.addObserver(self, selector: #selector(connectedDevicesChanged), name: .connectedDevicesChanged, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(switchedSessionAction(_:)), name: .switchedSession, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(sessionDeleted(_:)), name: .sessionDeleted, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(sessionReceived), name: .sessionReceived, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(currencyCreated), name: .currencyCreated, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(visibilityCreated), name: .visibilityCreated, object: nil) diffCalculator = TableViewDiffCalculator(tableView: tableView, initialSectionedValues: SectionedValues(createDiffTable())) diffCalculator?.insertionAnimation = .fade diffCalculator?.deletionAnimation = .fade super.viewWillAppear(animated) } var diffCalculator: TableViewDiffCalculator<String, String>? func createDiffTable() -> [(String, [String])] { var settingList = keys.map { $0.key } settingList.insert("Sync item database", at: 0) let settingSection = ("Settings", settingList) var sessionList = sessions.compactMap { session -> String? in guard let id = session.id else { return nil } return "\(id)\(session.current)" } sessionList.insert("CreateSessions", at: 0) let sessionsSection = ("Sessions", sessionList) var currencyList = currencies.compactMap { currency -> String? in guard let name = currency.name else { return nil } guard let currentCurrency = Load.currentCurrency() else { return "false\(name)" } let isCurrent = (currency === currentCurrency) return "\(isCurrent)\(name)" } currencyList.insert("CreateCurrency", at: 0) let currenciesSection = ("Currencies", currencyList) var visibilitiesList = visibilities.compactMap { visibility -> String? in guard let id = visibility.id else { return nil } return "\(visibility.current)\(id)" } visibilitiesList.insert("CreateVisibility", at: 0) let visibilitySeciont = ("Visibilities", visibilitiesList) var sectionList = [settingSection, sessionsSection, currenciesSection, visibilitySeciont] if PackageService.pack.session.connectedPeers.count > 0 { let connectedDevices = ("Devices", PackageService.pack.session.connectedPeers.map { $0.displayName }) sectionList.append(connectedDevices) } return sectionList } func updateDiffTable() { let newDiffTable = createDiffTable() diffCalculator?.sectionedValues = SectionedValues(newDiffTable) } @objc func sessionReceived() { sessions = Load.sessions() visibilities = Load.visibilities() updateDiffTable() } @objc func currencyCreated() { currencies = Load.currencies() updateDiffTable() } @objc func visibilityCreated() { visibilities = Load.visibilities() updateDiffTable() } @objc func switchedSessionAction(_ notification: Notification) { sessions = Load.sessions() visibilities = Load.visibilities() updateDiffTable() } func switchedSession(indexPath: IndexPath) { for session in sessions { session.current = false } let session = sessions[indexPath.row - 1] session.current = true CoreDataStack.saveContext() visibilities = Load.visibilities() sessions = Load.sessions() updateDiffTable() NotificationCenter.default.post(name: .reloadTeam, object: nil) NotificationCenter.default.post(name: .currencyChanged, object: nil) let action = SessionSwitched(session: session) PackageService.pack.send(action: action) } @objc func sessionDeleted(_ notification: Notification) { sessions = Load.sessions() updateDiffTable() } @objc func connectedDevicesChanged() { updateDiffTable() } override func numberOfSections(in tableView: UITableView) -> Int { return PackageService.pack.session.connectedPeers.count > 0 ? 5: 4 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return UserDefaults.standard.dictionaryWithValues(forKeys: settingValues.map { $0.0 }).count + 1 } else if section == 1 { return sessions.count + 1 } else if section == 2 { return currencies.count + 1 } else if section == 3 { return visibilities.count + 1 } else { return PackageService.pack.session.connectedPeers.count } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return NSLocalizedString("Settings", comment: "") } else if section == 1 { return NSLocalizedString("Sessions", comment: "") } else if section == 2 { return NSLocalizedString("Currencies", comment: "") } else if section == 3 { return NSLocalizedString("Visibilities", comment: "") } else { return NSLocalizedString("Connected devices", comment: "") } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { if indexPath.row < settingValues.count { let cell = tableView.dequeueReusableCell(withIdentifier: "SettingSwitchCell") as! SettingSwitchCell let cellSetting = keys[indexPath.row].key cell.settingLabel.text = NSLocalizedString(cellSetting, comment: "") cell.settingSwitch.setOn(UserDefaults.standard.bool(forKey: keys[indexPath.row].key), animated: false) cell.delegate = self cell.selectionStyle = .none return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "settingCell") cell?.textLabel?.text = NSLocalizedString("Sync item database", comment: "") cell?.selectionStyle = .none cell?.accessoryType = .none cell?.textLabel?.textColor = .black return cell! } } else if indexPath.section == 1 { if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "SettingButtonCell") as! SettingButtonCell cell.settingLabel?.text = NSLocalizedString("New session", comment: "") cell.selectionStyle = .none let localizedAdd = NSLocalizedString("Add", comment: "") cell.settingButton.setTitle(localizedAdd, for: .normal) cell.delegate = self return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "settingCell") cell?.textLabel?.text = sessions[indexPath.row - 1].name! + " " + String((sessions[indexPath.row - 1].id?.suffix(4))!) cell?.selectionStyle = .none cell?.accessoryType = .none cell?.textLabel?.textColor = .black if sessions[indexPath.row - 1].current { cell?.accessoryType = .checkmark } return cell! } } else if indexPath.section == 2 { if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "SettingButtonCell") as! SettingButtonCell cell.settingLabel?.text = NSLocalizedString("New Currency", comment: "") cell.selectionStyle = .none let localizedCreate = NSLocalizedString("Create", comment: "") cell.settingButton.setTitle(localizedCreate, for: .normal) cell.delegate = self return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "settingCell") let cellCurrency = currencies[indexPath.row - 1] cell?.textLabel?.text = cellCurrency.name cell?.selectionStyle = .none cell?.accessoryType = .none cell?.textLabel?.textColor = .black if cellCurrency == Load.currentCurrency() { cell?.accessoryType = .checkmark } return cell! } } else if indexPath.section == 3 { if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "SettingButtonCell") as! SettingButtonCell cell.settingLabel?.text = NSLocalizedString("New visibility", comment: "") cell.selectionStyle = .none let localizedCreate = NSLocalizedString("Create", comment: "") cell.settingButton.setTitle(localizedCreate, for: .normal) cell.delegate = self return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "settingCell") let cellVisibility = visibilities[indexPath.row - 1] cell?.textLabel?.text = cellVisibility.name if let color = NameGenerator.colors.first(where: { $0.0 == cellVisibility.name })?.1 { cell?.textLabel?.textColor = color } cell?.selectionStyle = .none cell?.accessoryType = .none if cellVisibility.current { cell?.accessoryType = .checkmark } return cell! } } else { let cell = tableView.dequeueReusableCell(withIdentifier: "settingCell") cell?.textLabel?.text = PackageService.pack.session.connectedPeers[indexPath.row].displayName cell?.selectionStyle = .none cell?.accessoryType = .none cell?.textLabel?.textColor = .black return cell! } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 0 && indexPath.row == settingValues.count { let syncAction = ItemListSync() let requestAction = ItemListRequested() PackageService.pack.send(action: syncAction) PackageService.pack.send(action: requestAction) } else if indexPath.section == 1 && indexPath.row > 0 && !sessions[indexPath.row - 1].current { guard sessions.filter({ $0.current }).count != 0 else { switchedSession(indexPath: indexPath) return } let localizedMessage = NSLocalizedString("Do you want to change session", comment: "") let alert = UIAlertController(title: nil, message: localizedMessage, preferredStyle: .alert) let localizedYes = NSLocalizedString("Yes", comment: "") let alertYes = UIAlertAction(title: localizedYes, style: .destructive, handler: {(_) in self.switchedSession(indexPath: indexPath) }) let localizedNo = NSLocalizedString("No", comment: "") let alertNo = UIAlertAction(title: localizedNo, style: .cancel, handler: nil) alert.addAction(alertYes) alert.addAction(alertNo) present(alert, animated: true, completion: nil) } else if indexPath.section == 2 { if indexPath.row == 0 { createCurrency() } else { let session = Load.currentSession() sessions = Load.sessions() visibilities = Load.visibilities() session.currency = currencies[indexPath.row - 1] CoreDataStack.saveContext() updateDiffTable() NotificationCenter.default.post(name: .currencyChanged, object: nil) } } else if indexPath.section == 3 { if indexPath.row != 0 { var rowsToReload = [indexPath] let previousVisibilityIndex = visibilities.firstIndex(where: { $0.current }) if let previousVisibilityIndex = previousVisibilityIndex { let previousRow = IndexPath(row: previousVisibilityIndex + 1, section: 3) if previousRow == indexPath { visibilities[previousVisibilityIndex].current = !visibilities[previousVisibilityIndex].current } else { visibilities[previousVisibilityIndex].current = false rowsToReload.append(previousRow) } } if rowsToReload.count == 2 || previousVisibilityIndex == nil { visibilities[indexPath.row - 1].current = true } CoreDataStack.saveContext() updateDiffTable() NotificationCenter.default.post(name: .reloadTeam, object: nil) } } } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return (indexPath.section == 1 && indexPath.row != 0) || (indexPath.section == 2 && indexPath.row != 0) || (indexPath.section == 3 && indexPath.row != 0) || indexPath.section == 4 } override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { var actions: [UIContextualAction] = [] let localizedYes = NSLocalizedString("Yes", comment: "") let localizedNo = NSLocalizedString("No", comment: "") let localizedRemove = NSLocalizedString("Remove", comment: "") if indexPath.section == 1 { actions = [] let localizedDelete = NSLocalizedString("Delete", comment: "") let removeSession = UIContextualAction(style: .destructive, title: localizedDelete, handler: { (_, _, _) in let localizedMessage = NSLocalizedString("Do you want to delete this session?", comment: "") let alert = UIAlertController(title: nil, message: localizedMessage, preferredStyle: .alert) let alertYes = UIAlertAction(title: localizedYes, style: .destructive, handler: { (_) -> Void in let context = CoreDataStack.managedObjectContext let session = self.sessions[indexPath.row - 1] let sessionId = session.id self.sessions.remove(at: indexPath.row - 1) context.delete(session) CoreDataStack.saveContext() self.visibilities = Load.visibilities() self.updateDiffTable() NotificationCenter.default.post(name: .reloadTeam, object: nil) NotificationCenter.default.post(name: .currencyChanged, object: nil) let action = SessionDeleted(sessionId: sessionId!) PackageService.pack.send(action: action) }) let alertNo = UIAlertAction(title: localizedNo, style: .cancel, handler: nil) alert.addAction(alertYes) alert.addAction(alertNo) self.present(alert, animated: true, completion: nil) }) actions.append(removeSession) let localizedSendTitle = NSLocalizedString("Send", comment: "") let sendSession = UIContextualAction(style: .normal, title: localizedSendTitle, handler: { (_, _, _) in let session = self.sessions[indexPath.row - 1] let action = SessionReceived(session: session) PackageService.pack.send(action: action) tableView.setEditing(false, animated: true) let localizedSendSessionString = NSLocalizedString("Send session", comment: "") whisper(messege: localizedSendSessionString) }) actions.append(sendSession) let localizedSharedTitle = NSLocalizedString("Share", comment: "") let shareSession = UIContextualAction(style: .normal, title: localizedSharedTitle, handler: { (_, _, _) in guard self.sessions.count > indexPath.row - 1 && indexPath.row - 1 >= 0 else { return } let dict = packSessionForMessage(self.sessions[indexPath.row - 1]) let url = save(dictionary: dict) self.documenController = UIDocumentInteractionController(url: url) let touchPoint = tableView.rectForRow(at: indexPath) self.documenController.presentOptionsMenu(from: touchPoint, in: tableView, animated: true) }) shareSession.backgroundColor = UIColor.darkGray actions.append(shareSession) } else if indexPath.section == 2 { let deleteCurrency = UIContextualAction(style: .destructive, title: localizedRemove, handler: { (_, _, _) in let currencyToDelete = self.currencies[indexPath.row - 1] self.currencies.remove(at: indexPath.row - 1) let context = CoreDataStack.managedObjectContext context.delete(currencyToDelete) CoreDataStack.saveContext() self.updateDiffTable() }) let localizedEdit = NSLocalizedString("Edit", comment: "") let editCurrency = UIContextualAction(style: .normal, title: localizedEdit, handler: { (_, _, _) in let currency = self.currencies[indexPath.row - 1] let currencyForm = NewCurrencyForm() currencyForm.modalPresentationStyle = .formSheet currencyForm.currency = currency self.present(currencyForm, animated: true, completion: nil) }) actions = [deleteCurrency, editCurrency] } else if indexPath.section == 3 { let deleteVisibility = UIContextualAction(style: .destructive, title: localizedRemove, handler: { (_, _, _) in let visibilityToDelete = self.visibilities[indexPath.row - 1] let visibilityId = visibilityToDelete.id self.visibilities.remove(at: indexPath.row - 1) let context = CoreDataStack.managedObjectContext context.delete(visibilityToDelete) CoreDataStack.saveContext() self.updateDiffTable() let action = VisibilityRemoved(visibilityId: visibilityId!) PackageService.pack.send(action: action) }) actions = [deleteVisibility] } else if indexPath.section == 4 { actions = [] let removePeer = UIContextualAction(style: .destructive, title: localizedRemove, handler: { (_, _, _) in let peer = PackageService.pack.session.connectedPeers[indexPath.row] let action = DisconnectPeer(peer: peer.displayName) PackageService.pack.send(action: action) PackageService.pack.session.cancelConnectPeer(peer) }) actions.append(removePeer) } return UISwipeActionsConfiguration(actions: actions) } } extension SettingMenu: settingCellDelegate { func touchedSwitch(_ sender: UISwitch) { if let indexPath = getCurrentCellIndexPath(sender, tableView: self.tableView) { UserDefaults.standard.set(sender.isOn, forKey: keys[indexPath.row].key) if keys[indexPath.row].key == "Show price" { NotificationCenter.default.post(name: .reloadRandomItemTable, object: nil) } } } func pressedButton(_ sender: UIButton) { guard let index = getCurrentCellIndexPath(sender, tableView: self.tableView) else { return } if index.section == 1 { Session.create() } else if index.section == 2 { createCurrency() } else if index.section == 3 { Visibility.createVisibility() visibilities = Load.visibilities() } sessions = Load.sessions() updateDiffTable() } func createCurrency() { let currencyForm = NewCurrencyForm() currencyForm.modalPresentationStyle = .formSheet present(currencyForm, animated: true) } } extension Notification.Name { static let switchedSession = Notification.Name("switchedSession") static let sessionDeleted = Notification.Name("sessionDeleted") static let sessionReceived = Notification.Name("sessionReceived") static let currencyCreated = Notification.Name("currencyCreated") static let currencyChanged = Notification.Name("currencyChanged") static let visibilityCreated = Notification.Name("visibilityCreated") }
32.909396
165
0.712705
14ad7b31b7366d18575d3446952cadd672dbd951
98,609
// // TokenizerTests.swift // SwiftFormat // // Created by Nick Lockwood on 12/08/2016. // Copyright 2016 Nick Lockwood // // Distributed under the permissive MIT license // Get the latest version from here: // // https://github.com/nicklockwood/SwiftFormat // // 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 SwiftFormat import XCTest class TokenizerTests: XCTestCase { // MARK: Invalid input func testInvalidToken() { let input = "let `foo = bar" let output: [Token] = [ .keyword("let"), .space(" "), .error("`foo"), .space(" "), .operator("=", .infix), .space(" "), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testUnclosedBraces() { let input = "func foo() {" let output: [Token] = [ .keyword("func"), .space(" "), .identifier("foo"), .startOfScope("("), .endOfScope(")"), .space(" "), .startOfScope("{"), .error(""), ] XCTAssertEqual(tokenize(input), output) } func testUnclosedMultilineComment() { let input = "/* comment" let output: [Token] = [ .startOfScope("/*"), .space(" "), .commentBody("comment"), .error(""), ] XCTAssertEqual(tokenize(input), output) } func testUnclosedString() { let input = "\"Hello World" let output: [Token] = [ .startOfScope("\""), .stringBody("Hello World"), .error(""), ] XCTAssertEqual(tokenize(input), output) } func testUnbalancedScopes() { let input = "array.map({ return $0 )" let output: [Token] = [ .identifier("array"), .operator(".", .infix), .identifier("map"), .startOfScope("("), .startOfScope("{"), .space(" "), .keyword("return"), .space(" "), .identifier("$0"), .space(" "), .error(")"), ] XCTAssertEqual(tokenize(input), output) } // MARK: Hashbang func testHashbangOnItsOwnInFile() { let input = "#!/usr/bin/swift" let output: [Token] = [ .startOfScope("#!"), .commentBody("/usr/bin/swift"), ] XCTAssertEqual(tokenize(input), output) } func testHashbangAtStartOfFile() { let input = "#!/usr/bin/swift \n" let output: [Token] = [ .startOfScope("#!"), .commentBody("/usr/bin/swift"), .space(" "), .linebreak("\n", 1), ] XCTAssertEqual(tokenize(input), output) } func testHashbangAfterFirstLine() { let input = "//Hello World\n#!/usr/bin/swift \n" let output: [Token] = [ .startOfScope("//"), .commentBody("Hello World"), .linebreak("\n", 1), .error("#!/usr/bin/swift"), .space(" "), .linebreak("\n", 2), ] XCTAssertEqual(tokenize(input), output) } // MARK: Unescaping func testUnescapeInteger() { let input = Token.number("1_000_000_000", .integer) let output = "1000000000" XCTAssertEqual(input.unescaped(), output) } func testUnescapeDecimal() { let input = Token.number("1_000.00_5", .decimal) let output = "1000.005" XCTAssertEqual(input.unescaped(), output) } func testUnescapeBinary() { let input = Token.number("0b010_1010_101", .binary) let output = "0101010101" XCTAssertEqual(input.unescaped(), output) } func testUnescapeHex() { let input = Token.number("0xFF_764Ep1_345", .hex) let output = "FF764Ep1345" XCTAssertEqual(input.unescaped(), output) } func testUnescapeIdentifier() { let input = Token.identifier("`for`") let output = "for" XCTAssertEqual(input.unescaped(), output) } func testUnescapeLinebreak() { let input = Token.stringBody("Hello\\nWorld") let output = "Hello\nWorld" XCTAssertEqual(input.unescaped(), output) } func testUnescapeQuotedString() { let input = Token.stringBody("\\\"Hello World\\\"") let output = "\"Hello World\"" XCTAssertEqual(input.unescaped(), output) } func testUnescapeUnicodeLiterals() { let input = Token.stringBody("\\u{1F1FA}\\u{1F1F8}") let output = "\u{1F1FA}\u{1F1F8}" XCTAssertEqual(input.unescaped(), output) } // MARK: Space func testSpaces() { let input = " " let output: [Token] = [ .space(" "), ] XCTAssertEqual(tokenize(input), output) } func testSpacesAndTabs() { let input = " \t \t" let output: [Token] = [ .space(" \t \t"), ] XCTAssertEqual(tokenize(input), output) } // MARK: Strings func testEmptyString() { let input = "\"\"" let output: [Token] = [ .startOfScope("\""), .endOfScope("\""), ] XCTAssertEqual(tokenize(input), output) } func testSimpleString() { let input = "\"foo\"" let output: [Token] = [ .startOfScope("\""), .stringBody("foo"), .endOfScope("\""), ] XCTAssertEqual(tokenize(input), output) } func testStringWithEscape() { let input = "\"hello\\tworld\"" let output: [Token] = [ .startOfScope("\""), .stringBody("hello\\tworld"), .endOfScope("\""), ] XCTAssertEqual(tokenize(input), output) } func testStringWithEscapedQuotes() { let input = "\"\\\"nice\\\" to meet you\"" let output: [Token] = [ .startOfScope("\""), .stringBody("\\\"nice\\\" to meet you"), .endOfScope("\""), ] XCTAssertEqual(tokenize(input), output) } func testStringWithEscapedLogic() { let input = "\"hello \\(name)\"" let output: [Token] = [ .startOfScope("\""), .stringBody("hello \\"), .startOfScope("("), .identifier("name"), .endOfScope(")"), .endOfScope("\""), ] XCTAssertEqual(tokenize(input), output) } func testStringWithEscapedBackslash() { let input = "\"\\\\\"" let output: [Token] = [ .startOfScope("\""), .stringBody("\\\\"), .endOfScope("\""), ] XCTAssertEqual(tokenize(input), output) } // MARK: Multiline strings func testSimpleMultilineString() { let input = "\"\"\"\n hello\n world\n \"\"\"" let output: [Token] = [ .startOfScope("\"\"\""), .linebreak("\n", 1), .space(" "), .stringBody("hello"), .linebreak("\n", 2), .space(" "), .stringBody("world"), .linebreak("\n", 3), .space(" "), .endOfScope("\"\"\""), ] XCTAssertEqual(tokenize(input), output) } func testIndentedSimpleMultilineString() { let input = "\"\"\"\n hello\n world\n\"\"\"" let output: [Token] = [ .startOfScope("\"\"\""), .linebreak("\n", 1), .stringBody(" hello"), .linebreak("\n", 2), .stringBody(" world"), .linebreak("\n", 3), .endOfScope("\"\"\""), ] XCTAssertEqual(tokenize(input), output) } func testEmptyMultilineString() { let input = "\"\"\"\n\"\"\"" let output: [Token] = [ .startOfScope("\"\"\""), .linebreak("\n", 1), .endOfScope("\"\"\""), ] XCTAssertEqual(tokenize(input), output) } func testMultilineStringWithEscapedLinebreak() { let input = "\"\"\"\n hello \\\n world\n\"\"\"" let output: [Token] = [ .startOfScope("\"\"\""), .linebreak("\n", 1), .stringBody(" hello \\"), .linebreak("\n", 2), .stringBody(" world"), .linebreak("\n", 3), .endOfScope("\"\"\""), ] XCTAssertEqual(tokenize(input), output) } func testMultilineStringStartingWithInterpolation() { let input = " \"\"\"\n \\(String(describing: 1))\n \"\"\"" let output: [Token] = [ .space(" "), .startOfScope("\"\"\""), .linebreak("\n", 1), .space(" "), .stringBody("\\"), .startOfScope("("), .identifier("String"), .startOfScope("("), .identifier("describing"), .delimiter(":"), .space(" "), .number("1", .integer), .endOfScope(")"), .endOfScope(")"), .linebreak("\n", 2), .space(" "), .endOfScope("\"\"\""), ] XCTAssertEqual(tokenize(input), output) } func testMultilineStringWithEscapedTripleQuote() { let input = "\"\"\"\n\\\"\"\"\n\"\"\"" let output: [Token] = [ .startOfScope("\"\"\""), .linebreak("\n", 1), .stringBody("\\\"\"\""), .linebreak("\n", 2), .endOfScope("\"\"\""), ] XCTAssertEqual(tokenize(input), output) } // MARK: Raw strings func testEmptyRawString() { let input = "#\"\"#" let output: [Token] = [ .startOfScope("#\""), .endOfScope("\"#"), ] XCTAssertEqual(tokenize(input), output) } func testEmptyDoubleRawString() { let input = "##\"\"##" let output: [Token] = [ .startOfScope("##\""), .endOfScope("\"##"), ] XCTAssertEqual(tokenize(input), output) } func testUnbalancedRawString() { let input = "##\"\"#" let output: [Token] = [ .startOfScope("##\""), .stringBody("\"#"), .error(""), ] XCTAssertEqual(tokenize(input), output) } func testUnbalancedRawString2() { let input = "#\"\"##" let output: [Token] = [ .startOfScope("#\""), .endOfScope("\"#"), .error("#"), ] XCTAssertEqual(tokenize(input), output) } func testRawStringContainingUnescapedQuote() { let input = "#\" \" \"#" let output: [Token] = [ .startOfScope("#\""), .stringBody(" \" "), .endOfScope("\"#"), ] XCTAssertEqual(tokenize(input), output) } func testRawStringContainingJustASingleUnescapedQuote() { let input = "#\"\"\"#" let output: [Token] = [ .startOfScope("#\"\"\""), .stringBody("#"), .error(""), ] XCTAssertEqual(tokenize(input), output) } func testRawStringContainingUnhashedBackslash() { let input = "#\"\\\"#" let output: [Token] = [ .startOfScope("#\""), .stringBody("\\"), .endOfScope("\"#"), ] XCTAssertEqual(tokenize(input), output) } func testRawStringContainingHashedEscapeSequence() { let input = "#\"\\#n\"#" let output: [Token] = [ .startOfScope("#\""), .stringBody("\\#n"), .endOfScope("\"#"), ] XCTAssertEqual(tokenize(input), output) } func testRawStringContainingUnderhashedEscapeSequence() { let input = "##\"\\#n\"##" let output: [Token] = [ .startOfScope("##\""), .stringBody("\\#n"), .endOfScope("\"##"), ] XCTAssertEqual(tokenize(input), output) } func testRawStringContainingUnhashedInterpolation() { let input = "#\"\\(5)\"#" let output: [Token] = [ .startOfScope("#\""), .stringBody("\\(5)"), .endOfScope("\"#"), ] XCTAssertEqual(tokenize(input), output) } func testRawStringContainingHashedInterpolation() { let input = "#\"\\#(5)\"#" let output: [Token] = [ .startOfScope("#\""), .stringBody("\\#"), .startOfScope("("), .number("5", .integer), .endOfScope(")"), .endOfScope("\"#"), ] XCTAssertEqual(tokenize(input), output) } func testRawStringContainingUnderhashedInterpolation() { let input = "##\"\\#(5)\"##" let output: [Token] = [ .startOfScope("##\""), .stringBody("\\#(5)"), .endOfScope("\"##"), ] XCTAssertEqual(tokenize(input), output) } // MARK: Multiline raw strings func testSimpleMultilineRawString() { let input = "#\"\"\"\n hello\n world\n \"\"\"#" let output: [Token] = [ .startOfScope("#\"\"\""), .linebreak("\n", 1), .space(" "), .stringBody("hello"), .linebreak("\n", 2), .space(" "), .stringBody("world"), .linebreak("\n", 3), .space(" "), .endOfScope("\"\"\"#"), ] XCTAssertEqual(tokenize(input), output) } func testMultilineRawStringContainingUnhashedInterpolation() { let input = "#\"\"\"\n \\(5)\n \"\"\"#" let output: [Token] = [ .startOfScope("#\"\"\""), .linebreak("\n", 1), .space(" "), .stringBody("\\(5)"), .linebreak("\n", 2), .space(" "), .endOfScope("\"\"\"#"), ] XCTAssertEqual(tokenize(input), output) } func testMultilineRawStringContainingHashedInterpolation() { let input = "#\"\"\"\n \\#(5)\n \"\"\"#" let output: [Token] = [ .startOfScope("#\"\"\""), .linebreak("\n", 1), .space(" "), .stringBody("\\#"), .startOfScope("("), .number("5", .integer), .endOfScope(")"), .linebreak("\n", 2), .space(" "), .endOfScope("\"\"\"#"), ] XCTAssertEqual(tokenize(input), output) } func testMultilineRawStringContainingUnderhashedInterpolation() { let input = "##\"\"\"\n \\#(5)\n \"\"\"##" let output: [Token] = [ .startOfScope("##\"\"\""), .linebreak("\n", 1), .space(" "), .stringBody("\\#(5)"), .linebreak("\n", 2), .space(" "), .endOfScope("\"\"\"##"), ] XCTAssertEqual(tokenize(input), output) } // MARK: Single-line comments func testSingleLineComment() { let input = "//foo" let output: [Token] = [ .startOfScope("//"), .commentBody("foo"), ] XCTAssertEqual(tokenize(input), output) } func testSingleLineCommentWithSpace() { let input = "// foo " let output: [Token] = [ .startOfScope("//"), .space(" "), .commentBody("foo"), .space(" "), ] XCTAssertEqual(tokenize(input), output) } func testSingleLineCommentWithLinebreak() { let input = "//foo\nbar" let output: [Token] = [ .startOfScope("//"), .commentBody("foo"), .linebreak("\n", 1), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } // MARK: Multiline comments func testSingleLineMultilineComment() { let input = "/*foo*/" let output: [Token] = [ .startOfScope("/*"), .commentBody("foo"), .endOfScope("*/"), ] XCTAssertEqual(tokenize(input), output) } func testSingleLineMultilineCommentWithSpace() { let input = "/* foo */" let output: [Token] = [ .startOfScope("/*"), .space(" "), .commentBody("foo"), .space(" "), .endOfScope("*/"), ] XCTAssertEqual(tokenize(input), output) } func testMultilineComment() { let input = "/*foo\nbar*/" let output: [Token] = [ .startOfScope("/*"), .commentBody("foo"), .linebreak("\n", 1), .commentBody("bar"), .endOfScope("*/"), ] XCTAssertEqual(tokenize(input), output) } func testMultilineCommentWithSpace() { let input = "/*foo\n bar*/" let output: [Token] = [ .startOfScope("/*"), .commentBody("foo"), .linebreak("\n", 1), .space(" "), .commentBody("bar"), .endOfScope("*/"), ] XCTAssertEqual(tokenize(input), output) } func testNestedComments() { let input = "/*foo/*bar*/baz*/" let output: [Token] = [ .startOfScope("/*"), .commentBody("foo"), .startOfScope("/*"), .commentBody("bar"), .endOfScope("*/"), .commentBody("baz"), .endOfScope("*/"), ] XCTAssertEqual(tokenize(input), output) } func testNestedCommentsWithSpace() { let input = "/* foo /* bar */ baz */" let output: [Token] = [ .startOfScope("/*"), .space(" "), .commentBody("foo"), .space(" "), .startOfScope("/*"), .space(" "), .commentBody("bar"), .space(" "), .endOfScope("*/"), .space(" "), .commentBody("baz"), .space(" "), .endOfScope("*/"), ] XCTAssertEqual(tokenize(input), output) } func testPreformattedMultilineComment() { let input = """ /* func foo() { if bar { print(baz) } } */ """ let output: [Token] = [ .startOfScope("/*"), .linebreak("\n", 1), .space(" "), .commentBody("func foo() {"), .linebreak("\n", 2), .space(" "), .commentBody(" if bar {"), .linebreak("\n", 3), .space(" "), .commentBody(" print(baz)"), .linebreak("\n", 4), .space(" "), .commentBody(" }"), .linebreak("\n", 5), .space(" "), .commentBody("}"), .linebreak("\n", 6), .space(" "), .endOfScope("*/"), ] XCTAssertEqual(tokenize(input), output) } // MARK: Numbers func testZero() { let input = "0" let output: [Token] = [.number("0", .integer)] XCTAssertEqual(tokenize(input), output) } func testSmallInteger() { let input = "5" let output: [Token] = [.number("5", .integer)] XCTAssertEqual(tokenize(input), output) } func testLargeInteger() { let input = "12345678901234567890" let output: [Token] = [.number("12345678901234567890", .integer)] XCTAssertEqual(tokenize(input), output) } func testNegativeInteger() { let input = "-7" let output: [Token] = [ .operator("-", .prefix), .number("7", .integer), ] XCTAssertEqual(tokenize(input), output) } func testInvalidInteger() { let input = "123abc" let output: [Token] = [ .number("123", .integer), .error("abc"), ] XCTAssertEqual(tokenize(input), output) } func testSmallFloat() { let input = "0.2" let output: [Token] = [.number("0.2", .decimal)] XCTAssertEqual(tokenize(input), output) } func testLargeFloat() { let input = "1234.567890" let output: [Token] = [.number("1234.567890", .decimal)] XCTAssertEqual(tokenize(input), output) } func testNegativeFloat() { let input = "-0.34" let output: [Token] = [ .operator("-", .prefix), .number("0.34", .decimal), ] XCTAssertEqual(tokenize(input), output) } func testExponential() { let input = "1234e5" let output: [Token] = [.number("1234e5", .decimal)] XCTAssertEqual(tokenize(input), output) } func testPositiveExponential() { let input = "0.123e+4" let output: [Token] = [.number("0.123e+4", .decimal)] XCTAssertEqual(tokenize(input), output) } func testNegativeExponential() { let input = "0.123e-4" let output: [Token] = [.number("0.123e-4", .decimal)] XCTAssertEqual(tokenize(input), output) } func testCapitalExponential() { let input = "0.123E-4" let output: [Token] = [.number("0.123E-4", .decimal)] XCTAssertEqual(tokenize(input), output) } func testInvalidExponential() { let input = "123.e5" let output: [Token] = [ .number("123", .integer), .operator(".", .infix), .identifier("e5"), ] XCTAssertEqual(tokenize(input), output) } func testLeadingZeros() { let input = "0005" let output: [Token] = [.number("0005", .integer)] XCTAssertEqual(tokenize(input), output) } func testBinary() { let input = "0b101010" let output: [Token] = [.number("0b101010", .binary)] XCTAssertEqual(tokenize(input), output) } func testOctal() { let input = "0o52" let output: [Token] = [.number("0o52", .octal)] XCTAssertEqual(tokenize(input), output) } func testHex() { let input = "0x2A" let output: [Token] = [.number("0x2A", .hex)] XCTAssertEqual(tokenize(input), output) } func testHexadecimalPower() { let input = "0xC3p0" let output: [Token] = [.number("0xC3p0", .hex)] XCTAssertEqual(tokenize(input), output) } func testCapitalHexadecimalPower() { let input = "0xC3P0" let output: [Token] = [.number("0xC3P0", .hex)] XCTAssertEqual(tokenize(input), output) } func testNegativeHexadecimalPower() { let input = "0xC3p-5" let output: [Token] = [.number("0xC3p-5", .hex)] XCTAssertEqual(tokenize(input), output) } func testFloatHexadecimalPower() { let input = "0xC.3p0" let output: [Token] = [.number("0xC.3p0", .hex)] XCTAssertEqual(tokenize(input), output) } func testFloatNegativeHexadecimalPower() { let input = "0xC.3p-5" let output: [Token] = [.number("0xC.3p-5", .hex)] XCTAssertEqual(tokenize(input), output) } func testUnderscoresInInteger() { let input = "1_23_4_" let output: [Token] = [.number("1_23_4_", .integer)] XCTAssertEqual(tokenize(input), output) } func testUnderscoresInFloat() { let input = "0_.1_2_" let output: [Token] = [.number("0_.1_2_", .decimal)] XCTAssertEqual(tokenize(input), output) } func testUnderscoresInExponential() { let input = "0.1_2_e-3" let output: [Token] = [.number("0.1_2_e-3", .decimal)] XCTAssertEqual(tokenize(input), output) } func testUnderscoresInBinary() { let input = "0b0000_0000_0001" let output: [Token] = [.number("0b0000_0000_0001", .binary)] XCTAssertEqual(tokenize(input), output) } func testUnderscoresInOctal() { let input = "0o123_456" let output: [Token] = [.number("0o123_456", .octal)] XCTAssertEqual(tokenize(input), output) } func testUnderscoresInHex() { let input = "0xabc_def" let output: [Token] = [.number("0xabc_def", .hex)] XCTAssertEqual(tokenize(input), output) } func testUnderscoresInHexadecimalPower() { let input = "0xabc_p5" let output: [Token] = [.number("0xabc_p5", .hex)] XCTAssertEqual(tokenize(input), output) } func testUnderscoresInFloatHexadecimalPower() { let input = "0xa.bc_p5" let output: [Token] = [.number("0xa.bc_p5", .hex)] XCTAssertEqual(tokenize(input), output) } func testNoLeadingUnderscoreInInteger() { let input = "_12345" let output: [Token] = [.identifier("_12345")] XCTAssertEqual(tokenize(input), output) } func testNoLeadingUnderscoreInHex() { let input = "0x_12345" let output: [Token] = [.error("0x_12345")] XCTAssertEqual(tokenize(input), output) } func testHexPropertyAccess() { let input = "0x123.ee" let output: [Token] = [ .number("0x123", .hex), .operator(".", .infix), .identifier("ee"), ] XCTAssertEqual(tokenize(input), output) } func testInvalidHexadecimal() { let input = "0x123.0" let output: [Token] = [ .error("0x123.0"), ] XCTAssertEqual(tokenize(input), output) } func testAnotherInvalidHexadecimal() { let input = "0x123.0p" let output: [Token] = [ .error("0x123.0p"), ] XCTAssertEqual(tokenize(input), output) } func testInvalidOctal() { let input = "0o1235678" let output: [Token] = [ .number("0o123567", .octal), .error("8"), ] XCTAssertEqual(tokenize(input), output) } // MARK: Identifiers & keywords func testFoo() { let input = "foo" let output: [Token] = [.identifier("foo")] XCTAssertEqual(tokenize(input), output) } func testDollar0() { let input = "$0" let output: [Token] = [.identifier("$0")] XCTAssertEqual(tokenize(input), output) } func testDollar() { // Note: support for this is deprecated in Swift 3 let input = "$" let output: [Token] = [.identifier("$")] XCTAssertEqual(tokenize(input), output) } func testFooDollar() { let input = "foo$" let output: [Token] = [.identifier("foo$")] XCTAssertEqual(tokenize(input), output) } func test_() { let input = "_" let output: [Token] = [.identifier("_")] XCTAssertEqual(tokenize(input), output) } func test_foo() { let input = "_foo" let output: [Token] = [.identifier("_foo")] XCTAssertEqual(tokenize(input), output) } func testFoo_bar() { let input = "foo_bar" let output: [Token] = [.identifier("foo_bar")] XCTAssertEqual(tokenize(input), output) } func testAtFoo() { let input = "@foo" let output: [Token] = [.keyword("@foo")] XCTAssertEqual(tokenize(input), output) } func testHashFoo() { let input = "#foo" let output: [Token] = [.keyword("#foo")] XCTAssertEqual(tokenize(input), output) } func testUnicode() { let input = "µsec" let output: [Token] = [.identifier("µsec")] XCTAssertEqual(tokenize(input), output) } func testEmoji() { let input = "🙃" let output: [Token] = [.identifier("🙃")] XCTAssertEqual(tokenize(input), output) } func testBacktickEscapedClass() { let input = "`class`" let output: [Token] = [.identifier("`class`")] XCTAssertEqual(tokenize(input), output) } func testDotPrefixedKeyword() { let input = ".default" let output: [Token] = [ .operator(".", .prefix), .identifier("default"), ] XCTAssertEqual(tokenize(input), output) } func testKeywordsAsArgumentLabelNames() { let input = "foo(for: bar, if: baz)" let output: [Token] = [ .identifier("foo"), .startOfScope("("), .identifier("for"), .delimiter(":"), .space(" "), .identifier("bar"), .delimiter(","), .space(" "), .identifier("if"), .delimiter(":"), .space(" "), .identifier("baz"), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testKeywordsAsArgumentLabelNames2() { let input = "foo(case: bar, default: baz)" let output: [Token] = [ .identifier("foo"), .startOfScope("("), .identifier("case"), .delimiter(":"), .space(" "), .identifier("bar"), .delimiter(","), .space(" "), .identifier("default"), .delimiter(":"), .space(" "), .identifier("baz"), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testKeywordsAsArgumentLabelNames3() { let input = "foo(switch: bar, case: baz)" let output: [Token] = [ .identifier("foo"), .startOfScope("("), .identifier("switch"), .delimiter(":"), .space(" "), .identifier("bar"), .delimiter(","), .space(" "), .identifier("case"), .delimiter(":"), .space(" "), .identifier("baz"), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testKeywordAsInternalArgumentLabelName() { let input = "func foo(all in: Array)" let output: [Token] = [ .keyword("func"), .space(" "), .identifier("foo"), .startOfScope("("), .identifier("all"), .space(" "), .identifier("in"), .delimiter(":"), .space(" "), .identifier("Array"), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testKeywordAsExternalArgumentLabelName() { let input = "func foo(in array: Array)" let output: [Token] = [ .keyword("func"), .space(" "), .identifier("foo"), .startOfScope("("), .identifier("in"), .space(" "), .identifier("array"), .delimiter(":"), .space(" "), .identifier("Array"), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testKeywordAsBothArgumentLabelNames() { let input = "func foo(for in: Array)" let output: [Token] = [ .keyword("func"), .space(" "), .identifier("foo"), .startOfScope("("), .identifier("for"), .space(" "), .identifier("in"), .delimiter(":"), .space(" "), .identifier("Array"), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testKeywordAsSubscriptLabels() { let input = "foo[for: bar]" let output: [Token] = [ .identifier("foo"), .startOfScope("["), .identifier("for"), .delimiter(":"), .space(" "), .identifier("bar"), .endOfScope("]"), ] XCTAssertEqual(tokenize(input), output) } func testNumberedTupleVariableMember() { let input = "foo.2" let output: [Token] = [ .identifier("foo"), .operator(".", .infix), .identifier("2"), ] XCTAssertEqual(tokenize(input), output) } func testNumberedTupleExpressionMember() { let input = "(1,2).1" let output: [Token] = [ .startOfScope("("), .number("1", .integer), .delimiter(","), .number("2", .integer), .endOfScope(")"), .operator(".", .infix), .identifier("1"), ] XCTAssertEqual(tokenize(input), output) } // MARK: Operators func testBasicOperator() { let input = "+=" let output: [Token] = [.operator("+=", .none)] XCTAssertEqual(tokenize(input), output) } func testDivide() { let input = "a / b" let output: [Token] = [ .identifier("a"), .space(" "), .operator("/", .infix), .space(" "), .identifier("b"), ] XCTAssertEqual(tokenize(input), output) } func testCustomOperator() { let input = "~=" let output: [Token] = [.operator("~=", .none)] XCTAssertEqual(tokenize(input), output) } func testCustomOperator2() { let input = "a <> b" let output: [Token] = [ .identifier("a"), .space(" "), .operator("<>", .infix), .space(" "), .identifier("b"), ] XCTAssertEqual(tokenize(input), output) } func testCustomOperator3() { let input = "a |> b" let output: [Token] = [ .identifier("a"), .space(" "), .operator("|>", .infix), .space(" "), .identifier("b"), ] XCTAssertEqual(tokenize(input), output) } func testCustomOperator4() { let input = "a <<>> b" let output: [Token] = [ .identifier("a"), .space(" "), .operator("<<>>", .infix), .space(" "), .identifier("b"), ] XCTAssertEqual(tokenize(input), output) } func testSequentialOperators() { let input = "a *= -b" let output: [Token] = [ .identifier("a"), .space(" "), .operator("*=", .infix), .space(" "), .operator("-", .prefix), .identifier("b"), ] XCTAssertEqual(tokenize(input), output) } func testDotPrefixedOperator() { let input = "..." let output: [Token] = [.operator("...", .none)] XCTAssertEqual(tokenize(input), output) } func testAngleBracketSuffixedOperator() { let input = "..<" let output: [Token] = [.operator("..<", .none)] XCTAssertEqual(tokenize(input), output) } func testAngleBracketSuffixedOperator2() { let input = "a..<b" let output: [Token] = [ .identifier("a"), .operator("..<", .infix), .identifier("b"), ] XCTAssertEqual(tokenize(input), output) } func testUnicodeOperator() { let input = "≥" let output: [Token] = [.operator("≥", .none)] XCTAssertEqual(tokenize(input), output) } func testOperatorFollowedByComment() { let input = "a+/* b */b" let output: [Token] = [ .identifier("a"), .operator("+", .postfix), .startOfScope("/*"), .space(" "), .commentBody("b"), .space(" "), .endOfScope("*/"), .identifier("b"), ] XCTAssertEqual(tokenize(input), output) } func testOperatorPrecededBySpaceFollowedByComment() { let input = "a +/* b */b" let output: [Token] = [ .identifier("a"), .space(" "), .operator("+", .infix), .startOfScope("/*"), .space(" "), .commentBody("b"), .space(" "), .endOfScope("*/"), .identifier("b"), ] XCTAssertEqual(tokenize(input), output) } func testOperatorPrecededByComment() { let input = "a/* a */-b" let output: [Token] = [ .identifier("a"), .startOfScope("/*"), .space(" "), .commentBody("a"), .space(" "), .endOfScope("*/"), .operator("-", .prefix), .identifier("b"), ] XCTAssertEqual(tokenize(input), output) } func testOperatorPrecededByCommentFollowedBySpace() { let input = "a/* a */- b" let output: [Token] = [ .identifier("a"), .startOfScope("/*"), .space(" "), .commentBody("a"), .space(" "), .endOfScope("*/"), .operator("-", .infix), .space(" "), .identifier("b"), ] XCTAssertEqual(tokenize(input), output) } func testOperatorMayContainDotIfStartsWithDot() { let input = ".*.." let output: [Token] = [.operator(".*..", .none)] XCTAssertEqual(tokenize(input), output) } func testOperatorMayNotContainDotUnlessStartsWithDot() { let input = "*.." let output: [Token] = [ .operator("*", .prefix), // TODO: should be postfix .operator("..", .none), ] XCTAssertEqual(tokenize(input), output) } func testOperatorStitchingDoesNotCreateIllegalToken() { let input = "a*..b" let output: [Token] = [ .identifier("a"), .operator("*", .postfix), .operator("..", .infix), .identifier("b"), ] XCTAssertEqual(tokenize(input), output) } func testNullCoalescingOperator() { let input = "foo ?? bar" let output: [Token] = [ .identifier("foo"), .space(" "), .operator("??", .infix), .space(" "), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testTernary() { let input = "a ? b() : c" let output: [Token] = [ .identifier("a"), .space(" "), .operator("?", .infix), .space(" "), .identifier("b"), .startOfScope("("), .endOfScope(")"), .space(" "), .operator(":", .infix), .space(" "), .identifier("c"), ] XCTAssertEqual(tokenize(input), output) } func testTernaryWithOddSpacing() { let input = "a ?b(): c" let output: [Token] = [ .identifier("a"), .space(" "), .operator("?", .infix), .identifier("b"), .startOfScope("("), .endOfScope(")"), .operator(":", .infix), .space(" "), .identifier("c"), ] XCTAssertEqual(tokenize(input), output) } func testInfixOperatorBeforeLinebreak() { let input = "foo +\nbar" let output: [Token] = [ .identifier("foo"), .space(" "), .operator("+", .infix), .linebreak("\n", 1), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testInfixOperatorAfterLinebreak() { let input = "foo\n+ bar" let output: [Token] = [ .identifier("foo"), .linebreak("\n", 1), .operator("+", .infix), .space(" "), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testInfixOperatorBeforeComment() { let input = "foo +/**/bar" let output: [Token] = [ .identifier("foo"), .space(" "), .operator("+", .infix), .startOfScope("/*"), .endOfScope("*/"), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testInfixOperatorAfterComment() { let input = "foo/**/+ bar" let output: [Token] = [ .identifier("foo"), .startOfScope("/*"), .endOfScope("*/"), .operator("+", .infix), .space(" "), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testPrefixMinusBeforeMember() { let input = "-.foo" let output: [Token] = [ .operator("-", .prefix), .operator(".", .prefix), .identifier("foo"), ] XCTAssertEqual(tokenize(input), output) } func testInfixMinusBeforeMember() { let input = "foo - .bar" let output: [Token] = [ .identifier("foo"), .space(" "), .operator("-", .infix), .space(" "), .operator(".", .prefix), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testPostfixOperatorBeforeMember() { let input = "foo′.bar" let output: [Token] = [ .identifier("foo"), .operator("′", .postfix), .operator(".", .infix), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testNotOperator() { let input = "!foo" let output: [Token] = [ .operator("!", .prefix), .identifier("foo"), ] XCTAssertEqual(tokenize(input), output) } func testNotOperatorAfterKeyword() { let input = "return !foo" let output: [Token] = [ .keyword("return"), .space(" "), .operator("!", .prefix), .identifier("foo"), ] XCTAssertEqual(tokenize(input), output) } func testStringDotMethod() { let input = "\"foo\".isEmpty" let output: [Token] = [ .startOfScope("\""), .stringBody("foo"), .endOfScope("\""), .operator(".", .infix), .identifier("isEmpty"), ] XCTAssertEqual(tokenize(input), output) } func testStringAssignment() { let input = "foo = \"foo\"" let output: [Token] = [ .identifier("foo"), .space(" "), .operator("=", .infix), .space(" "), .startOfScope("\""), .stringBody("foo"), .endOfScope("\""), ] XCTAssertEqual(tokenize(input), output) } func testInfixNotEqualsInParens() { let input = "(!=)" let output: [Token] = [ .startOfScope("("), .operator("!=", .none), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } // MARK: chevrons (might be operators or generics) func testLessThanGreaterThan() { let input = "a<b == a>c" let output: [Token] = [ .identifier("a"), .operator("<", .infix), .identifier("b"), .space(" "), .operator("==", .infix), .space(" "), .identifier("a"), .operator(">", .infix), .identifier("c"), ] XCTAssertEqual(tokenize(input), output) } func testLessThanGreaterThanFollowedByOperator() { let input = "a > -x, a<x, b > -y, b<y" let output: [Token] = [ .identifier("a"), .space(" "), .operator(">", .infix), .space(" "), .operator("-", .prefix), .identifier("x"), .delimiter(","), .space(" "), .identifier("a"), .operator("<", .infix), .identifier("x"), .delimiter(","), .space(" "), .identifier("b"), .space(" "), .operator(">", .infix), .space(" "), .operator("-", .prefix), .identifier("y"), .delimiter(","), .space(" "), .identifier("b"), .operator("<", .infix), .identifier("y"), ] XCTAssertEqual(tokenize(input), output) } func testGenericTypeAmpersandProtocol() { let input = "Foo<Int> & Bar" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .identifier("Int"), .endOfScope(">"), .space(" "), .operator("&", .infix), .space(" "), .identifier("Bar"), ] XCTAssertEqual(tokenize(input), output) } func testCustomChevronOperatorFollowedByParen() { let input = "foo <?> (bar)" let output: [Token] = [ .identifier("foo"), .space(" "), .operator("<?>", .infix), .space(" "), .startOfScope("("), .identifier("bar"), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testRightShift() { let input = "a>>b" let output: [Token] = [ .identifier("a"), .operator(">>", .infix), .identifier("b"), ] XCTAssertEqual(tokenize(input), output) } func testLeftShift() { let input = "a<<b" let output: [Token] = [ .identifier("a"), .operator("<<", .infix), .identifier("b"), ] XCTAssertEqual(tokenize(input), output) } func testTripleShift() { let input = "a>>>b" let output: [Token] = [ .identifier("a"), .operator(">>>", .infix), .identifier("b"), ] XCTAssertEqual(tokenize(input), output) } func testRightShiftEquals() { let input = "a>>=b" let output: [Token] = [ .identifier("a"), .operator(">>=", .infix), .identifier("b"), ] XCTAssertEqual(tokenize(input), output) } func testLeftShiftInsideTernary() { let input = "foo ? bar<<24 : 0" let output: [Token] = [ .identifier("foo"), .space(" "), .operator("?", .infix), .space(" "), .identifier("bar"), .operator("<<", .infix), .number("24", .integer), .space(" "), .operator(":", .infix), .space(" "), .number("0", .integer), ] XCTAssertEqual(tokenize(input), output) } func testBitshiftThatLooksLikeAGeneric() { let input = "a<b, b<c, d>>e" let output: [Token] = [ .identifier("a"), .operator("<", .infix), .identifier("b"), .delimiter(","), .space(" "), .identifier("b"), .operator("<", .infix), .identifier("c"), .delimiter(","), .space(" "), .identifier("d"), .operator(">>", .infix), .identifier("e"), ] XCTAssertEqual(tokenize(input), output) } func testBasicGeneric() { let input = "Foo<Bar, Baz>" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .identifier("Bar"), .delimiter(","), .space(" "), .identifier("Baz"), .endOfScope(">"), ] XCTAssertEqual(tokenize(input), output) } func testNestedGenerics() { let input = "Foo<Bar<Baz>>" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .identifier("Bar"), .startOfScope("<"), .identifier("Baz"), .endOfScope(">"), .endOfScope(">"), ] XCTAssertEqual(tokenize(input), output) } func testFunctionThatLooksLikeGenericType() { let input = "y<CGRectGetMaxY(r)" let output: [Token] = [ .identifier("y"), .operator("<", .infix), .identifier("CGRectGetMaxY"), .startOfScope("("), .identifier("r"), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testGenericClassDeclaration() { let input = "class Foo<T,U> {}" let output: [Token] = [ .keyword("class"), .space(" "), .identifier("Foo"), .startOfScope("<"), .identifier("T"), .delimiter(","), .identifier("U"), .endOfScope(">"), .space(" "), .startOfScope("{"), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testGenericSubclassDeclaration() { let input = "class Foo<T,U>: Bar" let output: [Token] = [ .keyword("class"), .space(" "), .identifier("Foo"), .startOfScope("<"), .identifier("T"), .delimiter(","), .identifier("U"), .endOfScope(">"), .delimiter(":"), .space(" "), .identifier("Bar"), ] XCTAssertEqual(tokenize(input), output) } func testGenericFunctionDeclaration() { let input = "func foo<T>(bar:T)" let output: [Token] = [ .keyword("func"), .space(" "), .identifier("foo"), .startOfScope("<"), .identifier("T"), .endOfScope(">"), .startOfScope("("), .identifier("bar"), .delimiter(":"), .identifier("T"), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testGenericClassInit() { let input = "foo = Foo<Int,String>()" let output: [Token] = [ .identifier("foo"), .space(" "), .operator("=", .infix), .space(" "), .identifier("Foo"), .startOfScope("<"), .identifier("Int"), .delimiter(","), .identifier("String"), .endOfScope(">"), .startOfScope("("), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testGenericFollowedByDot() { let input = "Foo<Bar>.baz()" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .identifier("Bar"), .endOfScope(">"), .operator(".", .infix), .identifier("baz"), .startOfScope("("), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testConstantThatLooksLikeGenericType() { let input = "(y<Pi)" let output: [Token] = [ .startOfScope("("), .identifier("y"), .operator("<", .infix), .identifier("Pi"), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testTupleOfBoolsThatLooksLikeGeneric() { let input = "(Foo<T,U>V)" let output: [Token] = [ .startOfScope("("), .identifier("Foo"), .operator("<", .infix), .identifier("T"), .delimiter(","), .identifier("U"), .operator(">", .infix), .identifier("V"), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testTupleOfBoolsThatReallyLooksLikeGeneric() { let input = "(Foo<T,U>=V)" let output: [Token] = [ .startOfScope("("), .identifier("Foo"), .operator("<", .infix), .identifier("T"), .delimiter(","), .identifier("U"), .operator(">=", .infix), .identifier("V"), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testGenericDeclarationThatLooksLikeTwoExpressions() { let input = "let d: a < b, b > = c" let output: [Token] = [ .keyword("let"), .space(" "), .identifier("d"), .delimiter(":"), .space(" "), .identifier("a"), .space(" "), .startOfScope("<"), .space(" "), .identifier("b"), .delimiter(","), .space(" "), .identifier("b"), .space(" "), .endOfScope(">"), .space(" "), .operator("=", .infix), .space(" "), .identifier("c"), ] XCTAssertEqual(tokenize(input), output) } func testGenericDeclarationWithoutSpace() { let input = "let foo: Foo<String,Int>=[]" let output: [Token] = [ .keyword("let"), .space(" "), .identifier("foo"), .delimiter(":"), .space(" "), .identifier("Foo"), .startOfScope("<"), .identifier("String"), .delimiter(","), .identifier("Int"), .endOfScope(">"), .operator("=", .infix), .startOfScope("["), .endOfScope("]"), ] XCTAssertEqual(tokenize(input), output) } func testGenericClassInitThatLooksLikeTuple() { let input = "(Foo<String,Int>(Bar))" let output: [Token] = [ .startOfScope("("), .identifier("Foo"), .startOfScope("<"), .identifier("String"), .delimiter(","), .identifier("Int"), .endOfScope(">"), .startOfScope("("), .identifier("Bar"), .endOfScope(")"), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testCustomChevronOperatorThatLooksLikeGeneric() { let input = "Foo<Bar,Baz>>>5" let output: [Token] = [ .identifier("Foo"), .operator("<", .infix), .identifier("Bar"), .delimiter(","), .identifier("Baz"), .operator(">>>", .infix), .number("5", .integer), ] XCTAssertEqual(tokenize(input), output) } func testGenericAsFunctionType() { let input = "Foo<Bar,Baz>->Void" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .identifier("Bar"), .delimiter(","), .identifier("Baz"), .endOfScope(">"), .operator("->", .infix), .identifier("Void"), ] XCTAssertEqual(tokenize(input), output) } func testGenericContainingFunctionType() { let input = "Foo<(Bar)->Baz>" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .startOfScope("("), .identifier("Bar"), .endOfScope(")"), .operator("->", .infix), .identifier("Baz"), .endOfScope(">"), ] XCTAssertEqual(tokenize(input), output) } func testGenericContainingFunctionTypeWithMultipleArguments() { let input = "Foo<(Bar,Baz)->Quux>" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .startOfScope("("), .identifier("Bar"), .delimiter(","), .identifier("Baz"), .endOfScope(")"), .operator("->", .infix), .identifier("Quux"), .endOfScope(">"), ] XCTAssertEqual(tokenize(input), output) } func testGenericContainingMultipleFunctionTypes() { let input = "Foo<(Bar)->Void,(Baz)->Void>" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .startOfScope("("), .identifier("Bar"), .endOfScope(")"), .operator("->", .infix), .identifier("Void"), .delimiter(","), .startOfScope("("), .identifier("Baz"), .endOfScope(")"), .operator("->", .infix), .identifier("Void"), .endOfScope(">"), ] XCTAssertEqual(tokenize(input), output) } func testGenericContainingArrayType() { let input = "Foo<[Bar],Baz>" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .startOfScope("["), .identifier("Bar"), .endOfScope("]"), .delimiter(","), .identifier("Baz"), .endOfScope(">"), ] XCTAssertEqual(tokenize(input), output) } func testGenericContainingTupleType() { let input = "Foo<(Bar,Baz)>" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .startOfScope("("), .identifier("Bar"), .delimiter(","), .identifier("Baz"), .endOfScope(")"), .endOfScope(">"), ] XCTAssertEqual(tokenize(input), output) } func testGenericContainingArrayAndTupleType() { let input = "Foo<[Bar],(Baz)>" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .startOfScope("["), .identifier("Bar"), .endOfScope("]"), .delimiter(","), .startOfScope("("), .identifier("Baz"), .endOfScope(")"), .endOfScope(">"), ] XCTAssertEqual(tokenize(input), output) } func testGenericFollowedByIn() { let input = "Foo<Bar,Baz> in" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .identifier("Bar"), .delimiter(","), .identifier("Baz"), .endOfScope(">"), .space(" "), .keyword("in"), ] XCTAssertEqual(tokenize(input), output) } func testOptionalGenericType() { let input = "Foo<T?,U>" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .identifier("T"), .operator("?", .postfix), .delimiter(","), .identifier("U"), .endOfScope(">"), ] XCTAssertEqual(tokenize(input), output) } func testTrailingOptionalGenericType() { let input = "Foo<T?>" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .identifier("T"), .operator("?", .postfix), .endOfScope(">"), ] XCTAssertEqual(tokenize(input), output) } func testNestedOptionalGenericType() { let input = "Foo<Bar<T?>>" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .identifier("Bar"), .startOfScope("<"), .identifier("T"), .operator("?", .postfix), .endOfScope(">"), .endOfScope(">"), ] XCTAssertEqual(tokenize(input), output) } func testDeeplyNestedGenericType() { let input = "Foo<Bar<Baz<Quux>>>" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .identifier("Bar"), .startOfScope("<"), .identifier("Baz"), .startOfScope("<"), .identifier("Quux"), .endOfScope(">"), .endOfScope(">"), .endOfScope(">"), ] XCTAssertEqual(tokenize(input), output) } func testGenericFollowedByGreaterThan() { let input = "Foo<T>\na=b>c" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .identifier("T"), .endOfScope(">"), .linebreak("\n", 1), .identifier("a"), .operator("=", .infix), .identifier("b"), .operator(">", .infix), .identifier("c"), ] XCTAssertEqual(tokenize(input), output) } func testGenericFollowedByElipsis() { let input = "foo<T>(bar: Baz<T>...)" let output: [Token] = [ .identifier("foo"), .startOfScope("<"), .identifier("T"), .endOfScope(">"), .startOfScope("("), .identifier("bar"), .delimiter(":"), .space(" "), .identifier("Baz"), .startOfScope("<"), .identifier("T"), .endOfScope(">"), .operator("...", .postfix), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testGenericOperatorFunction() { let input = "func ==<T>()" let output: [Token] = [ .keyword("func"), .space(" "), .operator("==", .none), .startOfScope("<"), .identifier("T"), .endOfScope(">"), .startOfScope("("), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testGenericCustomOperatorFunction() { let input = "func ∘<T,U>()" let output: [Token] = [ .keyword("func"), .space(" "), .operator("∘", .none), .startOfScope("<"), .identifier("T"), .delimiter(","), .identifier("U"), .endOfScope(">"), .startOfScope("("), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testGenericTypeContainingAmpersand() { let input = "Foo<Bar: Baz & Quux>" let output: [Token] = [ .identifier("Foo"), .startOfScope("<"), .identifier("Bar"), .delimiter(":"), .space(" "), .identifier("Baz"), .space(" "), .operator("&", .infix), .space(" "), .identifier("Quux"), .endOfScope(">"), ] XCTAssertEqual(tokenize(input), output) } func testCustomOperatorStartingWithOpenChevron() { let input = "foo<--bar" let output: [Token] = [ .identifier("foo"), .operator("<--", .infix), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testCustomOperatorEndingWithCloseChevron() { let input = "foo-->bar" let output: [Token] = [ .identifier("foo"), .operator("-->", .infix), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testGreaterThanLessThanOperator() { let input = "foo><bar" let output: [Token] = [ .identifier("foo"), .operator("><", .infix), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testLessThanGreaterThanOperator() { let input = "foo<>bar" let output: [Token] = [ .identifier("foo"), .operator("<>", .infix), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testGenericFollowedByAssign() { let input = "let foo: Bar<Baz> = 5" let output: [Token] = [ .keyword("let"), .space(" "), .identifier("foo"), .delimiter(":"), .space(" "), .identifier("Bar"), .startOfScope("<"), .identifier("Baz"), .endOfScope(">"), .space(" "), .operator("=", .infix), .space(" "), .number("5", .integer), ] XCTAssertEqual(tokenize(input), output) } func testGenericInFailableInit() { let input = "init?<T>()" let output: [Token] = [ .keyword("init"), .operator("?", .postfix), .startOfScope("<"), .identifier("T"), .endOfScope(">"), .startOfScope("("), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testInfixEqualsOperatorWithSpace() { let input = "operator == {}" let output: [Token] = [ .keyword("operator"), .space(" "), .operator("==", .none), .space(" "), .startOfScope("{"), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testInfixEqualsOperatorWithoutSpace() { let input = "operator =={}" let output: [Token] = [ .keyword("operator"), .space(" "), .operator("==", .none), .startOfScope("{"), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testInfixQuestionMarkChevronOperatorWithSpace() { let input = "operator ?< {}" let output: [Token] = [ .keyword("operator"), .space(" "), .operator("?<", .none), .space(" "), .startOfScope("{"), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testInfixQuestionMarkChevronOperatorWithoutSpace() { let input = "operator ?<{}" let output: [Token] = [ .keyword("operator"), .space(" "), .operator("?<", .none), .startOfScope("{"), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testInfixEqualsDoubleChevronOperator() { let input = "infix operator =<<" let output: [Token] = [ .identifier("infix"), .space(" "), .keyword("operator"), .space(" "), .operator("=<<", .none), ] XCTAssertEqual(tokenize(input), output) } func testInfixEqualsDoubleChevronGenericFunction() { let input = "func =<<<T>()" let output: [Token] = [ .keyword("func"), .space(" "), .operator("=<<", .none), .startOfScope("<"), .identifier("T"), .endOfScope(">"), .startOfScope("("), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testHalfOpenRangeFollowedByComment() { let input = "1..<5\n//comment" let output: [Token] = [ .number("1", .integer), .operator("..<", .infix), .number("5", .integer), .linebreak("\n", 1), .startOfScope("//"), .commentBody("comment"), ] XCTAssertEqual(tokenize(input), output) } func testSortAscending() { let input = "sort(by: <)" let output: [Token] = [ .identifier("sort"), .startOfScope("("), .identifier("by"), .delimiter(":"), .space(" "), .operator("<", .none), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testSortDescending() { let input = "sort(by: >)" let output: [Token] = [ .identifier("sort"), .startOfScope("("), .identifier("by"), .delimiter(":"), .space(" "), .operator(">", .none), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } func testGenericsWithWhereClause() { let input = "<A where A.B == C>" let output: [Token] = [ .startOfScope("<"), .identifier("A"), .space(" "), .keyword("where"), .space(" "), .identifier("A"), .operator(".", .infix), .identifier("B"), .space(" "), .operator("==", .infix), .space(" "), .identifier("C"), .endOfScope(">"), ] XCTAssertEqual(tokenize(input), output) } func testIfLessThanIfGreaterThan() { let input = "if x < 0 {}\nif y > (0) {}" let output: [Token] = [ .keyword("if"), .space(" "), .identifier("x"), .space(" "), .operator("<", .infix), .space(" "), .number("0", .integer), .space(" "), .startOfScope("{"), .endOfScope("}"), .linebreak("\n", 1), .keyword("if"), .space(" "), .identifier("y"), .space(" "), .operator(">", .infix), .space(" "), .startOfScope("("), .number("0", .integer), .endOfScope(")"), .space(" "), .startOfScope("{"), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testLessThanEnumCase() { let input = "XCTAssertFalse(.never < .never)" let output: [Token] = [ .identifier("XCTAssertFalse"), .startOfScope("("), .operator(".", .prefix), .identifier("never"), .space(" "), .operator("<", .infix), .space(" "), .operator(".", .prefix), .identifier("never"), .endOfScope(")"), ] XCTAssertEqual(tokenize(input), output) } // MARK: optionals func testAssignOptional() { let input = "Int?=nil" let output: [Token] = [ .identifier("Int"), .operator("?", .postfix), .operator("=", .infix), .identifier("nil"), ] XCTAssertEqual(tokenize(input), output) } func testQuestionMarkEqualOperator() { let input = "foo ?= bar" let output: [Token] = [ .identifier("foo"), .space(" "), .operator("?=", .infix), .space(" "), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testOptionalChaining() { let input = "foo!.bar" let output: [Token] = [ .identifier("foo"), .operator("!", .postfix), .operator(".", .infix), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testMultipleOptionalChaining() { let input = "foo?!?.bar" let output: [Token] = [ .identifier("foo"), .operator("?", .postfix), .operator("!", .postfix), .operator("?", .postfix), .operator(".", .infix), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testSplitLineOptionalChaining() { let input = "foo?\n .bar" let output: [Token] = [ .identifier("foo"), .operator("?", .postfix), .linebreak("\n", 1), .space(" "), .operator(".", .infix), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } // MARK: case statements func testSingleLineEnum() { let input = "enum Foo {case Bar, Baz}" let output: [Token] = [ .keyword("enum"), .space(" "), .identifier("Foo"), .space(" "), .startOfScope("{"), .keyword("case"), .space(" "), .identifier("Bar"), .delimiter(","), .space(" "), .identifier("Baz"), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testSingleLineGenericEnum() { let input = "enum Foo<T> {case Bar, Baz}" let output: [Token] = [ .keyword("enum"), .space(" "), .identifier("Foo"), .startOfScope("<"), .identifier("T"), .endOfScope(">"), .space(" "), .startOfScope("{"), .keyword("case"), .space(" "), .identifier("Bar"), .delimiter(","), .space(" "), .identifier("Baz"), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testMultilineLineEnum() { let input = "enum Foo {\ncase Bar\ncase Baz\n}" let output: [Token] = [ .keyword("enum"), .space(" "), .identifier("Foo"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .keyword("case"), .space(" "), .identifier("Bar"), .linebreak("\n", 2), .keyword("case"), .space(" "), .identifier("Baz"), .linebreak("\n", 3), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testSwitchStatement() { let input = "switch x {\ncase 1:\nbreak\ncase 2:\nbreak\ndefault:\nbreak\n}" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("x"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .endOfScope("case"), .space(" "), .number("1", .integer), .startOfScope(":"), .linebreak("\n", 2), .keyword("break"), .linebreak("\n", 3), .endOfScope("case"), .space(" "), .number("2", .integer), .startOfScope(":"), .linebreak("\n", 4), .keyword("break"), .linebreak("\n", 5), .endOfScope("default"), .startOfScope(":"), .linebreak("\n", 6), .keyword("break"), .linebreak("\n", 7), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testSwitchStatementWithEnumCases() { let input = "switch x {\ncase.foo,\n.bar:\nbreak\ndefault:\nbreak\n}" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("x"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .endOfScope("case"), .operator(".", .prefix), .identifier("foo"), .delimiter(","), .linebreak("\n", 2), .operator(".", .prefix), .identifier("bar"), .startOfScope(":"), .linebreak("\n", 3), .keyword("break"), .linebreak("\n", 4), .endOfScope("default"), .startOfScope(":"), .linebreak("\n", 5), .keyword("break"), .linebreak("\n", 6), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testSwitchCaseContainingDictionaryDefault() { let input = "switch x {\ncase y: foo[\"z\", default: []]\n}" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("x"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .endOfScope("case"), .space(" "), .identifier("y"), .startOfScope(":"), .space(" "), .identifier("foo"), .startOfScope("["), .startOfScope("\""), .stringBody("z"), .endOfScope("\""), .delimiter(","), .space(" "), .identifier("default"), .delimiter(":"), .space(" "), .startOfScope("["), .endOfScope("]"), .endOfScope("]"), .linebreak("\n", 2), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testSwitchCaseIsDictionaryStatement() { let input = "switch x {\ncase foo is [Key: Value]:\nbreak\ndefault:\nbreak\n}" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("x"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .endOfScope("case"), .space(" "), .identifier("foo"), .space(" "), .keyword("is"), .space(" "), .startOfScope("["), .identifier("Key"), .delimiter(":"), .space(" "), .identifier("Value"), .endOfScope("]"), .startOfScope(":"), .linebreak("\n", 2), .keyword("break"), .linebreak("\n", 3), .endOfScope("default"), .startOfScope(":"), .linebreak("\n", 4), .keyword("break"), .linebreak("\n", 5), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testSwitchCaseContainingCaseIdentifier() { let input = "switch x {\ncase 1:\nfoo.case\ndefault:\nbreak\n}" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("x"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .endOfScope("case"), .space(" "), .number("1", .integer), .startOfScope(":"), .linebreak("\n", 2), .identifier("foo"), .operator(".", .infix), .identifier("case"), .linebreak("\n", 3), .endOfScope("default"), .startOfScope(":"), .linebreak("\n", 4), .keyword("break"), .linebreak("\n", 5), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testSwitchCaseContainingDefaultIdentifier() { let input = "switch x {\ncase 1:\nfoo.default\ndefault:\nbreak\n}" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("x"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .endOfScope("case"), .space(" "), .number("1", .integer), .startOfScope(":"), .linebreak("\n", 2), .identifier("foo"), .operator(".", .infix), .identifier("default"), .linebreak("\n", 3), .endOfScope("default"), .startOfScope(":"), .linebreak("\n", 4), .keyword("break"), .linebreak("\n", 5), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testSwitchCaseContainingIfCase() { let input = "switch x {\ncase 1:\nif case x = y {}\ndefault:\nbreak\n}" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("x"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .endOfScope("case"), .space(" "), .number("1", .integer), .startOfScope(":"), .linebreak("\n", 2), .keyword("if"), .space(" "), .keyword("case"), .space(" "), .identifier("x"), .space(" "), .operator("=", .infix), .space(" "), .identifier("y"), .space(" "), .startOfScope("{"), .endOfScope("}"), .linebreak("\n", 3), .endOfScope("default"), .startOfScope(":"), .linebreak("\n", 4), .keyword("break"), .linebreak("\n", 5), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testSwitchCaseContainingIfCaseCommaCase() { let input = "switch x {\ncase 1:\nif case w = x, case y = z {}\ndefault:\nbreak\n}" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("x"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .endOfScope("case"), .space(" "), .number("1", .integer), .startOfScope(":"), .linebreak("\n", 2), .keyword("if"), .space(" "), .keyword("case"), .space(" "), .identifier("w"), .space(" "), .operator("=", .infix), .space(" "), .identifier("x"), .delimiter(","), .space(" "), .keyword("case"), .space(" "), .identifier("y"), .space(" "), .operator("=", .infix), .space(" "), .identifier("z"), .space(" "), .startOfScope("{"), .endOfScope("}"), .linebreak("\n", 3), .endOfScope("default"), .startOfScope(":"), .linebreak("\n", 4), .keyword("break"), .linebreak("\n", 5), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testSwitchCaseContainingGuardCase() { let input = "switch x {\ncase 1:\nguard case x = y else {}\ndefault:\nbreak\n}" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("x"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .endOfScope("case"), .space(" "), .number("1", .integer), .startOfScope(":"), .linebreak("\n", 2), .keyword("guard"), .space(" "), .keyword("case"), .space(" "), .identifier("x"), .space(" "), .operator("=", .infix), .space(" "), .identifier("y"), .space(" "), .keyword("else"), .space(" "), .startOfScope("{"), .endOfScope("}"), .linebreak("\n", 3), .endOfScope("default"), .startOfScope(":"), .linebreak("\n", 4), .keyword("break"), .linebreak("\n", 5), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testSwitchFollowedByEnum() { let input = "switch x {\ncase y: break\ndefault: break\n}\nenum Foo {\ncase z\n}" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("x"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .endOfScope("case"), .space(" "), .identifier("y"), .startOfScope(":"), .space(" "), .keyword("break"), .linebreak("\n", 2), .endOfScope("default"), .startOfScope(":"), .space(" "), .keyword("break"), .linebreak("\n", 3), .endOfScope("}"), .linebreak("\n", 4), .keyword("enum"), .space(" "), .identifier("Foo"), .space(" "), .startOfScope("{"), .linebreak("\n", 5), .keyword("case"), .space(" "), .identifier("z"), .linebreak("\n", 6), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testSwitchCaseContainingSwitchIdentifierFollowedByEnum() { let input = "switch x {\ncase 1:\nfoo.switch\ndefault:\nbreak\n}\nenum Foo {\ncase z\n}" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("x"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .endOfScope("case"), .space(" "), .number("1", .integer), .startOfScope(":"), .linebreak("\n", 2), .identifier("foo"), .operator(".", .infix), .identifier("switch"), .linebreak("\n", 3), .endOfScope("default"), .startOfScope(":"), .linebreak("\n", 4), .keyword("break"), .linebreak("\n", 5), .endOfScope("}"), .linebreak("\n", 6), .keyword("enum"), .space(" "), .identifier("Foo"), .space(" "), .startOfScope("{"), .linebreak("\n", 7), .keyword("case"), .space(" "), .identifier("z"), .linebreak("\n", 8), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testSwitchCaseContainingRangeOperator() { let input = "switch x {\ncase 0 ..< 2:\nbreak\ndefault:\nbreak\n}" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("x"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .endOfScope("case"), .space(" "), .number("0", .integer), .space(" "), .operator("..<", .infix), .space(" "), .number("2", .integer), .startOfScope(":"), .linebreak("\n", 2), .keyword("break"), .linebreak("\n", 3), .endOfScope("default"), .startOfScope(":"), .linebreak("\n", 4), .keyword("break"), .linebreak("\n", 5), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testEnumDeclarationInsideSwitchCase() { let input = "switch x {\ncase y:\nenum Foo {\ncase z\n}\nbreak\ndefault: break\n}" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("x"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .endOfScope("case"), .space(" "), .identifier("y"), .startOfScope(":"), .linebreak("\n", 2), .keyword("enum"), .space(" "), .identifier("Foo"), .space(" "), .startOfScope("{"), .linebreak("\n", 3), .keyword("case"), .space(" "), .identifier("z"), .linebreak("\n", 4), .endOfScope("}"), .linebreak("\n", 5), .keyword("break"), .linebreak("\n", 6), .endOfScope("default"), .startOfScope(":"), .space(" "), .keyword("break"), .linebreak("\n", 7), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testDefaultAfterWhereCondition() { let input = "switch foo {\ncase _ where baz < quux:\nbreak\ndefault:\nbreak\n}" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("foo"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .endOfScope("case"), .space(" "), .identifier("_"), .space(" "), .keyword("where"), .space(" "), .identifier("baz"), .space(" "), .operator("<", .infix), .space(" "), .identifier("quux"), .startOfScope(":"), .linebreak("\n", 2), .keyword("break"), .linebreak("\n", 3), .endOfScope("default"), .startOfScope(":"), .linebreak("\n", 4), .keyword("break"), .linebreak("\n", 5), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testEnumWithConditionalCase() { let input = "enum Foo {\ncase bar\n#if baz\ncase baz\n#endif\n}" let output: [Token] = [ .keyword("enum"), .space(" "), .identifier("Foo"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .keyword("case"), .space(" "), .identifier("bar"), .linebreak("\n", 2), .startOfScope("#if"), .space(" "), .identifier("baz"), .linebreak("\n", 3), .keyword("case"), .space(" "), .identifier("baz"), .linebreak("\n", 4), .endOfScope("#endif"), .linebreak("\n", 5), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testSwitchWithConditionalCase() { let input = "switch foo {\ncase bar:\nbreak\n#if baz\ndefault:\nbreak\n#endif\n}" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("foo"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .endOfScope("case"), .space(" "), .identifier("bar"), .startOfScope(":"), .linebreak("\n", 2), .keyword("break"), .linebreak("\n", 3), .startOfScope("#if"), .space(" "), .identifier("baz"), .linebreak("\n", 4), .endOfScope("default"), .startOfScope(":"), .linebreak("\n", 5), .keyword("break"), .linebreak("\n", 6), .endOfScope("#endif"), .linebreak("\n", 7), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testSwitchWithConditionalCase2() { let input = "switch foo {\n#if baz\ndefault:\nbreak\n#else\ncase bar:\nbreak\n#endif\n}" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("foo"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .startOfScope("#if"), .space(" "), .identifier("baz"), .linebreak("\n", 2), .endOfScope("default"), .startOfScope(":"), .linebreak("\n", 3), .keyword("break"), .linebreak("\n", 4), .keyword("#else"), .linebreak("\n", 5), .endOfScope("case"), .space(" "), .identifier("bar"), .startOfScope(":"), .linebreak("\n", 6), .keyword("break"), .linebreak("\n", 7), .endOfScope("#endif"), .linebreak("\n", 8), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testSwitchWithConditionalCase3() { let input = "switch foo {\n#if baz\ncase foo:\nbreak\n#endif\ncase bar:\nbreak\n}" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("foo"), .space(" "), .startOfScope("{"), .linebreak("\n", 1), .startOfScope("#if"), .space(" "), .identifier("baz"), .linebreak("\n", 2), .endOfScope("case"), .space(" "), .identifier("foo"), .startOfScope(":"), .linebreak("\n", 3), .keyword("break"), .linebreak("\n", 4), .endOfScope("#endif"), .linebreak("\n", 5), .endOfScope("case"), .space(" "), .identifier("bar"), .startOfScope(":"), .linebreak("\n", 6), .keyword("break"), .linebreak("\n", 7), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testGenericEnumCase() { let input = "enum Foo<T>: Bar where T: Bar { case bar }" let output: [Token] = [ .keyword("enum"), .space(" "), .identifier("Foo"), .startOfScope("<"), .identifier("T"), .endOfScope(">"), .delimiter(":"), .space(" "), .identifier("Bar"), .space(" "), .keyword("where"), .space(" "), .identifier("T"), .delimiter(":"), .space(" "), .identifier("Bar"), .space(" "), .startOfScope("{"), .space(" "), .keyword("case"), .space(" "), .identifier("bar"), .space(" "), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } func testCaseEnumValueWithoutSpaces() { let input = "switch x { case.foo:break }" let output: [Token] = [ .keyword("switch"), .space(" "), .identifier("x"), .space(" "), .startOfScope("{"), .space(" "), .endOfScope("case"), .operator(".", .prefix), .identifier("foo"), .startOfScope(":"), .keyword("break"), .space(" "), .endOfScope("}"), ] XCTAssertEqual(tokenize(input), output) } // MARK: dot prefix func testEnumValueInDictionaryLiteral() { let input = "[.foo:.bar]" let output: [Token] = [ .startOfScope("["), .operator(".", .prefix), .identifier("foo"), .delimiter(":"), .operator(".", .prefix), .identifier("bar"), .endOfScope("]"), ] XCTAssertEqual(tokenize(input), output) } // MARK: linebreaks func testLF() { let input = "foo\nbar" let output: [Token] = [ .identifier("foo"), .linebreak("\n", 1), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testCR() { let input = "foo\rbar" let output: [Token] = [ .identifier("foo"), .linebreak("\r", 1), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testCRLF() { let input = "foo\r\nbar" let output: [Token] = [ .identifier("foo"), .linebreak("\r\n", 1), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testCRLFAfterComment() { let input = "//foo\r\n//bar" let output: [Token] = [ .startOfScope("//"), .commentBody("foo"), .linebreak("\r\n", 1), .startOfScope("//"), .commentBody("bar"), ] XCTAssertEqual(tokenize(input), output) } func testCRLFInMultilineComment() { let input = "/*foo\r\nbar*/" let output: [Token] = [ .startOfScope("/*"), .commentBody("foo"), .linebreak("\r\n", 1), .commentBody("bar"), .endOfScope("*/"), ] XCTAssertEqual(tokenize(input), output) } // MARK: keypaths func testNamespacedKeyPath() { let input = "let foo = \\Foo.bar" let output: [Token] = [ .keyword("let"), .space(" "), .identifier("foo"), .space(" "), .operator("=", .infix), .space(" "), .operator("\\", .prefix), .identifier("Foo"), .operator(".", .infix), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testAnonymousKeyPath() { let input = "let foo = \\.bar" let output: [Token] = [ .keyword("let"), .space(" "), .identifier("foo"), .space(" "), .operator("=", .infix), .space(" "), .operator("\\", .prefix), .operator(".", .prefix), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } func testAnonymousSubscriptKeyPath() { let input = "let foo = \\.[0].bar" let output: [Token] = [ .keyword("let"), .space(" "), .identifier("foo"), .space(" "), .operator("=", .infix), .space(" "), .operator("\\", .prefix), .operator(".", .prefix), .startOfScope("["), .number("0", .integer), .endOfScope("]"), .operator(".", .infix), .identifier("bar"), ] XCTAssertEqual(tokenize(input), output) } }
28.807771
96
0.443124
7a57f1552c133a99e6138ee3f7dff8403b23ec1c
393
// Copyright (c) 2021 Payoneer Germany GmbH // https://www.payoneer.com // // This file is open source and available under the MIT license. // See the LICENSE file for more information. import Foundation /// Simple request that just performs `POST` request on specified URL. protocol PostRequest: Request, BodyEncodable {} extension PostRequest { var httpMethod: HTTPMethod { .POST } }
26.2
70
0.745547
8ac9a4faff548ac4cf1abef3e6e5a2966c5bc54f
1,754
// // ViewController.swift // YTIntegration // // Created by Dharmatej Parvathaneni on 3/5/20. // Copyright © 2020 dharmatej. All rights reserved. // import UIKit import WebKit class VideoController: UIViewController { // IBs @IBOutlet var customView: UIView! @IBAction func showYoutube() { self.loadVideo(.Youtube) } @IBAction func showVimeo() { self.loadVideo(.Vimeo) } @IBAction func showVimeoBP() { self.loadVideo(.ViemoBackGround) } // Locals private var webView = WKWebView() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let webViewConfig = WKWebViewConfiguration() webViewConfig.allowsInlineMediaPlayback = true webView = WKWebView(frame: self.customView.bounds, configuration: webViewConfig) // Load Default Player Video self.loadVideo(.Youtube) } private func loadVideo(_ provider: VideoType) { var videoUrl: URL switch provider { case .Vimeo: videoUrl = URL(string: "https://player.vimeo.com/video/94078580?background=1")! case .Youtube: videoUrl = URL(string: "https://www.youtube.com/embed/fEMakZVwq-Y?playsinline=1&autoplay=1")! case .ViemoBackGround: videoUrl = URL(string: "https://player.vimeo.com/video/396010417?autoplay=1")! } webView.load(URLRequest(url: videoUrl)) self.customView.addSubview(webView) } } enum VideoType { case Youtube case Vimeo case ViemoBackGround }
25.057143
105
0.628278
723ef4c83969e9bf034b267e66fc90036daa8985
575
{% include "Includes/header.stencil" %} import Foundation {% if info.description %} /** {{ info.description }} */ {% endif %} public struct {{ options.name }} { /// change this if your api has a different date encoding format public static var dateEncodingFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" {% if info.version %} public static let version = "{{ info.version }}" {% endif %} {% if tags %} {% for tag in tags %} public enum {{ options.tagPrefix }}{{ tag|upperCamelCase }}{{ options.tagSuffix }} {} {% endfor %} {% endif %} }
25
89
0.606957
5655dcc19f7a9ec2598ff67af178f833b0bd335b
1,729
// // Copyright (c) 2021 Related Code - https://relatedcode.com // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit //----------------------------------------------------------------------------------------------------------------------------------------------- class BadgeView: UIViewController { @IBOutlet var labelDescription: UILabel! //------------------------------------------------------------------------------------------------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.isHidden = true navigationController?.navigationItem.largeTitleDisplayMode = .never navigationController?.navigationBar.prefersLargeTitles = false } // MARK: - User actions //------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionSave(_ sender: UIButton) { print(#function) dismiss(animated: true, completion: nil) } //------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionLearnMore(_ sender: UIButton) { print(#function) dismiss(animated: true, completion: nil) } }
40.209302
145
0.506073
912ae08c359fb30f8c98a9140d1b12bbd2c9ba21
898
//// //// RawRepresentableTests.swift //// HISwiftExtensions //// //// Created by Matthew on 31/12/2015. //// Copyright © 2015 CocoaPods. All rights reserved. //// import Quick import Nimble import HISwiftExtensions class RawRepresentativeExtensionsSpec: QuickSpec { override func spec() { describe("raw representable extension") { enum Test: Int { case success } it("init optionalRawValue") { let value: Int? = 1 let test = Test(optionalRawValue: value) expect(test).to(equal(Test.success)) } it("init optionalRawValue nil"){ let value: Int? = nil let test = Test(optionalRawValue: value) expect(test).to(beNil()) } } } }
24.27027
56
0.503341
5d54db4491eeed683bfbc3a7e08db62ce3b4e633
570
// // Temp.swift // ios-mvp // // Created by Ahsan Ali on 05/09/2020. // Copyright © 2020 Ahsan Ali. All rights reserved. // import Foundation import ObjectMapper struct Temp : Mappable { var day : Double? var min : Double? var max : Double? var night : Double? var eve : Double? var morn : Double? init?(map: Map) { } mutating func mapping(map: Map) { day <- map["day"] min <- map["min"] max <- map["max"] night <- map["night"] eve <- map["eve"] morn <- map["morn"] } }
16.285714
52
0.529825
f85e3863e7b7fa473b953642b915d65ddaca943d
3,606
/// Declares a type that can parse an `Input` value into an `Output` value. /// /// * [Getting started](#Getting-started) /// * [String abstraction levels](#String-abstraction-levels) /// * [Error messages](#Error-messages) /// * [Backtracking](#Backtracking) /// /// ## Getting started /// /// A parser attempts to parse a nebulous piece of data, represented by the `Input` associated type, /// into something more well-structured, represented by the `Output` associated type. The parser /// implements the ``parse(_:)-76tcw`` method, which is handed an `inout Input`, and its job is to /// turn this into an `Output` if possible, or throw an error if it cannot. /// /// The argument of the ``parse(_:)-76tcw`` function is `inout` because a parser will usually /// consume some of the input in order to produce an output. For example, we can use an /// `Int.parser()` parser to extract an integer from the beginning of a substring and consume that /// portion of the string: /// /// ```swift /// var input: Substring = "123 Hello world" /// /// try Int.parser().parse(&input) // 123 /// input // " Hello world" /// ``` /// /// Note that this parser works on `Substring` rather than `String` because substrings expose /// efficient ways of removing characters from its beginning. Substrings are "views" into a string, /// specificed by start and end indices. Operations like `removeFirst`, `removeLast` and others can /// be implemented efficiently on substrings because they simply move the start and end indices, /// whereas their implementation on strings must make a copy of the string with the characters /// removed. /// /// To explore the concepts of parsers more deeply read the following articles: /// /// * <doc:GettingStarted> /// * <doc:Design> /// * <doc:StringAbstractions> /// * <doc:ErrorMessages> /// * <doc:Backtracking> @rethrows public protocol Parser { /// The kind of values this parser receives. associatedtype Input /// The kind of values parsed by this parser. associatedtype Output /// Attempts to parse a nebulous piece of data into something more well-structured. /// /// - Parameter input: A nebulous, mutable piece of data to be incrementally parsed. /// - Returns: A more well-structured value parsed from the given input. func parse(_ input: inout Input) throws -> Output } extension Parser { /// Attempts to parse a nebulous piece of data into something more well-structured. /// /// - Parameter input: A nebulous piece of data to be parsed. /// - Returns: A more well-structured value parsed from the given input. @inlinable public func parse(_ input: Input) rethrows -> Output { var input = input return try self.parse(&input) } /// Attempts to parse a nebulous collection of data into something more well-structured. /// /// - Parameter input: A nebulous collection of data to be parsed. /// - Returns: A more well-structured value parsed from the given input. @inlinable public func parse<C: Collection>(_ input: C) rethrows -> Output where Input == C.SubSequence { try Parse { self End<Input>() }.parse(input[...]) } /// Attempts to parse a nebulous collection of data into something more well-structured. /// /// - Parameter input: A nebulous collection of data to be parsed. /// - Returns: A more well-structured value parsed from the given input. @_disfavoredOverload @inlinable public func parse<S: StringProtocol>(_ input: S) rethrows -> Output where Input == S.SubSequence.UTF8View { try Parse { self End<Input>() }.parse(input[...].utf8) } }
38.774194
100
0.697171
28f268ae8c667f87c770f1c10e0350157860dcfb
330
import Foundation import SwiftUI enum PagingScrollSensitivity: Hashable { case fixed(_: StaticScrollSensitivity), dynamic(_: DynamicScrollSensitivity) } enum StaticScrollSensitivity: Hashable { case distance(_: CGFloat) } enum DynamicScrollSensitivity: CGFloat { case standard = 0.5, high = 0.25, extreme = 0.1 }
25.384615
80
0.754545
50b8c3951f00a696a2abb4dbb1506a07c2e867f7
613
import Foundation import XCTest import FuntastyKit final class FuntastyKitTests: XCTestCase { func testArchitecture() { let model = Model() let viewController = UIViewController() UIApplication.shared.keyWindow?.rootViewController = viewController let coordinator = ExampleCoordinator(from: viewController, model: model) coordinator.start() } } #if os(Linux) extension FuntastyKitTests { static var allTests: [(String, (FuntastyKitTests) -> () throws -> Void)] { return [ ("testArchitecture", testArchitecture) ] } } #endif
22.703704
80
0.66721
4bb56bda8640f7c1594133c1c496b83ab847ccf8
665
// // TopScoreStandingModule.swift // Live3s // // Created by phuc on 3/6/16. // Copyright © 2016 com.phucnguyen. All rights reserved. // import Foundation import SwiftyJSON class TopScoreStandingModule { var team = "'" var name_player = "" var number_first_goals = "" var number_goals = "" var number_penalties = "" init(json: JSON) { team = json["team"].stringValue name_player = json["name_player"].stringValue number_first_goals = json["number_first_goals"].stringValue number_goals = json["number_goals"].stringValue number_penalties = json["number_penalties"].stringValue } }
24.62963
67
0.66015
1afab0554952ec96a70066e1dfb7efe15ddac314
576
import Foundation import Metrics public final class TestStartedMetric: Metric { public init( host: String, testClassName: String, testMethodName: String) { super.init( fixedComponents: ["test", "started"], variableComponents: [ host, testClassName, testMethodName, Metric.reservedField, Metric.reservedField, Metric.reservedField ], value: 1, timestamp: Date() ) } }
23.04
49
0.498264
e92c55697868754870c67972f9f38ab16494868c
5,751
// // VPNDataManager+VPN.swift // VPN On // // Created by Lex Tang on 12/5/14. // Copyright (c) 2017 lexrus.com. All rights reserved. // import CoreData import VPNOnKit extension VPNDataManager { func allVPN() -> [VPN] { var vpns = [VPN]() let request = NSFetchRequest<VPN>(entityName: "VPN") let sortByTitle = NSSortDescriptor(key: "title", ascending: true) let sortByServer = NSSortDescriptor(key: "server", ascending: true) let sortByType = NSSortDescriptor(key: "ikev2", ascending: false) request.sortDescriptors = [sortByTitle, sortByServer, sortByType] if let moc = managedObjectContext, let results = (try? moc.fetch(request)) { results.forEach { if !$0.isDeleted { vpns.append($0) } } } return vpns } func createVPN( _ title: String, server: String, account: String, password: String, group: String, secret: String, alwaysOn: Bool = true, ikev2: Bool = false, remoteID: String? = nil ) -> VPN? { guard let entity = NSEntityDescription.entity(forEntityName: "VPN", in: managedObjectContext!), let vpn = NSManagedObject(entity: entity, insertInto: managedObjectContext!) as? VPN else { return nil } vpn.title = title vpn.server = server vpn.account = account vpn.group = group vpn.alwaysOn = alwaysOn vpn.ikev2 = ikev2 vpn.remoteID = remoteID do { try managedObjectContext!.save() saveContext() if !vpn.objectID.isTemporaryID { KeychainWrapper.setPassword(password, forVPNID: vpn.ID) if !secret.isEmpty { KeychainWrapper.setSecret(secret, forVPNID: vpn.ID) } if allVPN().count == 1 { VPNManager.shared.activatedVPNID = vpn.ID } return vpn } } catch { print("Could not save VPN \(error.localizedDescription)") } return nil } func deleteVPN(_ vpn:VPN) { let ID = "\(vpn.ID)" KeychainWrapper.destoryKeyForVPNID(ID) managedObjectContext!.delete(vpn) do { try managedObjectContext!.save() } catch { } saveContext() if VPNManager.shared.activatedVPNID == ID { VPNManager.shared.activatedVPNID = nil let vpns = allVPN() if let firstVPN = vpns.first { VPNManager.shared.activatedVPNID = firstVPN.ID } } } func VPNByID(_ ID: NSManagedObjectID) -> VPN? { if ID.isTemporaryID { return .none } var result: NSManagedObject? = nil do { result = try managedObjectContext?.existingObject(with: ID) } catch { } if let vpn = result as? VPN, !vpn.isDeleted { managedObjectContext?.refresh(vpn, mergeChanges: true) return vpn } return nil } func VPNByIDString(_ ID: String) -> VPN? { guard let URL = URL(string: ID) else { return nil } if URL.scheme?.lowercased() == "x-coredata" { if let moid = persistentStoreCoordinator!.managedObjectID(forURIRepresentation: URL) { return VPNByID(moid) } } return nil } func VPNByPredicate(_ predicate: NSPredicate) -> [VPN] { var vpns = [VPN]() let request = NSFetchRequest<VPN>(entityName: "VPN") request.predicate = predicate guard let results = try? managedObjectContext!.fetch(request) else { return vpns } results.filter { !$0.isDeleted }.forEach { vpns.append($0) } return vpns } func VPNBeginsWithTitle(_ title: String) -> [VPN] { let titleBeginsWithPredicate = NSPredicate(format: "title beginswith[cd] %@", argumentArray: [title]) return VPNByPredicate(titleBeginsWithPredicate) } func VPNHasTitle(_ title: String) -> [VPN] { let titleBeginsWithPredicate = NSPredicate(format: "title == %@", argumentArray: [title]) return VPNByPredicate(titleBeginsWithPredicate) } func duplicate(_ vpn: VPN) -> VPN? { let duplicatedVPNs = VPNDataManager.shared.VPNBeginsWithTitle(vpn.title) if duplicatedVPNs.count > 0 { guard let title = vpn.title else { return nil } let newTitle = "\(title) \(duplicatedVPNs.count)" if let newVPN = createVPN( newTitle, server: vpn.server, account: vpn.account, password: KeychainWrapper.passwordStringForVPNID(vpn.ID) ?? "", group: vpn.group, secret: KeychainWrapper.secretStringForVPNID(vpn.ID) ?? "", alwaysOn: vpn.alwaysOn, ikev2: vpn.ikev2, remoteID: vpn.remoteID ) { if let password = KeychainWrapper.passwordStringForVPNID(vpn.ID) { KeychainWrapper.setPassword(password, forVPNID: newVPN.ID) } if let secret = KeychainWrapper.secretStringForVPNID(vpn.ID) { KeychainWrapper.setSecret(secret, forVPNID: newVPN.ID) } return newVPN } } return nil } }
31.598901
109
0.53469
e074cdaee9b6536bd4386aaf303ebca1eb4187b3
265
// Copyright © 2020 Christian Tietze. All rights reserved. Distributed under the MIT License. protocol FileExistenceChecker { func fileExistence(at url: URL) -> FileExistence } enum FileExistence: Equatable { case none case file case directory }
22.083333
94
0.735849
4819afafaa4caffb73717eee915600d7cd14407a
331
// // AchievementService.swift // ClassicClient-Example // // Created by Justin Lycklama on 2020-08-26. // Copyright © 2020 CocoaPods. All rights reserved. // import Foundation import ClassicClient class AchievementService: NSObject, FakeServerProtocol { typealias T = Achievement let dataFileName = "achievements" }
20.6875
56
0.746224
f916943eaa7a3a1569b8f1c095f4851bad897c18
968
// // TryCatchFinally.swift // ginlo // // Created by RBU on 27/01/16. // Copyright © 2020 ginlo.net GmbH. All rights reserved. // import Foundation public func tryC(_ try: @escaping () -> Void) -> TryCatchFinally { TryCatchFinally(`try`) } public class TryCatchFinally { let tryFunc: () -> Void var catchFunc: (NSException) -> Void = { _ in } var finallyFunc: () -> Void = {} init(_ try: @escaping () -> Void) { tryFunc = `try` } @discardableResult public func `catch`(_ catch: @escaping (NSException) -> Void) -> TryCatchFinally { // objc bridging needs NSException!, not NSException as we'd like to expose to clients. self.catchFunc = { e in `catch`(e) } return self } public func finally(_ finally: @escaping () -> Void) { self.finallyFunc = finally } deinit { tryCatchFinally(self.tryFunc, self.catchFunc, self.finallyFunc) } }
22.511628
95
0.59814
e97e0b57cdc75aec92ddb6f9ba2584801a12f3b2
11,582
// // StepIndicatorVerticalView.swift // StepperView // // Created by Venkatnarayansetty, Badarinath on 4/16/20. // import SwiftUI /// A Step Indications View in `vertical` direction /// /// creates step indicator view either in `vertical` mode @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) struct StepIndicatorVerticalView<Cell>: View where Cell:View { //vertical mode elements /// state variable to hold height of line to render `View` when values changes @State private var lineHeight:CGFloat = 0 /// state variable to hold x-axis position of line to render `View` when values changes @State private var lineXPosition:CGFloat = 0 /// state variable to hold each step heights to render `View` when values changes @State private var columnHeights: [Int: CGFloat] = [:] /// state variable to hold y-axis position to render `View` when values changes @State private var lineYPosition: CGFloat = 0 /// state variable for dyanmic spacing @State private var dynamicSpace:CGFloat = Utils.standardSpacing /// environment variable to access pitstop options @Environment(\.pitStopOptions) var pitStopsOptions /// environment variable to access pitstop options @Environment(\.pitStopLineOptions) var pitStopLineOptions /// environment variable to access autospacing @Environment(\.autoSpacing) var autoSpacing /// environment variable to access steplife cycles @Environment(\.stepLifeCycle) var stepLifeCycle /// list of `View's` to display step indictor content var cells:[Cell] /// list of alignments to display the step indicator position can be `top` or `center` or `bottom` var alignments:[StepperAlignment] /// step indicator type can be a `Circle` , `Image` or `Custom` var indicationType: [StepperIndicationType<AnyView>] /// options to customize `width ` , `Color` of the line var lineOptions:StepperLineOptions /// spacing between each of the step indicators var verticalSpacing: CGFloat /// to detect the whether the line option is of type `rounded` var isRounded:Bool = false /// initilazes cells, alignments , indicators and spacing init(cells: [Cell], alignments: [StepperAlignment] = [], indicationType: [StepperIndicationType<AnyView>], lineOptions: StepperLineOptions = .defaults, verticalSpacing:CGFloat = 30.0) { self.cells = cells self.alignments = alignments self.indicationType = indicationType self.verticalSpacing = verticalSpacing self.lineOptions = lineOptions switch lineOptions { case .rounded(_, _, _): self.isRounded = true default: self.isRounded = false } } /// Provides the content and behavior of this view. var body: some View { HStack { //line view to host indicator to point VerticalLineView(lineHeight: $lineHeight, lineXPosition: $lineXPosition, lineYPosition: $lineYPosition, options: self.lineOptions, alignments: (self.firstAlignment, self.lastAlignment)) VStack(alignment: .leading, spacing: autoSpacing ? self.dynamicSpace : self.verticalSpacing) { ForEach(0..<self.cells.count, id:\.self) { index in HStack(alignment: self.getAlignment(type: self.alignments[index])) { IndicatorView(type: self.indicationType[index], indexofIndicator: index) .padding(.horizontal, Utils.standardSpacing) //for drawing pit stops. .ifTrue(self.pitStopsOptions.count > 0, content: { view in view.anchorPreference(key: BoundsPreferenceKey.self, value: .bounds) { $0 } .overlayPreferenceValue(BoundsPreferenceKey.self, { (preferences) in GeometryReader { proxy in preferences.map { anchor in self.drawAnchors(proxy: proxy, value: anchor, pitStopIndex: index) } } }) }) .ifTrue(self.isRounded, content: { view in view.anchorPreference(key: BoundsPreferenceKey.self, value: .bounds) { $0 } .overlayPreferenceValue(BoundsPreferenceKey.self, { (preferences) in GeometryReader { proxy in preferences.map { value in self.drawCustomLine(proxy: proxy, value: value, index: index) } } }) }) .eraseToAnyView() self.cells[index] .heightPreference(column: index) }.setAlignment(type: self.alignments[index]) .offset(x: self.getOffset()) } }.verticalHeightPreference() // Intermediate height of the Line View .onPreferenceChange(HeightPreference.self) { self.lineYPosition = self.getYPosition(for: self.firstAlignment) self.calculateIntermediateHeights(value: $0) } // Width of the Indicator View .onPreferenceChange(WidthPreference.self) { self.lineXPosition = $0.values.first ?? 12 } // Height of the Line View .onPreferenceChange(VerticalHeightPreference.self) { //print("Height of Divider \($0)") let finalHeight = $0.values.max() ?? 0.0 self.lineHeight = finalHeight - self.calculateHeightsForFirstAndLastAlignments() //print("Final Line Height \(self.lineHeight)") } // auto spacing .onPreferenceChange(PitstopHeightPreference.self) { //print("Pistop height value \($0)") self.dynamicSpace = Array($0.values).max() ?? 0.0 //print("Auto Spacing:: \(self.dynamicSpace)") } }.padding() } } // MARK: - Helper methods to construct step indicator vertical view. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) extension StepIndicatorVerticalView { /// Calculate intermediate heights of the view. /// - Parameter value: dictionary to hold the index and height values. private func calculateIntermediateHeights( value: [Int:CGFloat] ) { self.columnHeights = value //print("Intermediate Divider Height \(self.columnHeights)") self.dynamicSpace = self.columnHeights.first?.value ?? 0.0 //print("Auto Spacing:: \(self.dynamicSpace)") } /// returns the first alignment from array else `.center` by default private var firstAlignment: StepperAlignment { return self.alignments.first ?? .center } /// returns the last alignment from array else `center` by default private var lastAlignment: StepperAlignment { return self.alignments.last ?? .center } /// Calculates the height based on first and last alignments. private func calculateHeightsForFirstAndLastAlignments() -> CGFloat { if self.alignments.count > 1 { switch (firstAlignment, lastAlignment) { //Reduce 3 times to get actual height case (.center, .top): return 3 * self.getYPosition(for: .center) //Reduce 2 times to get actual height case (.center, .center): return 2 * self.getYPosition(for: .center) //Reduce 1 time to get actual height case (.center, .bottom): return self.getYPosition(for: .center) //Reduce 1 time to get actual height case (.top, .center): return self.getYPosition(for: .center) case (.top, .bottom): return self.getYPosition(for: firstAlignment) //Reduce 2 times to get actual height case (.top, .top): return 2 * self.getYPosition(for: .center) //Reduce 2 times as it's messured from it's first alignment (.bottom isn this case) case(.bottom, .top): return 2 * self.getYPosition(for: firstAlignment) //Reduce 3 times to get actual height case (.bottom, .center): return 3 * self.getYPosition(for: .center) case (.bottom, .bottom): return self.getYPosition(for: firstAlignment) } } else { return self.getYPosition(for: self.firstAlignment) } } /// draws pitstops for each of the step indicators. /// - Parameters: /// - proxy: co-ordinates values of step indicator /// - value: bound values of step indicator /// - pitStopIndex: Index position of step indicator private func drawAnchors(proxy: GeometryProxy, value: Anchor<CGRect>, pitStopIndex: Int) -> some View { guard self.pitStopsOptions.indices.contains(pitStopIndex) else { return EmptyView().eraseToAnyView() } guard self.pitStopLineOptions.count > 0 else { return PitStopView(proxy: proxy, value: value, lineXPosition: $lineXPosition, pitStop: self.pitStopsOptions[pitStopIndex], heightIndex: pitStopIndex) .eraseToAnyView() } return PitStopView(proxy: proxy, value: value, lineXPosition: $lineXPosition, pitStop: self.pitStopsOptions[pitStopIndex], lineOptions: self.pitStopLineOptions[pitStopIndex], heightIndex: pitStopIndex) .eraseToAnyView() } /// draaws custom line between the indicators /// - Parameters: /// - proxy: co-ordinates values of step indicator /// - value: bound values of step indicator /// - index: index position of step indicator /// - Returns: reurns a `view` of type of Line private func drawCustomLine(proxy: GeometryProxy, value: Anchor<CGRect>, index: Int) -> some View { guard index != self.cells.count - 1 else { return EmptyView().eraseToAnyView() } switch lineOptions { case .rounded(let width, let cornerRadius, let color): // draw a line return RoundedRectangle(cornerRadius: cornerRadius) .foregroundColor(stepLifeCycle[index] == StepLifeCycle.completed ? color : Color.gray.opacity(0.5)) .frame(width: width, height: self.verticalSpacing) .offset(x: proxy[value].midX - width/2, y: proxy[value].maxY) .eraseToAnyView() default: return EmptyView().eraseToAnyView() } } /// returns offset value to align the the line view private func getOffset() -> CGFloat { #if os(watchOS) return -Utils.watchoffsetConstant #else return -Utils.offsetConstant #endif } }
47.662551
123
0.577707
8fcfb3a654ebffabcf68fb60c2b559c7ab3e8d7e
12,977
// // PhotoAsset+Request.swift // HXPHPicker // // Created by Slience on 2021/3/11. // import UIKit import Photos // MARK: Request Photo public extension PhotoAsset { struct ImageDataResult { let imageData: Data let imageOrientation: UIImage.Orientation let info: [AnyHashable : Any]? } /// 获取原始图片地址 /// 网络图片获取方法 getNetworkImageURL /// - Parameters: /// - fileURL: 指定图片的本地地址 /// - resultHandler: 获取结果 func requestImageURL(toFile fileURL:URL? = nil, resultHandler: @escaping AssetURLCompletion) { if phAsset == nil { requestLocalImageURL(toFile: fileURL, resultHandler: resultHandler) return } requestAssetImageURL(toFile: fileURL, resultHandler: resultHandler) } /// 获取图片(系统相册获取的是压缩后的,不是原图) @discardableResult func requestImage(completion: ((UIImage?, PhotoAsset) -> Void)?) -> PHImageRequestID? { #if HXPICKER_ENABLE_EDITOR if let photoEdit = photoEdit { completion?(UIImage(contentsOfFile: photoEdit.editedImageURL.path), self) return nil } if let videoEdit = videoEdit { completion?(videoEdit.coverImage, self) return nil } #endif if phAsset == nil { requestLocalImage(urlType: .original) { (image, photoAsset) in completion?(image, photoAsset) } return nil } let options = PHImageRequestOptions.init() options.resizeMode = .fast options.deliveryMode = .highQualityFormat options.isNetworkAccessAllowed = true return AssetManager.requestImageData(for: phAsset!, version: isGifAsset ? .original : .current, iCloudHandler: nil, progressHandler: nil) { (result) in switch result { case .success(let dataResult): var image = UIImage.init(data: dataResult.imageData) if image?.imageOrientation != UIImage.Orientation.up { image = image?.normalizedImage() } image = image?.scaleImage(toScale: 0.5) completion?(image, self) case .failure(_): completion?(nil, self) } } } /// 请求获取缩略图 /// - Parameter completion: 完成回调 /// - Returns: 请求ID @discardableResult func requestThumbnailImage(targetWidth: CGFloat = 180, completion: ((UIImage?, PhotoAsset, [AnyHashable : Any]?) -> Void)?) -> PHImageRequestID? { #if HXPICKER_ENABLE_EDITOR if let photoEdit = photoEdit { completion?(photoEdit.editedImage, self, nil) return nil } if let videoEdit = videoEdit { completion?(videoEdit.coverImage, self, nil) return nil } #endif if phAsset == nil { requestLocalImage(urlType: .thumbnail) { (image, photoAsset) in completion?(image, photoAsset, nil) } return nil } return AssetManager.requestThumbnailImage(for: phAsset!, targetWidth: targetWidth) { (image, info) in completion?(image, self, info) } } /// 请求imageData,如果资源在iCloud上会自动下载。如果需要更细节的处理请查看 PHAssetManager+Asset /// - Parameters: /// - filterEditor: 过滤编辑后的图片 /// - iCloudHandler: 下载iCloud上的资源时回调iCloud的请求ID /// - progressHandler: iCloud下载进度 /// - Returns: 请求ID @discardableResult func requestImageData(filterEditor: Bool = false, iCloudHandler: PhotoAssetICloudHandler?, progressHandler: PhotoAssetProgressHandler?, resultHandler: ((PhotoAsset, Result<ImageDataResult, AssetManager.ImageDataError>) -> Void)?) -> PHImageRequestID { #if HXPICKER_ENABLE_EDITOR if let photoEdit = photoEdit, !filterEditor { do { let imageData = try Data.init(contentsOf: photoEdit.editedImageURL) resultHandler?(self, .success(.init(imageData: imageData, imageOrientation: photoEdit.editedImage.imageOrientation, info: nil))) }catch { resultHandler?(self, .failure(.init(info: nil, error: .invalidData))) } return 0 } if let videoEdit = videoEdit, !filterEditor { let imageData = PhotoTools.getImageData(for: videoEdit.coverImage) if let imageData = imageData { resultHandler?(self, .success(.init(imageData: imageData, imageOrientation: videoEdit.coverImage!.imageOrientation, info: nil))) }else { resultHandler?(self, .failure(.init(info: nil, error: .invalidData))) } return 0 } #endif if phAsset == nil { requestlocalImageData { photoAsset, result in switch result { case .success(let imageResult): resultHandler?(photoAsset, .success(.init(imageData: imageResult.imageData, imageOrientation: imageResult.imageOrientation, info: nil))) case .failure(let error): resultHandler?(photoAsset, .failure(error)) } } return 0 } var version = PHImageRequestOptionsVersion.current if mediaSubType == .imageAnimated { version = .original } downloadStatus = .downloading return AssetManager.requestImageData(for: phAsset!, version: version) { iCloudRequestID in iCloudHandler?(self, iCloudRequestID) } progressHandler: { progress, error, stop, info in self.downloadProgress = progress DispatchQueue.main.async { progressHandler?(self, progress) } } resultHandler: { result in switch result { case .success(let dataResult): self.downloadProgress = 1 self.downloadStatus = .succeed resultHandler?(self, .success(.init(imageData: dataResult.imageData, imageOrientation: dataResult.imageOrientation, info: dataResult.info))) case .failure(let error): if AssetManager.assetCancelDownload(for: error.info) { self.downloadStatus = .canceled }else { self.downloadProgress = 0 self.downloadStatus = .failed } resultHandler?(self, .failure(error)) } } } } // MARK: Request LivePhoto public extension PhotoAsset { /// 请求LivePhoto,如果资源在iCloud上会自动下载。如果需要更细节的处理请查看 PHAssetManager+Asset /// - Parameters: /// - targetSize: 请求的大小 /// - iCloudHandler: 下载iCloud上的资源时回调iCloud的请求ID /// - progressHandler: iCloud下载进度 /// - Returns: 请求ID @available(iOS 9.1, *) @discardableResult func requestLivePhoto(targetSize: CGSize, iCloudHandler: PhotoAssetICloudHandler?, progressHandler: PhotoAssetProgressHandler?, success: ((PhotoAsset, PHLivePhoto, [AnyHashable : Any]?) -> Void)?, failure: PhotoAssetFailureHandler?) -> PHImageRequestID { if phAsset == nil { failure?(self, nil, .invalidPHAsset) return 0 } downloadStatus = .downloading return AssetManager.requestLivePhoto(for: phAsset!, targetSize: targetSize) { (iCloudRequestID) in iCloudHandler?(self, iCloudRequestID) } progressHandler: { (progress, error, stop, info) in self.downloadProgress = progress DispatchQueue.main.async { progressHandler?(self, progress) } } resultHandler: { (livePhoto, info, downloadSuccess) in if downloadSuccess { self.downloadProgress = 1 self.downloadStatus = .succeed success?(self, livePhoto!, info) }else { if AssetManager.assetCancelDownload(for: info) { self.downloadStatus = .canceled }else { self.downloadProgress = 0 self.downloadStatus = .failed } failure?(self, info, .requestFailed(info)) } } } func requestLivePhotoURL(completion: @escaping (Result<AssetURLResult, AssetError>) -> Void) { #if HXPICKER_ENABLE_EDITOR if let photoEdit = photoEdit { completion(.success(.init(url: photoEdit.editedImageURL, urlType: .local, mediaType: .photo, livePhoto: nil))) return } #endif guard let phAsset = phAsset else { completion(.failure(.invalidPHAsset)) return } var imageURL: URL? var videoURL: URL? AssetManager.requestLivePhoto(contentURL: phAsset) { url in imageURL = url } videoHandler: { url in videoURL = url } completionHandler: { error in if let error = error { switch error { case .allError(let imageError, let videoError): completion(.failure(.exportLivePhotoURLFailed(imageError, videoError))) case .imageError(let error): completion(.failure(.exportLivePhotoImageURLFailed(error))) case .videoError(let error): completion(.failure(.exportLivePhotoVideoURLFailed(error))) } }else { completion(.success(.init(url: imageURL!, urlType: .local, mediaType: .photo, livePhoto: .init(imageURL: imageURL!, videoURL: videoURL!)))) } } } } // MARK: Request Video public extension PhotoAsset { /// 获取原始视频地址,系统相册里的视频需要自行压缩 /// 网络视频如果在本地有缓存则会返回本地地址,如果没有缓存则为ni /// - Parameters: /// - fileURL: 指定视频地址 /// - exportPreset: 导出质量,不传则获取的是原始视频地址 /// - resultHandler: 获取结果 func requestVideoURL(toFile fileURL:URL? = nil, exportPreset: String? = nil, resultHandler: @escaping AssetURLCompletion) { if phAsset == nil { requestLocalVideoURL(toFile: fileURL, resultHandler: resultHandler) return } requestAssetVideoURL(toFile: fileURL, exportPreset: exportPreset, resultHandler: resultHandler) } /// 请求AVAsset,如果资源在iCloud上会自动下载。如果需要更细节的处理请查看 PHAssetManager+Asset /// - Parameters: /// - filterEditor: 过滤编辑过的视频,取原视频 /// - iCloudHandler: 下载iCloud上的资源时回调iCloud的请求ID /// - progressHandler: iCloud下载进度 /// - Returns: 请求ID @discardableResult func requestAVAsset(filterEditor: Bool = false, deliveryMode: PHVideoRequestOptionsDeliveryMode = .automatic, iCloudHandler: PhotoAssetICloudHandler?, progressHandler: PhotoAssetProgressHandler?, success: ((PhotoAsset, AVAsset, [AnyHashable : Any]?) -> Void)?, failure: PhotoAssetFailureHandler?) -> PHImageRequestID { #if HXPICKER_ENABLE_EDITOR if let videoEdit = videoEdit, !filterEditor { success?(self, AVAsset.init(url: videoEdit.editedURL), nil) return 0 } #endif if phAsset == nil { if let localVideoURL = localVideoAsset?.videoURL { success?(self, AVAsset.init(url: localVideoURL), nil) }else if let networkVideoURL = networkVideoAsset?.videoURL { success?(self, AVAsset.init(url: networkVideoURL), nil) }else { failure?(self, nil, .invalidPHAsset) } return 0 } downloadStatus = .downloading return AssetManager.requestAVAsset(for: phAsset!, deliveryMode: deliveryMode) { (iCloudRequestID) in iCloudHandler?(self, iCloudRequestID) } progressHandler: { (progress, error, stop, info) in self.downloadProgress = progress DispatchQueue.main.async { progressHandler?(self, progress) } } resultHandler: { (result) in switch result { case .success(let avResult): self.downloadProgress = 1 self.downloadStatus = .succeed success?(self, avResult.avAsset, avResult.info) case .failure(let error): if AssetManager.assetCancelDownload(for: error.info) { self.downloadStatus = .canceled }else { self.downloadProgress = 0 self.downloadStatus = .failed } failure?(self, error.info, error.error) } } } }
39.685015
159
0.571858
e6fb119607667b06c4dae4109deb4fb95aa1632e
12,008
// // ABITpees.swift // web3swift // // Created by Alexander Vlasov on 06.12.2017. // Copyright © 2017 Bankex Foundation. All rights reserved. // import Foundation // JSON Decoding public struct ABIInput: Decodable { var name: String? var type: String var indexed: Bool? } public struct ABIOutput: Decodable { var name: String? var type: String } public struct ABIRecord: Decodable { var name: String? var type: String? var payable: Bool? var constant: Bool? var stateMutability: String? var inputs: [ABIInput]? var outputs: [ABIOutput]? var anonymous: Bool? } public struct EventLogJSON { } // Native parsing protocol AbiValidating { var isValid: Bool { get } } protocol ABIElementPropertiesProtocol { var isArray: Bool {get} var arraySize: ABIElement.ArraySize {get} var subtype: ABIElement.ParameterType? {get} var memoryUsage: UInt64 {get} } public enum ABIElement { enum ArraySize { //bytes for convenience case staticSize(UInt64) case dynamicSize case notArray } case function(Function) case constructor(Constructor) case fallback(Fallback) case event(Event) public struct Function { let name: String? let inputs: [Input] let outputs: [Output] let constant: Bool let payable: Bool struct Output { let name: String let type: ParameterType } struct Input { let name: String let type: ParameterType } } public struct Constructor { let inputs: [Function.Input] let constant: Bool let payable: Bool } public struct Fallback { let constant: Bool let payable: Bool } public struct Event { let name: String let inputs: [Input] let anonymous: Bool struct Input { let name: String let type: ParameterType let indexed: Bool } } /// Specifies the type that parameters in a contract have. public enum ParameterType { case dynamicABIType(DynamicType) case staticABIType(StaticType) /// Denotes any type that has a fixed length. public enum StaticType:ABIElementPropertiesProtocol { var isArray: Bool { switch self { case .array(_, length: _): return true default: return false } } var arraySize: ABIElement.ArraySize { switch self { case .array(_, length: let length): return ABIElement.ArraySize.staticSize(length) default: return ABIElement.ArraySize.notArray } } var subtype: ABIElement.ParameterType? { switch self { case .array(let type, length: _): return ParameterType.staticABIType(type) default: return nil } } var memoryUsage: UInt64 { switch self { case .array(_, length: let length): return 32*length default: return 32 } } /// uint<M>: unsigned integer type of M bits, 0 < M <= 256, M % 8 == 0. e.g. uint32, uint8, uint256. case uint(bits: UInt64) /// int<M>: two's complement signed integer type of M bits, 0 < M <= 256, M % 8 == 0. case int(bits: UInt64) /// address: equivalent to uint160, except for the assumed interpretation and language typing. case address /// bool: equivalent to uint8 restricted to the values 0 and 1 case bool /// bytes<M>: binary type of M bytes, 0 < M <= 32. case bytes(length: UInt64) /// function: equivalent to bytes24: an address, followed by a function selector // case function /// <type>[M]: a fixed-length array of the given fixed-length type. indirect case array(StaticType, length: UInt64) // The specification also defines the following types: // uint, int: synonyms for uint256, int256 respectively (not to be used for computing the function selector). // We do not include these in this enum, as we will just be mapping those // to .uint(bits: 256) and .int(bits: 256) directly. } /// Denotes any type that has a variable length. public enum DynamicType { var isArray: Bool { switch self { case .dynamicArray(_): return true case .arrayOfDynamicTypes(length: _): return true default: return false } } var arraySize: ABIElement.ArraySize { switch self { case .dynamicArray(_): return ABIElement.ArraySize.dynamicSize case .arrayOfDynamicTypes(_, length: let length): return ABIElement.ArraySize.staticSize(length) default: return ABIElement.ArraySize.notArray } } var subtype: ABIElement.ParameterType? { switch self { case .dynamicArray(let type): return ParameterType.staticABIType(type) case .arrayOfDynamicTypes(let type, length: _): return ParameterType.dynamicABIType(type) default: return nil } } var memoryUsage: UInt64 { switch self { // case .dynamicArray(_): // return 32 // case .arrayOfDynamicTypes(_, length: _): // return 32 default: return 32 } } /// bytes: dynamic sized byte sequence. case bytes /// string: dynamic sized unicode string assumed to be UTF-8 encoded. case string /// <type>[]: a variable-length array of the given fixed-length type. case dynamicArray(StaticType) /// fixed length array of dynamic types is considered as dynamic type. indirect case arrayOfDynamicTypes(DynamicType, length: UInt64) } } } // MARK: - DynamicType Equatable extension ABIElement.ParameterType.DynamicType: Equatable { public static func ==(lhs: ABIElement.ParameterType.DynamicType, rhs: ABIElement.ParameterType.DynamicType) -> Bool { switch (lhs, rhs) { case (.bytes, .bytes): return true case (.string, .string): return true case (.dynamicArray(let value1), .dynamicArray(let value2)): return value1 == value2 case (.arrayOfDynamicTypes(let type1, let len1), .arrayOfDynamicTypes(let type2, let len2)): return type1 == type2 && len1 == len2 default: return false } } } // MARK: - ParameterType Equatable extension ABIElement.ParameterType: Equatable { public static func ==(lhs: ABIElement.ParameterType, rhs: ABIElement.ParameterType) -> Bool { switch (lhs, rhs) { case (.dynamicABIType(let value1), .dynamicABIType(let value2)): return value1 == value2 case (.staticABIType(let value1), .staticABIType(let value2)): return value1 == value2 default: return false } } } // MARK: - StaticType Equatable extension ABIElement.ParameterType.StaticType: Equatable { public static func ==(lhs: ABIElement.ParameterType.StaticType, rhs: ABIElement.ParameterType.StaticType) -> Bool { switch (lhs, rhs) { case let (.uint(length1), .uint(length2)): return length1 == length2 case let (.int(length1), .int(length2)): return length1 == length2 case (.address, .address): return true case (.bool, .bool): return true case let (.bytes(length1), .bytes(length2)): return length1 == length2 // case (.function, .function): // return true case let (.array(type1, length1), .array(type2, length2)): return type1 == type2 && length1 == length2 default: return false } } } // MARK: - ParameterType Validity extension ABIElement.ParameterType: AbiValidating { public var isValid: Bool { switch self { case .staticABIType(let type): return type.isValid case .dynamicABIType(let type): return type.isValid } } } // MARK: - ParameterType.StaticType Validity extension ABIElement.ParameterType.StaticType: AbiValidating { public var isValid: Bool { switch self { case .uint(let bits), .int(let bits): return bits > 0 && bits <= 256 && bits % 8 == 0 case .bytes(let length): return length > 0 && length <= 32 case let .array(type, _): return type.isValid default: return true } } } // MARK: - ParameterType.DynamicType Validity extension ABIElement.ParameterType.DynamicType: AbiValidating { public var isValid: Bool { // Right now we cannot create invalid dynamic types. return true } } // MARK: - Method ID for Contract extension ABIElement.Function { public var signature: String { return "\(name ?? "")(\(inputs.map { $0.type.abiRepresentation }.joined(separator: ",")))" } public var methodString: String { return String(signature.sha3(.keccak256).prefix(8)) } public var methodEncoding: Data { return signature.data(using: .ascii)!.sha3(.keccak256)[0...3] } } // MARK: - Event topic extension ABIElement.Event { public var signature: String { return "\(name)(\(inputs.map { $0.type.abiRepresentation }.joined(separator: ",")))" } public var topic: Data { return signature.data(using: .ascii)!.sha3(.keccak256) } } protocol AbiEncoding { var abiRepresentation: String { get } } extension ABIElement.ParameterType: AbiEncoding { public var abiRepresentation: String { switch self { case .staticABIType(let type): return type.abiRepresentation case .dynamicABIType(let type): return type.abiRepresentation } } } extension ABIElement.ParameterType.StaticType: AbiEncoding { public var abiRepresentation: String { switch self { case .uint(let bits): return "uint\(bits)" case .int(let bits): return "int\(bits)" case .address: return "address" case .bool: return "bool" case .bytes(let length): return "bytes\(length)" // case .function: // return "function" case let .array(type, length): return "\(type.abiRepresentation)[\(length)]" } } } extension ABIElement.ParameterType.DynamicType: AbiEncoding { public var abiRepresentation: String { switch self { case .bytes: return "bytes" case .string: return "string" case .dynamicArray(let type): return "\(type.abiRepresentation)[]" case .arrayOfDynamicTypes(let type, let length): return "\(type.abiRepresentation)[\(length)]" } } }
30.170854
121
0.55005
bff47cddaad91e4e67ae0686749bd47b1ffa05a4
4,281
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file shows an example of implementing the OperationCondition protocol. */ #if os(iOS) import UIKit /** A condition for verifying that we can present alerts to the user via `UILocalNotification` and/or remote notifications. */ struct UserNotificationCondition: OperationCondition { enum Behavior { /// Merge the new `UIUserNotificationSettings` with the `currentUserNotificationSettings`. case Merge /// Replace the `currentUserNotificationSettings` with the new `UIUserNotificationSettings`. case Replace } static let name = "UserNotification" static let currentSettings = "CurrentUserNotificationSettings" static let desiredSettings = "DesiredUserNotificationSettigns" static let isMutuallyExclusive = false let settings: UIUserNotificationSettings let application: UIApplication let behavior: Behavior /** The designated initializer. - parameter settings: The `UIUserNotificationSettings` you wish to be registered. - parameter application: The `UIApplication` on which the `settings` should be registered. - parameter behavior: The way in which the `settings` should be applied to the `application`. By default, this value is `.Merge`, which means that the `settings` will be combined with the existing settings on the `application`. You may also specify `.Replace`, which means the `settings` will overwrite the exisiting settings. */ init(settings: UIUserNotificationSettings, application: UIApplication, behavior: Behavior = .Merge) { self.settings = settings self.application = application self.behavior = behavior } func dependencyForOperation(_ operation: OperationCustom) -> Operation? { return UserNotificationPermissionOperation(settings: settings, application: application, behavior: behavior) } func evaluateForOperation(_ operation: OperationCustom, completion: (OperationConditionResult) -> Void) { let result: OperationConditionResult let current = application.currentUserNotificationSettings switch (current, settings) { case (let current?, let settings) where current.contains(settings: settings): result = .Satisfied default: let error = OperationErrorCode.conditionFailed(userInfo: [ OperationConditionKey:type(of: self).name, type(of: self).currentSettings: "current ?? NSNull()", type(of: self).desiredSettings: "settings deng " ]) result = .Failed(error) } completion(result) } } /** A private `OperationCustom` subclass to register a `UIUserNotificationSettings` object with a `UIApplication`, prompting the user for permission if necessary. */ private class UserNotificationPermissionOperation: OperationCustom { let settings: UIUserNotificationSettings let application: UIApplication let behavior: UserNotificationCondition.Behavior init(settings: UIUserNotificationSettings, application: UIApplication, behavior: UserNotificationCondition.Behavior) { self.settings = settings self.application = application self.behavior = behavior super.init() addCondition(AlertPresentation()) } override func execute() { DispatchQueue.main.async { let current = self.application.currentUserNotificationSettings let settingsToRegister: UIUserNotificationSettings switch (current, self.behavior) { case (let currentSettings?, .Merge): settingsToRegister = currentSettings.settingsByMerging(self.settings) default: settingsToRegister = self.settings } self.application.registerUserNotificationSettings(settingsToRegister) } } } #endif
34.804878
122
0.660126
e534d8279df108991c1be8b29e1e7e7ea2ba1af8
1,415
/* * Copyright 2016-2018 JD Fergason * * 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. */ /** Abstraction for TOML key paths */ public struct Path: Hashable, Equatable { internal(set) public var components: [String] init(_ components: [String]) { self.components = components } func begins(with: [String]) -> Bool { if with.count > components.count { return false } for x in with.indices { if components[x] != with[x] { return false } } return true } public var hashValue: Int { return components.reduce(0, { $0 ^ $1.hashValue }) } public static func == (lhs: Path, rhs: Path) -> Bool { return lhs.components == rhs.components } static func + (lhs: Path, rhs: Path) -> Path { return Path(lhs.components + rhs.components) } }
26.698113
75
0.625442
1eb6b8f6f1f4b5c2253db71d58cd8611b267d69a
1,721
// // Copyright © 2019 Stefan Brighiu. All rights reserved. // import Foundation import UIKit extension UIBarButtonItem: IsNavigationBarItem { internal var button: UIButton? { return self.customView as? UIButton } internal static func buildSystemItem(with type: UIBarButtonItemType, target: Any, action: Selector, isLeft: Bool, and style: NavigationBarStyle) -> UIBarButtonItem { let newItem: UIBarButtonItem! if let systemItem = type.systemItem { newItem = UIBarButtonItem(barButtonSystemItem: systemItem, target: target, action: action) newItem.tintColor = style.buttonTitleColor if let style = type.systemStyle { newItem.style = style } } else if let _ = type.title { let button = UIButton.build(with: type, target: target, action: action, isLeft: isLeft, and: style) newItem = UIBarButtonItem(customView: button) newItem.tintColor = style.buttonTitleColor } else { newItem = UIBarButtonItem(image: type.image, style: .plain, target: target, action: action) newItem.tintColor = style.imageTint } newItem.saveItemType(type) return newItem } public var barItemType: UIBarButtonItemType? { return navBarItemTypes[uniqueIdentifier] as? UIBarButtonItemType } }
37.413043
103
0.531668
e59dff5cc1f585d6a845a1a19193ad3563f8ad5a
598
// // URLShorthandValidator.swift // FormValidator // // Created by Éberson Oliveira on 01/12/2017. // Copyright © 2017 S2IT Mobile. All rights reserved. // import Foundation /** * The `URLShorthandValidator` contains an `URLShorthandCondition`. A valid string is a URL, with or without scheme. * - seealso: `URLShorthandCondition` */ public struct URLShorthandValidator: Validator { // MARK: - Properties public var conditions: [Condition] // MARK: - Initializers public init() { conditions = [URLShorthandCondition()] } }
19.933333
117
0.652174
d9f0d87a278fa33ce6f93f8764568c349b7fe758
587
// // AnasayfaRouter.swift // LezzetDuragi // // Created by Riza Erdi Karakus on 9.01.2022. // import Foundation class AnasayfaRouter:PresenterToRouterAnasayfaProtocol{ static func createModule(ref: AnasayfaViewController) { let presenter = AnasayfaPresenter() ref.anasayfaPresenterNesnesi = presenter ref.anasayfaPresenterNesnesi?.anasayfaInteractor = AnasayfaInteractor() ref.anasayfaPresenterNesnesi?.anasayfaView = ref ref.anasayfaPresenterNesnesi?.anasayfaInteractor?.anasayfaPresenter = presenter } }
26.681818
87
0.715503
acff020ae95e387bfc95cf91f83e897c44441d36
5,757
// // UsageSpec.swift // // // Created by Thomas Bonk on 27.04.21. // Copyright 2021 Thomas Bonk <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import Quick @testable import SwiftyLua class UsageSpec: QuickSpec { override func spec() { describe("Instantiating a Lua virtual machine") { /** The class `LuaVM` is represents a Lua virtual machine. Its constructor accepts a boolean value that determines whether the standard Lua libraries shall be loaded or not. The default value is `true` for loading the standard libraries. */ it("Instantiate a Lua VM without loading the Lua standard library") { let _ = LuaVM(openLibs: false) } it("Instantiate a Lua VM with loading the Lua standard library") { // The parameter `openLibs` defaults to true, so you don't need to pass it to the constructor. let _ = LuaVM() } } describe("Executing Lua code") { it("Execute code from a string") { let lua = LuaVM() let result = try lua.execute(string: """ function fib(m) if m < 2 then return m end return fib(m-1) + fib(m-2) end return fib(15); """) if case VirtualMachine.EvalResults.values(let returnValue) = result { NSLog("Result of fib(15) = \((returnValue[0] as! Number).toInteger())") } } it("Execute code from a file") { let lua = LuaVM() let result = try lua.execute( url: Bundle.module.url(forResource: "fib", withExtension: "lua", subdirectory: "LuaScripts")!) if case VirtualMachine.EvalResults.values(let returnValue) = result { NSLog("Result of fib(15) = \((returnValue[0] as! Number).toInteger())") } } } describe("Setting a global variables and structs") { it("Register a global variable") { let lua = LuaVM() lua.globals["global_var"] = 1337 let result = try lua.execute(string: "return global_var;") if case VirtualMachine.EvalResults.values(let returnValue) = result { NSLog("globale_var = \((returnValue[0] as! Number).toInteger())") } } it("Register a global struct") { let lua = LuaVM() let point = lua.vm.createTable() point["x"] = 0.5 point["y"] = 1.5 lua.globals["point"] = point let result = try lua.execute(string: "return point.x, point.y;") if case VirtualMachine.EvalResults.values(let returnValue) = result { NSLog("(x, y) = (\((returnValue[0] as! Number).toDouble()), \((returnValue[1] as! Number).toDouble())) ") } } } describe("Registering a native Swift function") { it("Register a native Swift function and call it") { let lua = LuaVM() lua.registerFunction( FunctionDescriptor( name: "fib", parameters: [Int.arg], fn: { (args: Arguments) -> SwiftReturnValue in let n = args.number.toInteger() var fib = 1 var prevFib = 1 for _ in 2..<n { let temp = fib; fib = fib + prevFib prevFib = temp } return .values([fib]) })) let result = try lua.execute(string: "return fib(15);") if case VirtualMachine.EvalResults.values(let returnValue) = result { NSLog("Result of fib(15) = \((returnValue[0] as! Number).toInteger())") } } } describe("Registering a native Swift type (class or struct)") { class Car: CustomTypeImplementation { public var name: String = "" // MARK: - Descriptor static func descriptor(_ vm: LuaVM) -> CustomTypeDescriptor { return CustomTypeDescriptor( constructor: ConstructorDescriptor { (args: Arguments) -> SwiftReturnValue in return .value(vm.toReference(Car())) }, functions: [], methods: [ MethodDescriptor("getName") { (instance: CustomTypeImplementation, args: Arguments) -> SwiftReturnValue in let car = instance as! Car return .value(car.name) }, MethodDescriptor("setName", parameters: [String.arg]) { (instance: CustomTypeImplementation, args: Arguments) -> SwiftReturnValue in let car = instance as! Car car.name = args.string return .nothing } ] ) } } it("Register a native Swift type and instantiate it") { let lua = LuaVM() lua.registerCustomType(type: Car.self) let result = try lua .execute(string: """ myCar = Car.new(); myCar:setName('Volvo'); return myCar; """) if case VirtualMachine.EvalResults.values(let returnValue) = result { let car: Car = (returnValue[0] as! Userdata).toCustomType() NSLog("myCar.name = \(car.name)") } } } } }
29.372449
146
0.569046
9bcd29a92db4b2ea9a40b3c50b08b2a3f1ae1eec
4,845
/* * Copyright (c) 2016-2021 Erik Doernenburg and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use these files 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 ScreenSaver class ConfigureSheetController : NSObject { struct Preset { var gridSize: CGFloat var speedFactor: CGFloat var startInterval: Double } static var presets = [ Preset(gridSize: 125, speedFactor: 1/4, startInterval: 3), Preset(gridSize: 125, speedFactor: 1, startInterval: 1), Preset(gridSize: 150, speedFactor: 1/13, startInterval: 9), Preset(gridSize: 100, speedFactor: 1/13, startInterval: 1) ] static var sharedInstance = ConfigureSheetController() @IBOutlet var window: NSWindow! @IBOutlet var versionField: NSTextField! @IBOutlet var presetSelector: NSPopUpButton! @IBOutlet var scaleSlider: NSSlider! @IBOutlet var speedSlider: NSSlider! @IBOutlet var delaySlider: NSSlider! var configuration: Configuration var ignoreSliderChanges: Bool override init() { configuration = Configuration.sharedInstance ignoreSliderChanges = false super.init() let myBundle = Bundle(for: ConfigureSheetController.self) myBundle.loadNibNamed("ConfigureSheet", owner: self, topLevelObjects: nil) let bundleVersion = (myBundle.infoDictionary!["CFBundleShortVersionString"] ?? "n/a") as! String let sourceVersion = (myBundle.infoDictionary!["Source Version"] ?? "n/a") as! String versionField.stringValue = String(format: "Version %@ (%@)", bundleVersion, sourceVersion) } func loadConfiguration() { scaleSlider.integerValue = Int(configuration.gridSize) speedSlider.integerValue = sliderValueForSpeedFactor(configuration.speedFactor) delaySlider.integerValue = Int(configuration.startInterval) selectPresetFromSliderValues() } private func saveConfiguration() { configuration.gridSize = CGFloat(scaleSlider.integerValue) configuration.speedFactor = speedFactorForSliderValue(speedSlider.integerValue) configuration.startInterval = Double(delaySlider.integerValue) configuration.sync() } private func selectPresetFromSliderValues() { let index = ConfigureSheetController.presets.firstIndex { preset in preset.gridSize == CGFloat(scaleSlider.integerValue) && preset.speedFactor == speedFactorForSliderValue(speedSlider.integerValue) && preset.startInterval == Double(delaySlider.integerValue) } presetSelector.selectItem(withTag: index ?? -1) } private func applyPresetToSliders() { let tag = presetSelector.selectedTag() if tag >= 0 && tag < ConfigureSheetController.presets.count { let preset = ConfigureSheetController.presets[tag] scaleSlider.animator().integerValue = Int(preset.gridSize) speedSlider.animator().integerValue = sliderValueForSpeedFactor(preset.speedFactor) delaySlider.animator().integerValue = Int(preset.startInterval) } } private func speedFactorForSliderValue(_ value: Int) -> CGFloat { 1 / (speedSlider.maxValue - Double(value) + 1) } private func sliderValueForSpeedFactor(_ factor: CGFloat) -> Int { Int(speedSlider.maxValue - (1.0 / factor) + 1) } @IBAction func openProjectPage(_ sender: AnyObject) { NSWorkspace.shared.open(URL(string: "https://github.com/thoughtworks/tw2021-screensaver")!); } @IBAction func applyPreset(_ sender: NSButton) { ignoreSliderChanges = true Timer.scheduledTimer(withTimeInterval: 0.8, repeats: false) { _ in self.ignoreSliderChanges = false } applyPresetToSliders() } @IBAction func sliderChanged(_ sender: NSSlider) { if ignoreSliderChanges == false { selectPresetFromSliderValues() } } @IBAction func closeConfigureSheet(_ sender: NSButton) { if sender.tag == 1 { saveConfiguration() } window.sheetParent!.endSheet(window, returnCode: (sender.tag == 1) ? NSApplication.ModalResponse.OK : NSApplication.ModalResponse.cancel) } }
36.156716
145
0.67162
deaeb4760892108c59234b8d50a24758591cbe00
3,136
// // DetailTableViewController.swift // JamPop // // Created by Jakob Daugherty on 4/3/18. // Copyright © 2018 Jakob Daugherty. All rights reserved. // import UIKit class DetailTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
32.666667
136
0.673788
ff5a7b1ecc6336caea240bf09c3e1f38dfb89563
8,772
// // EditScanViewController.swift // WeScan // // Created by Boris Emorine on 2/12/18. // Copyright © 2018 WeTransfer. All rights reserved. // import UIKit import AVFoundation /// The `EditScanViewController` offers an interface for the user to edit the detected quadrilateral. final class EditScanViewController: UIViewController { lazy private var imageView: UIImageView = { let imageView = UIImageView() imageView.clipsToBounds = true imageView.isOpaque = true imageView.image = image imageView.backgroundColor = .black imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() lazy private var quadView: QuadrilateralView = { let quadView = QuadrilateralView() quadView.editable = true quadView.translatesAutoresizingMaskIntoConstraints = false return quadView }() lazy private var nextButton: UIBarButtonItem = { let title = NSLocalizedString("wescan.edit.button.next", tableName: nil, bundle: Bundle(for: EditScanViewController.self), value: "Next", comment: "A generic next button") let button = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(pushReviewController)) button.tintColor = navigationController?.navigationBar.tintColor return button }() /// The image the quadrilateral was detected on. private let image: UIImage /// The detected quadrilateral that can be edited by the user. Uses the image's coordinates. private var quad: Quadrilateral private var zoomGestureController: ZoomGestureController! private var quadViewWidthConstraint = NSLayoutConstraint() private var quadViewHeightConstraint = NSLayoutConstraint() // MARK: - Life Cycle init(image: UIImage, quad: Quadrilateral?, rotateImage: Bool = true) { self.image = rotateImage ? image.applyingPortraitOrientation() : image self.quad = quad ?? EditScanViewController.defaultQuad(forImage: image) super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupViews() setupConstraints() title = NSLocalizedString("wescan.edit.title", tableName: nil, bundle: Bundle(for: EditScanViewController.self), value: "Edit Scan", comment: "The title of the EditScanViewController") navigationItem.rightBarButtonItem = nextButton zoomGestureController = ZoomGestureController(image: image, quadView: quadView) let touchDown = UILongPressGestureRecognizer(target: zoomGestureController, action: #selector(zoomGestureController.handle(pan:))) touchDown.minimumPressDuration = 0 view.addGestureRecognizer(touchDown) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() adjustQuadViewConstraints() displayQuad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(false, animated: false) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Work around for an iOS 11.2 bug where UIBarButtonItems don't get back to their normal state after being pressed. navigationController?.navigationBar.tintAdjustmentMode = .normal navigationController?.navigationBar.tintAdjustmentMode = .automatic } // MARK: - Setups private func setupViews() { view.addSubview(imageView) view.addSubview(quadView) } private func setupConstraints() { let imageViewConstraints = [ imageView.topAnchor.constraint(equalTo: view.topAnchor), imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor), view.bottomAnchor.constraint(equalTo: imageView.bottomAnchor), view.leadingAnchor.constraint(equalTo: imageView.leadingAnchor) ] quadViewWidthConstraint = quadView.widthAnchor.constraint(equalToConstant: 0.0) quadViewHeightConstraint = quadView.heightAnchor.constraint(equalToConstant: 0.0) let quadViewConstraints = [ quadView.centerXAnchor.constraint(equalTo: view.centerXAnchor), quadView.centerYAnchor.constraint(equalTo: view.centerYAnchor), quadViewWidthConstraint, quadViewHeightConstraint ] NSLayoutConstraint.activate(quadViewConstraints + imageViewConstraints) } // MARK: - Actions @objc func pushReviewController() { guard let quad = quadView.quad, let ciImage = CIImage(image: image) else { if let imageScannerController = navigationController as? ImageScannerController { let error = ImageScannerControllerError.ciImageCreation imageScannerController.imageScannerDelegate?.imageScannerController(imageScannerController, didFailWithError: error) } return } let scaledQuad = quad.scale(quadView.bounds.size, image.size) self.quad = scaledQuad var cartesianScaledQuad = scaledQuad.toCartesian(withHeight: image.size.height) cartesianScaledQuad.reorganize() let filteredImage = ciImage.applyingFilter("CIPerspectiveCorrection", parameters: [ "inputTopLeft": CIVector(cgPoint: cartesianScaledQuad.bottomLeft), "inputTopRight": CIVector(cgPoint: cartesianScaledQuad.bottomRight), "inputBottomLeft": CIVector(cgPoint: cartesianScaledQuad.topLeft), "inputBottomRight": CIVector(cgPoint: cartesianScaledQuad.topRight) ]) let enhancedImage = filteredImage.applyingAdaptiveThreshold()?.withFixedOrientation() var uiImage: UIImage! // Let's try to generate the CGImage from the CIImage before creating a UIImage. if let cgImage = CIContext(options: nil).createCGImage(filteredImage, from: filteredImage.extent) { uiImage = UIImage(cgImage: cgImage) } else { uiImage = UIImage(ciImage: filteredImage, scale: 1.0, orientation: .up) } let finalImage = uiImage.withFixedOrientation() let results = ImageScannerResults(originalImage: image, scannedImage: finalImage, enhancedImage: enhancedImage, doesUserPreferEnhancedImage: false, detectedRectangle: scaledQuad) let reviewViewController = ReviewViewController(results: results) navigationController?.pushViewController(reviewViewController, animated: true) } private func displayQuad() { let imageSize = image.size let imageFrame = CGRect(origin: quadView.frame.origin, size: CGSize(width: quadViewWidthConstraint.constant, height: quadViewHeightConstraint.constant)) let scaleTransform = CGAffineTransform.scaleTransform(forSize: imageSize, aspectFillInSize: imageFrame.size) let transforms = [scaleTransform] let transformedQuad = quad.applyTransforms(transforms) quadView.drawQuadrilateral(quad: transformedQuad, animated: false) } /// The quadView should be lined up on top of the actual image displayed by the imageView. /// Since there is no way to know the size of that image before run time, we adjust the constraints to make sure that the quadView is on top of the displayed image. private func adjustQuadViewConstraints() { let frame = AVMakeRect(aspectRatio: image.size, insideRect: imageView.bounds) quadViewWidthConstraint.constant = frame.size.width quadViewHeightConstraint.constant = frame.size.height } /// Generates a `Quadrilateral` object that's centered and one third of the size of the passed in image. private static func defaultQuad(forImage image: UIImage) -> Quadrilateral { let topLeft = CGPoint(x: image.size.width / 3.0, y: image.size.height / 3.0) let topRight = CGPoint(x: 2.0 * image.size.width / 3.0, y: image.size.height / 3.0) let bottomRight = CGPoint(x: 2.0 * image.size.width / 3.0, y: 2.0 * image.size.height / 3.0) let bottomLeft = CGPoint(x: image.size.width / 3.0, y: 2.0 * image.size.height / 3.0) let quad = Quadrilateral(topLeft: topLeft, topRight: topRight, bottomRight: bottomRight, bottomLeft: bottomLeft) return quad } }
43.641791
192
0.683425
3a589d3d7d046d0eb4a372d374d61323ae1becb5
3,896
class WMFWelcomeContainerViewController: ThemeableViewController { override func apply(theme: Theme) { super.apply(theme: theme) guard viewIfLoaded != nil else { return } for child in children { guard let themeable = child as? Themeable else { continue } themeable.apply(theme: theme) } } @IBOutlet private var bottomContainerView:UIView! @IBOutlet private var overallContainerStackView:UIStackView! @IBOutlet private var overallContainerStackViewCenterYConstraint:NSLayoutConstraint! @IBOutlet private var topContainerViewHeightConstraint:NSLayoutConstraint! @IBOutlet private var bottomContainerViewHeightConstraint:NSLayoutConstraint! var welcomePageType:WMFWelcomePageType = .intro weak var welcomeNavigationDelegate:WMFWelcomeNavigationDelegate? = nil private var hasAlreadyFadedInAndUp = false private var needsDeviceAdjustments = true override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if (shouldFadeInAndUp() && !hasAlreadyFadedInAndUp) { view.wmf_zeroLayerOpacity() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if (shouldFadeInAndUp() && !hasAlreadyFadedInAndUp) { view.wmf_fadeInAndUpWithDuration(0.4, delay: 0.1) hasAlreadyFadedInAndUp = true } UIAccessibility.post(notification: .screenChanged, argument: view) } private func shouldFadeInAndUp() -> Bool { switch welcomePageType { case .intro: return false case .exploration: return true case .languages: return true case .analytics: return true } } override func updateViewConstraints() { super.updateViewConstraints() if needsDeviceAdjustments { let height = view.bounds.size.height if height <= 568 { // On iPhone 5 reduce size of animations. reduceTopAnimationsSizes(reduction: 30) bottomContainerViewHeightConstraint.constant = 367 overallContainerStackView.spacing = 10 } else { // On everything else add vertical separation between bottom container and animations. overallContainerStackView.spacing = 20 } useBottomAlignmentIfPhone() needsDeviceAdjustments = false } } private func reduceTopAnimationsSizes(reduction: CGFloat) { topContainerViewHeightConstraint.constant = topContainerViewHeightConstraint.constant - reduction } private func useBottomAlignmentIfPhone() { assert(Int(overallContainerStackViewCenterYConstraint.priority.rawValue) == 999, "The Y centering constraint must not have required '1000' priority because on non-tablets we add a required bottom alignment constraint on overallContainerView which we want to be favored when present.") if (UIDevice.current.userInterfaceIdiom == .phone) { overallContainerStackView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination as? WMFWelcomePanelViewController { vc.welcomePageType = welcomePageType vc.apply(theme: theme) } else if let vc = segue.destination as? WMFWelcomeAnimationViewController{ vc.welcomePageType = welcomePageType vc.apply(theme: theme) } } @IBAction private func next(withSender sender: AnyObject) { welcomeNavigationDelegate?.showNextWelcomePage(self) } }
38.574257
292
0.660934
4bee207a9d9cb7b1d06728ae851f39e373b77806
553
// // SuicidalHelpInterfaces.swift // MFLHalsa // // Created by Alex Miculescu on 10/03/2017. // Copyright © 2017 Future Workshops. All rights reserved. // import UIKit import MFL_Common //MARK: - Presenter public protocol NightmaresTraumaHelpPresenter { func userWantsToViewCounsellingApp() func userWantsToCancel() } //MARK: - Wireframe public protocol NightmaresTraumaHelpWireframe { func start(_ dependencies: HasNavigationController & HasStyle) func openLinkInBrowser(_ urlString: String) func dismiss() }
20.481481
66
0.734177
ebfbbc7b600378348634e6695e13b2d5c6c52282
2,354
// // MainCoordinator.swift // MVVM.Demo // // Created by Jason Lew-Rapai on 4/19/18. // Copyright © 2018 Jason Lew-Rapai. All rights reserved. // import UIKit import Swinject class MainCoordinator: Coordinator { private let resolver: Resolver private let navigationControllerTransitionManager: NavigationControllerTransitionManager var rootNavigationController: UINavigationController! init(resolver: Resolver) { self.resolver = resolver self.navigationControllerTransitionManager = resolver.resolve(NavigationControllerTransitionManager.self)! } func start() -> UINavigationController { if self.rootNavigationController == nil { self.rootNavigationController = UINavigationController() self.rootNavigationController.navigationBar.isTranslucent = true self.rootNavigationController.delegate = self.navigationControllerTransitionManager } let viewModel: LaunchScreenViewModel = self.resolver.resolve(LaunchScreenViewModel.self)! .setup(delegate: self) let viewController: LaunchScreenViewController = LaunchScreenViewController(viewModel: viewModel) self.rootNavigationController.viewControllers = [viewController] return self.rootNavigationController } private func launchParty() { DispatchQueue.main.async { let viewController: PartyViewController = PartyViewController(viewModel: self.resolver.resolve(PartyViewModel.self)!) self.rootNavigationController.pushViewController(viewController, animated: true) } } } extension MainCoordinator: LaunchScreenViewModelDelegate { func launchScreenViewModelDidLaunchLogIn(_ source: LaunchScreenViewModel) { let viewController: LoginViewController = LoginViewController( viewModel: self.resolver.resolve(LoginViewModel.self)! .setup(completion: { [weak self] in self?.userDidLogIn() })) self.rootNavigationController.present(viewController, animated: true, completion: nil) } func launchScreenViewModelDidLaunchParty(_ source: LaunchScreenViewModel) { self.launchParty() } private func userDidLogIn() { let userService: UserServiceProtocol = self.resolver.resolve(UserServiceProtocol.self)! if userService.isLoggedIn.value { print("Logged In!") self.launchParty() } else { print("You broke this somehow...") } } }
35.134328
123
0.760408
d6f4a257b95b129247a221fa18b72ec6289aab04
2,173
// // AppDelegate.swift // Flappy Bird // // Created by PROTECO on 23/01/18. // Copyright © 2018 curso proteco. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.234043
285
0.755177
f5772903d6daf867c4988e0738832af7a29b537b
1,050
// // NoReply.swift // /* * ********************************************************************************************************************* * * BACKENDLESS.COM CONFIDENTIAL * * ******************************************************************************************************************** * * Copyright 2019 BACKENDLESS.COM. All Rights Reserved. * * NOTICE: All information contained herein is, and remains the property of Backendless.com and its suppliers, * if any. The intellectual and technical concepts contained herein are proprietary to Backendless.com and its * suppliers and may be covered by U.S. and Foreign Patents, patents in process, and are protected by trade secret * or copyright law. Dissemination of this information or reproduction of this material is strictly forbidden * unless prior written permission is obtained from Backendless.com. * * ******************************************************************************************************************** */ struct NoReply: Decodable { }
45.652174
120
0.495238
e890b92fc2eaad32f0ef4506b2a5ed475c7df2c3
2,670
// // Request.swift // // // Created by Mathieu Perrais on 2/12/21. // import Foundation import Combine // This is a "business logic" request, higher level than the underlying HTTPRequest // (think of it like a high level request of resource) // Response can be anything at this stage but common type would be a Decodable model or a plain confirmation JSON public struct Request<ResponseType> { public let underlyingRequest: HTTPRequest // Custom closure that does the decoding public let decode: (HTTPResponse) throws -> Response<ResponseType> public init(underlyingRequest: HTTPRequest, decode: @escaping (HTTPResponse) throws -> Response<ResponseType>) { self.underlyingRequest = underlyingRequest self.decode = decode } } /// If the `ResponseType` is `Decodable` we add an initializer that takes a `TopLevelDecoder` to do the transformation to the Decodable Model extension Request where ResponseType: Decodable { // request a value that's decoded using a plain JSON decoder public init(underlyingRequest: HTTPRequest) { self.init(underlyingRequest: underlyingRequest, decoder: JSONDecoder()) } // request a value that's decoded using the specified decoder // requires: import Combine public init<D: TopLevelDecoder>(underlyingRequest: HTTPRequest, decoder: D) where D.Input == Data { self.init( underlyingRequest: underlyingRequest, decode: { httpResponse in // Custom closure, just a call to decoding on the custom decoder we passed (closure can throw) let body = try httpResponse.validateBody(underlyingRequest: underlyingRequest) let bodyModel = try decoder.decode(ResponseType.self, from: body) return Response(httpResponse: httpResponse, body: bodyModel) } ) } } /// If the `ResponseType` is `Decodable` we add an initializer that takes a `TopLevelDecoder` to do the transformation to the Decodable Model extension Request where ResponseType == JSONDictionary { public init(underlyingRequest: HTTPRequest) { self.init( underlyingRequest: underlyingRequest, decode: { httpResponse in // Custom closure, we use built-in json deserialization to return the Dictionary let body = try httpResponse.validateBody(underlyingRequest: underlyingRequest) let bodyJSON = try JSONSerialization.jsonObject(with: body) as? JSONDictionary ?? [:] return Response(httpResponse: httpResponse, body: bodyJSON) } ) } }
40.454545
141
0.682397
722231ee2947c2a266defcb02357c14e9ba34a23
2,623
import UIKit import RxSwift public extension UICollectionView { func registerClassForCell(_ cellClass: UICollectionViewCell.Type) { register(cellClass, forCellWithReuseIdentifier: cellClass.reuseIdentifier) } func registerClassesForCells(_ cellClasses: UICollectionViewCell.Type...) { for cellClass in cellClasses { registerClassForCell(cellClass) } } func dequeueReusableCell<T: UICollectionViewCell>(for indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell( withReuseIdentifier: T.self.reuseIdentifier, for: indexPath) as? T else { fatalError("You are trying to dequeue \(T.self) which is not registered") } return cell } func registerClassForSupplementaryView(_ viewClass: UICollectionReusableView.Type, ofKind kind: String) { register( viewClass, forSupplementaryViewOfKind: kind, withReuseIdentifier: viewClass.reuseIdentifier ) } func dequeueReusableSupplementaryView<T: UICollectionReusableView>( ofKind kind: String, for indexPath: IndexPath ) -> T { guard let view = dequeueReusableSupplementaryView( ofKind: kind, withReuseIdentifier: T.self.reuseIdentifier, for: indexPath) as? T else { fatalError("You are trying to dequeue \(T.self) which is not registered") } return view } func registerClassForHeaderView(_ viewClass: UICollectionReusableView.Type) { registerClassForSupplementaryView(viewClass, ofKind: UICollectionView.elementKindSectionHeader) } func dequeueReusableHeaderView<T: UICollectionReusableView>(for indexPath: IndexPath) -> T { dequeueReusableSupplementaryView( ofKind: UICollectionView.elementKindSectionHeader, for: indexPath ) } func registerClassForFooterView(_ viewClass: UICollectionReusableView.Type) { registerClassForSupplementaryView(viewClass, ofKind: UICollectionView.elementKindSectionFooter) } func dequeueReusableFooterView<T: UICollectionReusableView>(for indexPath: IndexPath) -> T { dequeueReusableSupplementaryView( ofKind: UICollectionView.elementKindSectionFooter, for: indexPath ) } } public extension Reactive where Base: UICollectionView { // swiftlint:disable all func items<Sequence: Swift.Sequence, Cell: UICollectionViewCell, Source: ObservableType> (_ cellClass: Cell.Type) -> (_ source: Source) -> (_ configureCell: @escaping (Int, Sequence.Element, Cell) -> Void) -> Disposable where Source.Element == Sequence { return base.rx.items(cellIdentifier: cellClass.reuseIdentifier, cellType: cellClass) } }
32.7875
107
0.742661
296cad43500beb6691842b70f9995fb0cada256b
553
// // GifImageDataEndpoint.swift // giphy-layout // // Created by Alexandra Bashkirova on 26.03.2022. // import Foundation import UIKit enum GifImageDataError: Error { case notValid } struct GifImageDataEndpoint: Endpoint, RequestBuildable { typealias Response = Data private let url: URL init(url: URL) { self.url = url } func makeRequest() -> URLRequest? { get(url) } func response(from response: URLResponse?, with body: Data) throws -> Response { return body } }
17.28125
84
0.629295
d6050a33aaab72f117770366b4ebddd42ae7cc56
330
// // SelfSheetViewController.swift // ultimate-sheet-swift // // Created by Boris Dipner on 08.04.2020. // Copyright © 2020 Boris Dipner. All rights reserved. // import UIKit class SelfSheetViewController: UIViewController { @IBOutlet var handleArea: UIView! @IBOutlet weak var handleViewRectangle: UIView! }
19.411765
55
0.724242
16fa831f01f7381b7d9ff0934897910b005febe6
2,381
// // Copyright (c) 2019-Present Umobi - https://github.com/umobi // // 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 public extension UIImage { convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgImage = image?.cgImage else { return nil } self.init(cgImage: cgImage) } func with(color: UIColor) -> UIImage { guard let cgImage = self.cgImage else { return self } UIGraphicsBeginImageContextWithOptions(size, false, scale) let context = UIGraphicsGetCurrentContext()! context.translateBy(x: 0, y: size.height) context.scaleBy(x: 1.0, y: -1.0) context.setBlendMode(.normal) let imageRect = CGRect(x: 0, y: 0, width: size.width, height: size.height) context.clip(to: imageRect, mask: cgImage) color.setFill() context.fill(imageRect) let newImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext(); return newImage } } #endif
41.051724
83
0.698866
f890dc7890423960cd90e93ec5335eadbbed14b1
19,448
let WMFAppResignActiveDateKey = "WMFAppResignActiveDateKey" let WMFShouldRestoreNavigationStackOnResume = "WMFShouldRestoreNavigationStackOnResume" let WMFAppSiteKey = "Domain" let WMFSearchURLKey = "WMFSearchURLKey" let WMFMostRecentInTheNewsNotificationDateKey = "WMFMostRecentInTheNewsNotificationDate" let WMFInTheNewsMostRecentDateNotificationCountKey = "WMFInTheNewsMostRecentDateNotificationCount" let WMFDidShowNewsNotificatonInFeedKey = "WMFDidShowNewsNotificatonInFeedKey" let WMFInTheNewsNotificationsEnabled = "WMFInTheNewsNotificationsEnabled" let WMFFeedRefreshDateKey = "WMFFeedRefreshDateKey" let WMFLocationAuthorizedKey = "WMFLocationAuthorizedKey" let WMFPlacesDidPromptForLocationAuthorization = "WMFPlacesDidPromptForLocationAuthorization" let WMFExploreDidPromptForLocationAuthorization = "WMFExploreDidPromptForLocationAuthorization" let WMFPlacesHasAppeared = "WMFPlacesHasAppeared" let WMFAppThemeName = "WMFAppThemeName" let WMFIsImageDimmingEnabled = "WMFIsImageDimmingEnabled" let WMFIsAutomaticTableOpeningEnabled = "WMFIsAutomaticTableOpeningEnabled" let WMFDidShowThemeCardInFeed = "WMFDidShowThemeCardInFeed" let WMFDidShowReadingListCardInFeed = "WMFDidShowReadingListCardInFeed" let WMFDidShowEnableReadingListSyncPanelKey = "WMFDidShowEnableReadingListSyncPanelKey" let WMFDidShowLoginToSyncSavedArticlesToReadingListPanelKey = "WMFDidShowLoginToSyncSavedArticlesToReadingListPanelKey" let WMFDidShowThankRevisionAuthorEducationPanelKey = "WMFDidShowThankRevisionAuthorEducationPanelKey" let WMFDidShowLimitHitForUnsortedArticlesPanel = "WMFDidShowLimitHitForUnsortedArticlesPanel" let WMFDidShowSyncDisabledPanel = "WMFDidShowSyncDisabledPanel" let WMFDidShowSyncEnabledPanel = "WMFDidShowSyncEnabledPanel" let WMFDidSplitExistingReadingLists = "WMFDidSplitExistingReadingLists" let WMFDidShowTitleDescriptionEditingIntro = "WMFDidShowTitleDescriptionEditingIntro" let WMFDidShowFirstEditPublishedPanelKey = "WMFDidShowFirstEditPublishedPanelKey" let WMFIsSyntaxHighlightingEnabled = "WMFIsSyntaxHighlightingEnabled" let WMFSearchLanguageKey = "WMFSearchLanguageKey" let WMFAppInstallId = "WMFAppInstallId" let WMFSendUsageReports = "WMFSendUsageReports" let WMFShowNotificationsExploreFeedCard = "WMFShowNotificationsExploreFeedCard" let WMFUserHasOnboardedToNotificationsCenter = "WMFUserHasOnboardedToNotificationsCenter" let WMFDidShowNotificationsCenterPushOptInPanel = "WMFDidShowNotificationsCenterPushOptInPanel" let WMFSubscribedToEchoNotifications = "WMFSubscribedToEchoNotifications" @objc public enum WMFAppDefaultTabType: Int { case explore case settings } @objc public extension UserDefaults { @objc(WMFUserDefaultsKey) class Key: NSObject { @objc static let defaultTabType = "WMFDefaultTabTypeKey" static let isUserUnawareOfLogout = "WMFIsUserUnawareOfLogout" static let didShowDescriptionPublishedPanel = "WMFDidShowDescriptionPublishedPanel" static let didShowEditingOnboarding = "WMFDidShowEditingOnboarding" static let autoSignTalkPageDiscussions = "WMFAutoSignTalkPageDiscussions" static let talkPageForceRefreshRevisionIDs = "WMFTalkPageForceRefreshRevisionIDs" } @objc func wmf_dateForKey(_ key: String) -> Date? { return self.object(forKey: key) as? Date } @objc func wmf_appResignActiveDate() -> Date? { return self.wmf_dateForKey(WMFAppResignActiveDateKey) } @objc func wmf_setAppResignActiveDate(_ date: Date?) { if let date = date { self.set(date, forKey: WMFAppResignActiveDateKey) }else{ self.removeObject(forKey: WMFAppResignActiveDateKey) } } @objc var shouldRestoreNavigationStackOnResume: Bool { get { return bool(forKey: WMFShouldRestoreNavigationStackOnResume) } set { set(newValue, forKey: WMFShouldRestoreNavigationStackOnResume) } } @objc var wmf_lastAppVersion: String? { get { return string(forKey: "WMFLastAppVersion") } set { set(newValue, forKey: "WMFLastAppVersion") } } @objc var wmf_appInstallId: String? { get { var appInstallId = string(forKey: WMFAppInstallId) if appInstallId == nil { appInstallId = UUID().uuidString set(appInstallId, forKey: WMFAppInstallId) } return appInstallId } set { set(newValue, forKey: WMFAppInstallId) } } @objc var wmf_sendUsageReports: Bool { get { return bool(forKey: WMFSendUsageReports) } set { set(newValue, forKey: WMFSendUsageReports) } } @objc var wmf_isSubscribedToEchoNotifications: Bool { get { return bool(forKey: WMFSubscribedToEchoNotifications) } set { set(newValue, forKey: WMFSubscribedToEchoNotifications) } } @objc func wmf_setFeedRefreshDate(_ date: Date) { self.set(date, forKey: WMFFeedRefreshDateKey) } @objc func wmf_feedRefreshDate() -> Date? { return self.wmf_dateForKey(WMFFeedRefreshDateKey) } @objc func wmf_setLocationAuthorized(_ authorized: Bool) { self.set(authorized, forKey: WMFLocationAuthorizedKey) } @objc var themeAnalyticsName: String { let name = string(forKey: WMFAppThemeName) let systemDarkMode = systemDarkModeEnabled guard name != nil, name != Theme.defaultThemeName else { return systemDarkMode ? Theme.black.analyticsName : Theme.light.analyticsName } if Theme.withName(name)?.name == Theme.light.name { return Theme.defaultAnalyticsThemeName } return Theme.withName(name)?.analyticsName ?? Theme.light.analyticsName } @objc var themeDisplayName: String { let name = string(forKey: WMFAppThemeName) guard name != nil, name != Theme.defaultThemeName else { return CommonStrings.defaultThemeDisplayName } return Theme.withName(name)?.displayName ?? Theme.light.displayName } @objc(themeCompatibleWith:) func theme(compatibleWith traitCollection: UITraitCollection) -> Theme { let name = string(forKey: WMFAppThemeName) let systemDarkMode = traitCollection.userInterfaceStyle == .dark systemDarkModeEnabled = systemDarkMode guard name != nil, name != Theme.defaultThemeName else { return systemDarkMode ? Theme.black.withDimmingEnabled(wmf_isImageDimmingEnabled) : .light } let theme = Theme.withName(name) ?? Theme.light return theme.isDark ? theme.withDimmingEnabled(wmf_isImageDimmingEnabled) : theme } @objc var themeName: String { get { string(forKey: WMFAppThemeName) ?? Theme.defaultThemeName } set { set(newValue, forKey: WMFAppThemeName) } } @objc var wmf_isImageDimmingEnabled: Bool { get { return bool(forKey: WMFIsImageDimmingEnabled) } set { set(newValue, forKey: WMFIsImageDimmingEnabled) } } @objc var wmf_IsSyntaxHighlightingEnabled: Bool { get { if object(forKey: WMFIsSyntaxHighlightingEnabled) == nil { return true //default to highlighting enabled } return bool(forKey: WMFIsSyntaxHighlightingEnabled) } set { set(newValue, forKey: WMFIsSyntaxHighlightingEnabled) } } @objc var wmf_isAutomaticTableOpeningEnabled: Bool { get { return bool(forKey: WMFIsAutomaticTableOpeningEnabled) } set { set(newValue, forKey: WMFIsAutomaticTableOpeningEnabled) } } @objc var wmf_didShowThemeCardInFeed: Bool { get { return bool(forKey: WMFDidShowThemeCardInFeed) } set { set(newValue, forKey: WMFDidShowThemeCardInFeed) } } @objc var wmf_didShowReadingListCardInFeed: Bool { get { return bool(forKey: WMFDidShowReadingListCardInFeed) } set { set(newValue, forKey: WMFDidShowReadingListCardInFeed) } } @objc func wmf_locationAuthorized() -> Bool { return self.bool(forKey: WMFLocationAuthorizedKey) } @objc func wmf_setPlacesHasAppeared(_ hasAppeared: Bool) { self.set(hasAppeared, forKey: WMFPlacesHasAppeared) } @objc func wmf_placesHasAppeared() -> Bool { return self.bool(forKey: WMFPlacesHasAppeared) } @objc func wmf_setPlacesDidPromptForLocationAuthorization(_ didPrompt: Bool) { self.set(didPrompt, forKey: WMFPlacesDidPromptForLocationAuthorization) } @objc func wmf_placesDidPromptForLocationAuthorization() -> Bool { return self.bool(forKey: WMFPlacesDidPromptForLocationAuthorization) } @objc func wmf_setExploreDidPromptForLocationAuthorization(_ didPrompt: Bool) { self.set(didPrompt, forKey: WMFExploreDidPromptForLocationAuthorization) } @objc func wmf_exploreDidPromptForLocationAuthorization() -> Bool { return self.bool(forKey: WMFExploreDidPromptForLocationAuthorization) } @objc func wmf_setShowSearchLanguageBar(_ enabled: Bool) { self.set(NSNumber(value: enabled as Bool), forKey: "ShowLanguageBar") } @objc func wmf_showSearchLanguageBar() -> Bool { if let enabled = self.object(forKey: "ShowLanguageBar") as? NSNumber { return enabled.boolValue }else{ return false } } @objc var wmf_openAppOnSearchTab: Bool { get { return bool(forKey: "WMFOpenAppOnSearchTab") } set { set(newValue, forKey: "WMFOpenAppOnSearchTab") } } @objc func wmf_currentSearchContentLanguageCode() -> String? { self.string(forKey: WMFSearchLanguageKey) } @objc func wmf_setCurrentSearchContentLanguageCode(_ code: String?) { if let code = code { set(code, forKey: WMFSearchLanguageKey) } else { removeObject(forKey: WMFSearchLanguageKey) } } @objc func wmf_setDidShowWIconPopover(_ shown: Bool) { self.set(NSNumber(value: shown as Bool), forKey: "ShowWIconPopover") } @objc func wmf_didShowWIconPopover() -> Bool { if let enabled = self.object(forKey: "ShowWIconPopover") as? NSNumber { return enabled.boolValue }else{ return false } } @objc func wmf_setDidShowMoreLanguagesTooltip(_ shown: Bool) { self.set(NSNumber(value: shown as Bool), forKey: "ShowMoreLanguagesTooltip") } @objc func wmf_didShowMoreLanguagesTooltip() -> Bool { if let enabled = self.object(forKey: "ShowMoreLanguagesTooltip") as? NSNumber { return enabled.boolValue }else{ return false } } @objc func wmf_setTableOfContentsIsVisibleInline(_ visibleInline: Bool) { self.set(NSNumber(value: visibleInline as Bool), forKey: "TableOfContentsIsVisibleInline") } @objc func wmf_isTableOfContentsVisibleInline() -> Bool { if let enabled = self.object(forKey: "TableOfContentsIsVisibleInline") as? NSNumber { return enabled.boolValue }else{ return true } } @objc func wmf_setDidFinishLegacySavedArticleImageMigration(_ didFinish: Bool) { self.set(didFinish, forKey: "DidFinishLegacySavedArticleImageMigration2") } @objc func wmf_didFinishLegacySavedArticleImageMigration() -> Bool { return self.bool(forKey: "DidFinishLegacySavedArticleImageMigration2") } @objc func wmf_mostRecentInTheNewsNotificationDate() -> Date? { return self.wmf_dateForKey(WMFMostRecentInTheNewsNotificationDateKey) } @objc func wmf_setMostRecentInTheNewsNotificationDate(_ date: Date) { self.set(date, forKey: WMFMostRecentInTheNewsNotificationDateKey) } @objc func wmf_inTheNewsMostRecentDateNotificationCount() -> Int { return self.integer(forKey: WMFInTheNewsMostRecentDateNotificationCountKey) } @objc func wmf_setInTheNewsMostRecentDateNotificationCount(_ count: Int) { self.set(count, forKey: WMFInTheNewsMostRecentDateNotificationCountKey) } @objc func wmf_inTheNewsNotificationsEnabled() -> Bool { return self.bool(forKey: WMFInTheNewsNotificationsEnabled) } @objc func wmf_setInTheNewsNotificationsEnabled(_ enabled: Bool) { self.set(enabled, forKey: WMFInTheNewsNotificationsEnabled) } @objc func wmf_setDidShowNewsNotificationCardInFeed(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowNewsNotificatonInFeedKey) } @objc func wmf_didShowNewsNotificationCardInFeed() -> Bool { return self.bool(forKey: WMFDidShowNewsNotificatonInFeedKey) } @objc func wmf_setDidShowEnableReadingListSyncPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowEnableReadingListSyncPanelKey) } @objc func wmf_didShowEnableReadingListSyncPanel() -> Bool { return self.bool(forKey: WMFDidShowEnableReadingListSyncPanelKey) } @objc func wmf_setDidShowLoginToSyncSavedArticlesToReadingListPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowLoginToSyncSavedArticlesToReadingListPanelKey) } @objc func wmf_didShowLoginToSyncSavedArticlesToReadingListPanel() -> Bool { return self.bool(forKey: WMFDidShowLoginToSyncSavedArticlesToReadingListPanelKey) } @objc func wmf_setDidShowThankRevisionAuthorEducationPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowThankRevisionAuthorEducationPanelKey) } @objc func wmf_didShowThankRevisionAuthorEducationPanel() -> Bool { return self.bool(forKey: WMFDidShowThankRevisionAuthorEducationPanelKey) } @objc func wmf_setDidShowFirstEditPublishedPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowFirstEditPublishedPanelKey) } @objc func wmf_didShowFirstEditPublishedPanel() -> Bool { return self.bool(forKey: WMFDidShowFirstEditPublishedPanelKey) } @objc func wmf_didShowLimitHitForUnsortedArticlesPanel() -> Bool { return self.bool(forKey: WMFDidShowLimitHitForUnsortedArticlesPanel) } @objc func wmf_setDidShowLimitHitForUnsortedArticlesPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowLimitHitForUnsortedArticlesPanel) } @objc func wmf_didShowSyncDisabledPanel() -> Bool { return self.bool(forKey: WMFDidShowSyncDisabledPanel) } @objc func wmf_setDidShowSyncDisabledPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowSyncDisabledPanel) } @objc func wmf_didShowSyncEnabledPanel() -> Bool { return self.bool(forKey: WMFDidShowSyncEnabledPanel) } @objc func wmf_setDidShowSyncEnabledPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowSyncEnabledPanel) } @objc func wmf_didSplitExistingReadingLists() -> Bool { return self.bool(forKey: WMFDidSplitExistingReadingLists) } @objc func wmf_setDidSplitExistingReadingLists(_ didSplit: Bool) { self.set(didSplit, forKey: WMFDidSplitExistingReadingLists) } @objc var defaultTabType: WMFAppDefaultTabType { get { guard let defaultTabType = WMFAppDefaultTabType(rawValue: integer(forKey: UserDefaults.Key.defaultTabType)) else { let explore = WMFAppDefaultTabType.explore set(explore.rawValue, forKey: UserDefaults.Key.defaultTabType) return explore } return defaultTabType } set { set(newValue.rawValue, forKey: UserDefaults.Key.defaultTabType) wmf_openAppOnSearchTab = newValue == .settings } } @objc func wmf_didShowTitleDescriptionEditingIntro() -> Bool { return self.bool(forKey: WMFDidShowTitleDescriptionEditingIntro) } @objc func wmf_setDidShowTitleDescriptionEditingIntro(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowTitleDescriptionEditingIntro) } @objc var wmf_userHasOnboardedToNotificationsCenter: Bool { get { return bool(forKey: WMFUserHasOnboardedToNotificationsCenter) } set { set(newValue, forKey: WMFUserHasOnboardedToNotificationsCenter) } } @objc var wmf_didShowNotificationsCenterPushOptInPanel: Bool { get { return bool(forKey: WMFDidShowNotificationsCenterPushOptInPanel) } set { set(newValue, forKey: WMFDidShowNotificationsCenterPushOptInPanel) } } var isUserUnawareOfLogout: Bool { get { return bool(forKey: UserDefaults.Key.isUserUnawareOfLogout) } set { set(newValue, forKey: UserDefaults.Key.isUserUnawareOfLogout) } } var didShowDescriptionPublishedPanel: Bool { get { return bool(forKey: UserDefaults.Key.didShowDescriptionPublishedPanel) } set { set(newValue, forKey: UserDefaults.Key.didShowDescriptionPublishedPanel) } } @objc var didShowEditingOnboarding: Bool { get { return bool(forKey: UserDefaults.Key.didShowEditingOnboarding) } set { set(newValue, forKey: UserDefaults.Key.didShowEditingOnboarding) } } var autoSignTalkPageDiscussions: Bool { get { return bool(forKey: UserDefaults.Key.autoSignTalkPageDiscussions) } set { set(newValue, forKey: UserDefaults.Key.autoSignTalkPageDiscussions) } } var talkPageForceRefreshRevisionIDs: Set<Int>? { get { guard let arrayValue = array(forKey: UserDefaults.Key.talkPageForceRefreshRevisionIDs) as? [Int], !arrayValue.isEmpty else { return nil } return Set<Int>(arrayValue) } set { guard let newValue = newValue, !newValue.isEmpty else { removeObject(forKey: UserDefaults.Key.talkPageForceRefreshRevisionIDs) return } let arrayValue = Array(newValue) set(arrayValue, forKey: UserDefaults.Key.talkPageForceRefreshRevisionIDs) } } private var systemDarkModeEnabled: Bool { get { return bool(forKey: "SystemDarkMode") } set { set(newValue, forKey: "SystemDarkMode") } } @objc var wmf_shouldShowNotificationsExploreFeedCard: Bool { get { return bool(forKey: WMFShowNotificationsExploreFeedCard) } set{ set(newValue, forKey: WMFShowNotificationsExploreFeedCard) } } #if UI_TEST @objc func wmf_isFastlaneSnapshotInProgress() -> Bool { return bool(forKey: "FASTLANE_SNAPSHOT") } #endif }
35.75
126
0.682127
09975cffdb381eff9b81eb41b38fb98caf84d8ca
478
// // CheckDatabaseEncryptionKey.swift // tl2swift // // Created by Code Generator // import Foundation /// Checks the database encryption key for correctness. Works only when the current authorization state is authorizationStateWaitEncryptionKey public struct CheckDatabaseEncryptionKey: Codable { /// Encryption key to check or set up public let encryptionKey: Data? public init(encryptionKey: Data?) { self.encryptionKey = encryptionKey } }
20.782609
142
0.740586
62647d879d7cc29efcd6fa93586597fc850330ec
2,807
// // ViewController.swift // Sample // // Created by Meniny on 2018-01-31. // Copyright © 2018年 Meniny Lab. All rights reserved. // import UIKit import TableFlow class ViewController: UITableViewController { lazy var manager: TableManager = { return TableManager.init(table: self.tableView) }() var dataSource: [Site] = [] override func viewDidLoad() { super.viewDidLoad() self.tableView.rowHeight = UITableView.automaticDimension self.tableView.tableFooterView = UITableViewHeaderFooterView.init() self.refresh() } func refresh() { self.manager.removeAll() self.manager.add(section: self.generateSection()) self.manager.reloadData() } func fillData() { let image = Image.named("avatar") self.dataSource.append(Site.init(name: "Github", url: "https://github.com", icon: image)) self.dataSource.append(Site.init(name: "Google", url: "https://google.com", icon: image)) self.dataSource.append(Site.init(name: "Twitter", url: "https://twitter.com", icon: image)) self.dataSource.append(Site.init(name: "Facebook", url: "https://facebook.com", icon: image)) self.dataSource.append(Site.init(name: "Youtube", url: "https://youtube.com", icon: image)) } let SECTION_ID = "SECTION_ID" func generateSection() -> Section { self.fillData() let section = Section.init(id: SECTION_ID, rows: []) for s in dataSource { // Or use the typealias: `SiteRow` let row = Row<SiteInfoTableViewCell>.init(model: s) row.onTap({ (r) -> (RowTapBehaviour?) in self.alert(s.name) return RowTapBehaviour.deselect(true) }) section.add(row) } // Or use `Row<SwitchTableViewCell>` let switchRow = SwitchRow.init(title: "Require PC version", isOn: true) switchRow.onChange { (config) in self.alert("\(config.title ?? ""): \(config.isOn)") } section.add(switchRow) let selectionRow = SelectionRow.init(mode: .present, title: "Your age", select: "19", in: "18", "19", "20", "21", "22", "23") selectionRow.accessoryType = .disclosureIndicator selectionRow.onChange { (r) in self.alert(r.default ?? "") } section.add(selectionRow) return section } func alert(_ text: String) { let controller = UIAlertController.init(title: "Message", message: text, preferredStyle: .alert) controller.addAction(UIAlertAction.init(title: "Done", style: .cancel, handler: nil)) self.present(controller, animated: true, completion: nil) } }
33.416667
133
0.597435
26dae581522a4d9ab984006322bc2c8b8ae98026
968
//===--- LoggerInitialization.swift ---------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2017-2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation /// Initializes the PlaygroundLogger framework. /// /// - note: This function is invoked by host stubs via dlsym. @_cdecl("PGLInitializePlaygroundLogger") public func initializePlaygroundLogger(clientVersion: Int, sendData: @escaping SendDataFunction) -> Void { Swift._playgroundPrintHook = printHook PlaygroundLogger.sendData = sendData // TODO: take clientVersion and use to customize PlaygroundLogger behavior. }
38.72
106
0.660124
01ca357fa43af8a7b7bee8744e4f6e1330e0dd2a
311
// // Videos.swift // vidStream // // Created by Anupriya Soman on 27/11/2019. // Copyright © 2019 Anupriya Soman. All rights reserved. // import Foundation import Foundation struct Videos: Decodable { let description: String? let thumb: String? let title: String? let sources: String? }
16.368421
57
0.681672
4636e8c3d5e8cb425a7cef99fa57d9cb9f89bb7d
19,591
import AppKit protocol MinefieldDelegate: class { func minefieldWindowShouldClose(_ minefield: Minefield) -> Bool func minefieldWindowDidResize(_ minefield: Minefield) } class Minefield: NSView { enum MineStyle: Int { case bomb case flower var description: String { switch self { case .bomb: return "mine-style-bomb".localized case .flower: return "mine-style-flower".localized } } } enum FieldStyle: Int { case solid case sheet } struct Difficulty: Equatable { var numberOfColumns: Int var numberOfRows: Int var numberOfMines: Int static let beginner: Difficulty = Difficulty(numberOfColumns: 9, numberOfRows: 9, numberOfMines: 10) static let intermediate: Difficulty = Difficulty(numberOfColumns: 16, numberOfRows: 16, numberOfMines: 40) static let advanced: Difficulty = Difficulty(numberOfColumns: 30, numberOfRows: 16, numberOfMines: 99) var rawValues: [Int] {[numberOfColumns, numberOfRows, numberOfMines]} init(numberOfColumns: Int, numberOfRows: Int, numberOfMines: Int) { self.numberOfColumns = numberOfColumns self.numberOfRows = numberOfRows self.numberOfMines = numberOfMines } init(rawValues: [Int]) { self.numberOfColumns = rawValues[0] self.numberOfRows = rawValues[1] self.numberOfMines = rawValues[2] } init?(tag: Int) { switch tag { case 1: self = .beginner case 2: self = .intermediate case 3: self = .advanced default: return nil } } } weak var delegate: MinefieldDelegate? var difficulty: Difficulty var moundMatrix: MoundMatrix! var moundDelegate: MoundDelegate var numberOfColumns: Int {difficulty.numberOfColumns} var numberOfRows: Int {difficulty.numberOfRows} var numberOfMounds: Int {difficulty.numberOfColumns * difficulty.numberOfRows} var numberOfMines: Int {difficulty.numberOfMines} var mineStyle: MineStyle var fieldStyle: FieldStyle var standardMoundSize: CGFloat {fieldStyle == .sheet ? 26 : 24} var minMoundSize: CGFloat {fieldStyle == .sheet ? 24 : 22} var maxMoundSize: CGFloat {36} var moundSize: CGFloat var contentInsets: NSEdgeInsets { fieldStyle == .sheet ? NSEdgeInsets(top: -1, left: 1, bottom: 1, right: 1) : NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } var hasDeployed: Bool = false let animationSeparatingDuration: Double = 0.2 let delayAfterFirstSubanimation: Double = 0.4 var animationSignature: TimeInterval = 0 var isAnimatingResizing: Bool = false var states: String { get { var states = "" moundMatrix.forEach {mound in states.append("\(mound.state.rawValue) ") states.append("\(mound.hint) ") } return states } set { let split = newValue.split(separator: " ").map {Int(String($0))!} moundMatrix.forEach {mound, _, rawIndex in mound.state = Mound.State(rawValue: split[rawIndex * 2]) mound.hint = split[rawIndex * 2 + 1] } } } init(mineStyle: MineStyle?, fieldStyle: FieldStyle?, moundSize: CGFloat?, difficulty: Difficulty?, moundDelegate: MoundDelegate) { if fieldStyle != nil { self.fieldStyle = fieldStyle! } else if #available(OSX 10.16, *) { self.fieldStyle = .sheet } else { self.fieldStyle = .solid } self.mineStyle = mineStyle ?? .bomb self.moundSize = 0 self.difficulty = difficulty ?? .beginner self.moundDelegate = moundDelegate super.init(frame: .zero) self.moundSize = max(minMoundSize, round(moundSize ?? standardMoundSize)) wantsLayer = true layerContentsRedrawPolicy = .onSetNeedsDisplay moundMatrix = MoundMatrix( numberOfColumns: self.difficulty.numberOfColumns, numberOfRows: self.difficulty.numberOfRows, delegate: self ) } required init?(coder: NSCoder) {nil} override func viewDidChangeEffectiveAppearance() { Mound.invalidCaches() setWindowBackground() } func layoutMounds() { moundMatrix.forEach {mound, index in moundMatrix(moundMatrix, update: mound, at: index) } } func reuse(undeploys: Bool, extraAction: ((Mound) -> Void)? = nil) { if undeploys { hasDeployed = false moundMatrix.forEach {mound in mound.state = .covered(withFlag: .none) mound.hint = 0 extraAction?(mound) } } else { moundMatrix.forEach {mound in mound.state = .covered(withFlag: .none) if mound.hasMine { mound.showsMine = false } extraAction?(mound) } } } func fittingSize(numberOfColumns: Int? = nil, numberOfRows: Int? = nil, moundSize: CGFloat? = nil) -> NSSize { let theNumberOfColumns = numberOfColumns ?? self.numberOfColumns let theNumberOfRows = numberOfRows ?? self.numberOfRows let theMoundSize = moundSize ?? self.moundSize return NSSize( width: CGFloat(theNumberOfColumns) * theMoundSize + contentInsets.left + contentInsets.right, height: CGFloat(theNumberOfRows) * theMoundSize + contentInsets.top + contentInsets.bottom ) } func moundSize(frame: NSRect? = nil, numberOfColumns: Int? = nil, numberOfRows: Int? = nil, rounds: Bool = true) -> CGFloat { let theFrame = frame ?? self.frame let theNumberOfColumns = numberOfColumns ?? self.numberOfColumns let moundSize = (theFrame.width - contentInsets.left - contentInsets.right) / CGFloat(theNumberOfColumns) if rounds { return round(moundSize) } else { return moundSize } } func resizeToMatchDifficulty() { if moundMatrix.numberOfColumns == numberOfColumns, moundMatrix.numberOfRows == numberOfRows { return reuse(undeploys: true) } hasDeployed = false let oldContentSize = frame.size let newContentSize = fittingSize() let newWindowFrameSize = window!.frameRect(forContentRect: NSRect(origin: .zero, size: newContentSize)).size let newWindowFrame = NSRect( origin: NSPoint( x: round(window!.frame.minX - (newWindowFrameSize.width - window!.frame.width) / 2), y: window!.frame.minY - (newWindowFrameSize.height - window!.frame.height) ), size: newWindowFrameSize ) let duration = window!.animationResizeTime(newWindowFrame) let oldCache = bitmapImageRepForCachingDisplay(in: bounds)! cacheDisplay(in: bounds, to: oldCache) moundMatrix.setSize(numberOfColumns: numberOfColumns, numberOfRows: numberOfRows) reuse(undeploys: true) {$0.layout()} setFrameSize(newContentSize) let newCache = bitmapImageRepForCachingDisplay(in: bounds)! cacheDisplay(in: bounds, to: newCache) subviews.forEach {$0.isHidden = true} setFrameSize(oldContentSize) let contentAnimation = CABasicAnimation(keyPath: "contents") contentAnimation.fromValue = oldCache.cgImage contentAnimation.duration = duration contentAnimation.delegate = self layer!.contents = newCache.cgImage layer!.add(contentAnimation, forKey: nil) window!.setFrame(newWindowFrame, display: false, animate: true) isAnimatingResizing = true DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + duration) { self.isAnimatingResizing = false } setWindowRatio() } func deployMines(skip skippedIndices: Set<MoundMatrix.Index>) { var mineArray: [Bool] = [] for _ in 0..<numberOfMines {mineArray.append(true)} for _ in numberOfMines..<(numberOfColumns * numberOfRows - skippedIndices.count) {mineArray.append(false)} mineArray.shuffle() var offset = 0 moundMatrix.forEach {mound, index, rawIndex in if skippedIndices.contains(index) {return offset += 1} if !mineArray[rawIndex - offset] {return} mound.hasMine = true index.vicinities.forEach {vicinityIndex in if let vicinityMound = moundMatrix[vicinityIndex], !vicinityMound.hasMine { vicinityMound.hint += 1 } } } hasDeployed = true } private func beginAnimationWindow( from centerMound: Mound, animationViewType AnimationView: AnimationView.Type, subanimationWillStart: @escaping (Mound, TimeInterval) -> Void, delaysAfterFirstSubanimation: Bool, then callback: @escaping () -> Void ) { guard !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion else { moundMatrix.forEach {mound, index in if mound.hasMine { mound.showMine(animates: true, flashes: true, duration: 0.5) } } return DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: callback) } let animationWindow = AnimationWindow(frame: window!.frame, viewType: AnimationView, didClose: callback) let centerIndex = moundMatrix.indexOf(centerMound)! var minedMounds: [(Mound, Double)] = [] moundMatrix.forEach {mound, index in if mound.hasMine { let distance = sqrt(pow(Double(index.column - centerIndex.column), 2) + pow(Double(index.row - centerIndex.row), 2)) minedMounds.append((mound, distance)) } } var numberOfRemained = minedMounds.count let animationSignature = Date().timeIntervalSince1970 self.animationSignature = animationSignature for (mound, distance) in minedMounds { let delay = 0.01 + distance * animationSeparatingDuration + (distance != 0 && delaysAfterFirstSubanimation ? delayAfterFirstSubanimation : 0 ) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay) { guard animationSignature == self.animationSignature else {return} subanimationWillStart(mound, animationSignature) let animationView = AnimationView.init( center: NSPoint(x: mound.frame.midX, y: mound.frame.midY), moundFrameSize: mound.frame.size ) animationWindow.contentView!.addSubview(animationView) animationView.startAnimation { animationView.removeFromSuperview() numberOfRemained -= 1 if numberOfRemained == 0, animationWindow.isVisible { self.closeAnimationWindow(animationWindow) } } } } window!.addChildWindow(animationWindow, ordered: .above) } func radiate(from centerMound: Mound, then callback: @escaping () -> Void) { beginAnimationWindow( from: centerMound, animationViewType: ShineView.self, subanimationWillStart: {mound, _ in mound.showMine(animates: true, flashes: true) }, delaysAfterFirstSubanimation: false, then: callback ) } func explode(from centerMound: Mound, then callback: @escaping () -> Void) { let delay = Double(BoomView.indexOfMaxContentFrame) * BoomView.frameDuration beginAnimationWindow( from: centerMound, animationViewType: BoomView.self, subanimationWillStart: {mound, animationSignature in DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + (mound == centerMound ? 0 : delay)) { if animationSignature == self.animationSignature { mound.showMine(animates: false) } } }, delaysAfterFirstSubanimation: true, then: callback ) } func disturb(from centerMound: Mound, then callback: @escaping () -> Void) { let delay = Double(SpinView.indexOfMaxContentFrame) * SpinView.frameDuration beginAnimationWindow( from: centerMound, animationViewType: SpinView.self, subanimationWillStart: {mound, animationSignature in DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay) { if animationSignature == self.animationSignature { mound.showMine(animates: true, duration: 0.25) } } }, delaysAfterFirstSubanimation: true, then: callback ) } @discardableResult func stopAllAnimationsIfNeeded() -> Bool { if let childWindows = window?.childWindows, childWindows.count > 0 { childWindows.forEach {window in if window is AnimationWindow { closeAnimationWindow(window as! AnimationWindow) } } return true } else { return false } } func closeAnimationWindow(_ animationWindow: AnimationWindow) { animationSignature = Date().timeIntervalSince1970 moundMatrix.forEach {mound in if mound.hasMine {mound.showMine(animates: false)} } animationWindow.orderOut(nil) window!.removeChildWindow(animationWindow) } override func mouseDown(with event: NSEvent) { stopAllAnimationsIfNeeded() } } extension Minefield: MoundMatrixDelegate { func moundMatrix(_ moundMatrix: MoundMatrix, moundAt index: MoundMatrix.Index) -> Mound { let mound = Mound() mound.wantsLayer = wantsLayer mound.delegate = moundDelegate self.moundMatrix(moundMatrix, update: mound, at: index) addSubview(mound) return mound } func moundMatrix(_ moundMatrix: MoundMatrix, update mound: Mound, at index: MoundMatrix.Index) { mound.luminosity = CGFloat(index.row) / CGFloat(numberOfRows - 1) * 2 - 1 mound.edgingMask = Mound.EdgingMask(rawValue: (index.row == numberOfRows - 1 ? Mound.EdgingMask.top.rawValue : 0) | (index.column == 0 ? Mound.EdgingMask.left.rawValue : 0) | (index.row == 0 ? Mound.EdgingMask.bottom.rawValue : 0) | (index.column == numberOfColumns - 1 ? Mound.EdgingMask.right.rawValue : 0) ) mound.frame = NSRect( x: CGFloat(index.column) * moundSize + contentInsets.left, y: CGFloat(index.row) * moundSize + contentInsets.bottom, width: moundSize, height: moundSize ) } func moundMatrix(_ moundMatrix: MoundMatrix, didRemove mound: Mound) { mound.removeFromSuperview() } } extension Minefield: CAAnimationDelegate { func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { subviews.forEach {$0.isHidden = false} layer!.contents = nil } } extension Minefield: NSWindowDelegate { func setWindowRatio() { window!.contentAspectRatio = NSSize(width: numberOfColumns, height: numberOfRows) } func setWindowBackground() { if fieldStyle == .sheet, let visualEffectView = window!.contentView!.superview!.subviews[0] as? NSVisualEffectView { visualEffectView.blendingMode = .behindWindow visualEffectView.material = .sidebar visualEffectView.state = .followsWindowActiveState } } func windowWillAppear(_ window: NSWindow) { let newFrameSize = window.frameRect(forContentRect: NSRect(origin: window.frame.origin, size: fittingSize())).size window.setFrame(NSRect(origin: NSPoint(x: window.frame.minX + (window.frame.width - newFrameSize.width) / 2, y: window.frame.minY + (window.frame.height - newFrameSize.height)), size: newFrameSize), display: false) setWindowBackground() setWindowRatio() if fieldStyle == .sheet { layer!.mask = CALayer() if #available(OSX 10.16, *) { layer!.mask!.cornerRadius = 8.5 layer!.mask!.cornerCurve = .continuous } else { layer!.mask!.cornerRadius = 4 } layer!.mask!.backgroundColor = .black layer!.mask!.autoresizingMask = [.layerWidthSizable, .layerHeightSizable] layer!.mask!.frame = layer!.bounds.insetBy(NSEdgeInsets(top: -layer!.mask!.cornerRadius, left: contentInsets.left + 1, bottom: contentInsets.bottom + 1, right: contentInsets.right + 1)) } } func windowWillUseStandardFrame(_ window: NSWindow, defaultFrame newFrame: NSRect) -> NSRect { let fittingSize = self.fittingSize(moundSize: standardMoundSize) let contentRect = window.contentRect(forFrameRect: NSRect(x: 0, y: 0, width: fittingSize.width, height: -fittingSize.height)) return NSRect(x: window.frame.minX, y: window.frame.maxY, width: contentRect.width, height: -contentRect.height).standardized } func windowWillResize(_ window: NSWindow, to frameSize: NSSize) -> NSSize { guard !isAnimatingResizing else {return frameSize} let contentRect = window.contentRect(forFrameRect: NSRect(origin: .zero, size: frameSize)) let moundSize = min(maxMoundSize, max(minMoundSize, self.moundSize(frame: contentRect))) return window.frameRect(forContentRect: NSRect(origin: .zero, size: fittingSize(moundSize: moundSize))).size } func windowDidResize(_: Notification) { guard !isAnimatingResizing else {return} moundSize = moundSize(rounds: false) layoutMounds() stopAllAnimationsIfNeeded() } func windowDidEndLiveResize(_: Notification) { delegate?.minefieldWindowDidResize(self) } func windowWillClose(_: Notification) { stopAllAnimationsIfNeeded() } func windowShouldClose(_: NSWindow) -> Bool { delegate?.minefieldWindowShouldClose(self) ?? true } }
37.675
134
0.588485
f5a2d85c93d424824b88b3fac8e61c2b9ffdfe5e
1,544
// // DanceInstructionParser.swift // Advent // // Created by Nicky Advokaat on 16/12/2017. // Copyright © 2017 Nicky Advokaat. All rights reserved. // import Foundation class DanceParser { class func parseDance(instructions: String) -> Dance { var danceInstructions: [DanceInstruction] = [] let split = instructions.split(separator: ",").map(String.init) for instruction in split { if let danceInstruction = parseInstruction(instruction: instruction) { danceInstructions.append(danceInstruction) } } return Dance(danceInstructions: danceInstructions) } private class func parseInstruction(instruction: String) -> DanceInstruction? { let instructionType = instruction[0] let instructionValue = instruction.suffix(instruction.count - 1) switch instructionType { case "s": return SpinDanceInstruction(size: Int(instructionValue)!) case "x": let splitValue = instructionValue.split(separator: "/") let first = Int(splitValue[0])! let second = Int(splitValue[1])! return ExchangeDanceInstruction(positionA: first, positionB: second) case "p": let splitValue = instructionValue.split(separator: "/").map(String.init) let first = splitValue[0] let second = splitValue[1] return PartnerDanceInstruction(partnerA: first, partnerB: second) default: return nil } } }
35.090909
84
0.632124
1a63bd113b30b3540bce247a3451df4049d2ed88
2,696
// // Tweak.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // 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 CoreData // MARK: - Tweak /** The `Tweak` clause allows fine-tuning the `NSFetchRequest` for a fetch or query. Sample usage: ``` let employees = transaction.fetchAll( From<MyPersonEntity>(), Tweak { (fetchRequest) -> Void in fetchRequest.includesPendingChanges = false fetchRequest.fetchLimit = 5 } ) ``` */ public struct Tweak: FetchClause, QueryClause, DeleteClause { /** The block to customize the `NSFetchRequest` */ public let closure: (_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> Void /** Initializes a `Tweak` clause with a closure where the `NSFetchRequest` may be configured. - Important: `Tweak`'s closure is executed only just before the fetch occurs, so make sure that any values captured by the closure is not prone to race conditions. Also, some utilities (such as `ListMonitor`s) may keep `FetchClause`s in memory and may thus introduce retain cycles if reference captures are not handled properly. - parameter closure: the block to customize the `NSFetchRequest` */ public init(_ closure: @escaping (_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> Void) { self.closure = closure } // MARK: FetchClause, QueryClause, DeleteClause public func applyToFetchRequest<ResultType>(_ fetchRequest: NSFetchRequest<ResultType>) { self.closure(fetchRequest as! NSFetchRequest<NSFetchRequestResult>) } }
37.971831
333
0.716246
f8f521c9d342f439299a5f7f8509d38e3f632857
8,559
// 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: return [[RESULT]] : $Float // CHECK: } // end sil function 'applyTranspose_f_direct_arity1' @_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: [[RESULT:%.*]] = tuple ([[RES1]] : $Float, [[RES2]] : $Float) // CHECK: return [[RESULT]] : $(Float, Float) // CHECK: } // end sil function 'applyTranspose_f_direct_arity2' @_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
55.219355
240
0.68057
6442fe66880afa48917a5892fb976c46d0dca428
378
// Created by adong666666 on 2018/8/24. Copyright © 2018年 adong666666. All rights reserved. import UIKit class cover_city : NSObject { @objc var city_name: String = "" @objc var city_no: String = "" init(dict : [String : Any]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) {} }
29.076923
93
0.650794
3a51d8c93ac4e55f4f747ceb59292ac6c67431bd
2,147
// // NVActivityIndicatorAnimationBallScaleRippleMultiple.swift // NVActivityIndicatorViewDemo // // Created by Nguyen Vinh on 7/24/15. // Copyright (c) 2015 Nguyen Vinh. All rights reserved. // import Cocoa class NVActivityIndicatorAnimationBallScaleRippleMultiple: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) { let duration: CFTimeInterval = 1.25 let beginTime = CACurrentMediaTime() let beginTimes = [0.0, 0.2, 0.4] let timingFunction = CAMediaTimingFunction(controlPoints: 0.21, 0.53, 0.56, 0.8) // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.7] scaleAnimation.timingFunction = timingFunction scaleAnimation.values = [0, 1.0] scaleAnimation.duration = duration // Opacity animation let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.keyTimes = [0, 0.7, 1] opacityAnimation.timingFunctions = [timingFunction, timingFunction] opacityAnimation.values = [1, 0.7, 0] opacityAnimation.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, opacityAnimation] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circles for i in 0 ..< 3 { let circle = NVActivityIndicatorShape.ring.layerWith(size: size, color: color) let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2, y: (layer.bounds.size.height - size.height) / 2, width: size.width, height: size.height) animation.beginTime = beginTime + beginTimes[i] circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } }
37.017241
97
0.614811
fbdb195acf5e6e243ce9ce470ec95097463c7104
559
import XcodeServer import ProcedureKit @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) @available(swift, introduced: 5.1) public class SyncBotStatsProcedure: GroupProcedure { public init(source: BotQueryable, destination: BotPersistable, bot: Bot) { super.init(operations: []) let get = GetBotStatsProcedure(source: source, input: bot.id) let update = UpdateBotStatsProcedure(destination: destination, bot: bot) update.injectResult(from: get) addChildren([get, update]) } }
31.055556
80
0.676208
e924fb9532eb3e444d475650885a6b8d7e8ba3d3
5,797
// // RSCollectionViewCell.swift // Pods // // Created by James Kizer on 5/17/18. // import UIKit import SnapKit import Gloss open class RSCollectionViewCellConfiguration: NSObject { override public init() { super.init() } // public required init?(json: JSON) { // // } // // public func toJSON() -> JSON? { // return [:] // } } open class RSCollectionViewCell: UICollectionViewCell, CAAnimationDelegate { open var widthConstraint: NSLayoutConstraint! open var heightConstraint: NSLayoutConstraint! open var onTap: ((RSCollectionViewCell)->())? open var activeBorderColor: UIColor? open var inactiveBorderColor: UIColor? public static func spacingView(axis: NSLayoutConstraint.Axis) -> UIView { let view = UIView() view.snp.makeConstraints { (make) in if axis == .vertical { make.height.equalTo(0) } else { make.width.equalTo(0) } } return view } public static func lineView(axis: NSLayoutConstraint.Axis, color: UIColor) -> UIView { let view = UIView() view.snp.makeConstraints { (make) in if axis == .vertical { make.height.equalTo(1) } else { make.width.equalTo(1) } } view.backgroundColor = color return view } open func setCellWidth(width: CGFloat) { self.widthConstraint.constant = width self.widthConstraint.isActive = true self.heightConstraint.isActive = false } open func setCellHeight(height: CGFloat) { self.heightConstraint.constant = height self.heightConstraint.isActive = true self.widthConstraint.isActive = false } override public init(frame: CGRect) { super.init(frame: frame) self.contentView.translatesAutoresizingMaskIntoConstraints = true self.widthConstraint = self.contentView.widthAnchor.constraint(equalToConstant: 0.0) self.heightConstraint = self.contentView.heightAnchor.constraint(equalToConstant: 0.0) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(cellTapped)) self.addGestureRecognizer(tapGestureRecognizer) } open override func prepareForReuse() { self.onTap = nil self.activeBorderColor = nil self.inactiveBorderColor = nil super.prepareForReuse() } open override var isHighlighted: Bool { get { return super.isHighlighted } set(newIsHighlighted) { if self.onTap != nil { super.isHighlighted = newIsHighlighted self.updateShadow(shadow: !newIsHighlighted, animated: false) } } } @objc public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { let shadowOpacity: Float = self.isHighlighted ? 0.0 : 0.3 self.layer.shadowOpacity = shadowOpacity } func updateShadow(shadow: Bool, animated: Bool) { let opacity: Float = shadow ? 0.3 : 0.0 // self.layer.shadowColor = UIColor.black.cgColor let shadowColor: CGColor = { let active = (self.onTap == nil) if active { if let color = self.activeBorderColor { return color.cgColor } else { return self.tintColor.cgColor } } else { if let color = self.inactiveBorderColor { return color.cgColor } else { return UIColor.black.cgColor } } }() self.layer.shadowColor = shadowColor self.layer.shadowOffset = CGSize(width: 0.0, height: 2.0) self.layer.shadowRadius = 3.0 if animated { let animation = CABasicAnimation(keyPath: "shadowOpacity") animation.duration = 0.025 animation.fromValue = self.layer.shadowOpacity animation.toValue = opacity animation.delegate = self self.layer.add(animation, forKey: "shadowOpacity") } else { self.layer.shadowOpacity = opacity } } open override func layoutSubviews() { super.layoutSubviews() self.updateShadow(shadow: !self.isHighlighted, animated: false) } open func configure(paramMap: [String : Any]){ } //fancy method signature to support variance //see RSCardCollectionViewCell##configure(config: T) for usage //the gist is that we can still support inheritance while specializing the //parameter type as we go up the chain open func configure(config: RSCollectionViewCellConfiguration) { } @objc open func cellTapped(sender: UITapGestureRecognizer) { self.onTap?(self) } open func setCellTint(color: UIColor) { self.tintColor = color } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { let height = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height layoutAttributes.bounds.size.height = height return layoutAttributes } }
28.004831
147
0.578748
c1b7c19faa660aa95ac424b3ecc653c76dad4475
421
// // Authentication.swift // NetworkManager // // Created by yasinkbas on 2.07.2020. // Copyright © 2020 Yasin Akbaş. All rights reserved. // import Foundation public protocol NLAuthentication {} public protocol NLBaiscAuthenticationModel: NLAuthentication { static var key: String { get set } } public protocol NLAccessTokenAuthentication: NLAuthentication { static var accessKey: String { get set } }
20.047619
63
0.743468
fc771cc3122a79b9ceb90d5ff97a52420d14f12d
7,296
// // ZLImageEditorConfiguration.swift // ZLImageEditor // // Created by long on 2020/11/23. // // Created by long on 2020/8/17. // // Copyright (c) 2020 Long Zhang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public class ZLImageEditorConfiguration: NSObject { private static let single = ZLImageEditorConfiguration() @objc public class func `default`() -> ZLImageEditorConfiguration { return ZLImageEditorConfiguration.single } /// Language for framework. @objc public var languageType: ZLImageEditorLanguageType = .system { didSet { Bundle.resetLanguage() } } private var pri_editImageTools: [ZLImageEditorConfiguration.EditImageTool] = [.draw, .clip, .imageSticker, .textSticker, .mosaic, .filter] /// Edit image tools. (Default order is draw, clip, imageSticker, textSticker, mosaic, filtter) /// Because Objective-C Array can't contain Enum styles, so this property is not available in Objective-C. /// - warning: If you want to use the image sticker feature, you must provide a view that implements ZLImageStickerContainerDelegate. public var editImageTools: [ZLImageEditorConfiguration.EditImageTool] { set { pri_editImageTools = newValue } get { if pri_editImageTools.isEmpty { return [.draw, .clip, .imageSticker, .textSticker, .mosaic, .filter] } else { return pri_editImageTools } } } public var strikerIconImage:UIImage?=nil private var pri_editImageDrawColors: [UIColor] = [.white, .black, zlRGB(241, 79, 79), zlRGB(243, 170, 78), zlRGB(80, 169, 56), zlRGB(30, 183, 243), zlRGB(139, 105, 234)] /// Draw colors for image editor. @objc public var editImageDrawColors: [UIColor] { set { pri_editImageDrawColors = newValue } get { if pri_editImageDrawColors.isEmpty { return [.white, .black, zlRGB(241, 79, 79), zlRGB(243, 170, 78), zlRGB(80, 169, 56), zlRGB(30, 183, 243), zlRGB(139, 105, 234)] } else { return pri_editImageDrawColors } } } /// The default draw color. If this color not in editImageDrawColors, will pick the first color in editImageDrawColors as the default. @objc public var editImageDefaultDrawColor = zlRGB(241, 79, 79) private var pri_editImageClipRatios: [ZLImageClipRatio] = [.custom] /// Edit ratios for image editor. @objc public var editImageClipRatios: [ZLImageClipRatio] { set { pri_editImageClipRatios = newValue } get { if pri_editImageClipRatios.isEmpty { return [.custom] } else { return pri_editImageClipRatios } } } private var pri_textStickerTextColors: [UIColor] = [.white, .black, zlRGB(241, 79, 79), zlRGB(243, 170, 78), zlRGB(80, 169, 56), zlRGB(30, 183, 243), zlRGB(139, 105, 234)] /// Text sticker colors for image editor. @objc public var textStickerTextColors: [UIColor] { set { pri_textStickerTextColors = newValue } get { if pri_textStickerTextColors.isEmpty { return [.white, .black, zlRGB(241, 79, 79), zlRGB(243, 170, 78), zlRGB(80, 169, 56), zlRGB(30, 183, 243), zlRGB(139, 105, 234)] } else { return pri_textStickerTextColors } } } /// The default text sticker color. If this color not in textStickerTextColors, will pick the first color in textStickerTextColors as the default. @objc public var textStickerDefaultTextColor = UIColor.white private var pri_filters: [ZLFilter] = ZLFilter.all /// Filters for image editor. @objc public var filters: [ZLFilter] { set { pri_filters = newValue } get { if pri_filters.isEmpty { return ZLFilter.all } else { return pri_filters } } } @objc public var imageStickerContainerView: (UIView & ZLImageStickerContainerDelegate)? = nil /// If image edit tools only has clip and this property is true. When you click edit, the cropping interface (i.e. ZLClipImageViewController) will be displayed. Default is false @objc public var showClipDirectlyIfOnlyHasClipTool = false /// The background color of edit done button. @objc public var editDoneBtnBgColor: UIColor = zlRGB(80, 169, 56) } extension ZLImageEditorConfiguration { @objc public enum EditImageTool: Int { case draw case clip case imageSticker case textSticker case mosaic case filter } } // MARK: Clip ratio. public class ZLImageClipRatio: NSObject { let title: String let whRatio: CGFloat @objc public init(title: String, whRatio: CGFloat) { self.title = title self.whRatio = whRatio } } func ==(lhs: ZLImageClipRatio, rhs: ZLImageClipRatio) -> Bool { return lhs.whRatio == rhs.whRatio } extension ZLImageClipRatio { @objc public static let custom = ZLImageClipRatio(title: "custom", whRatio: 0) @objc public static let wh1x1 = ZLImageClipRatio(title: "1 : 1", whRatio: 1) @objc public static let wh3x4 = ZLImageClipRatio(title: "3 : 4", whRatio: 3.0/4.0) @objc public static let wh4x3 = ZLImageClipRatio(title: "4 : 3", whRatio: 4.0/3.0) @objc public static let wh2x3 = ZLImageClipRatio(title: "2 : 3", whRatio: 2.0/3.0) @objc public static let wh3x2 = ZLImageClipRatio(title: "3 : 2", whRatio: 3.0/2.0) @objc public static let wh9x16 = ZLImageClipRatio(title: "9 : 16", whRatio: 9.0/16.0) @objc public static let wh16x9 = ZLImageClipRatio(title: "16 : 9", whRatio: 16.0/9.0) } @objc public protocol ZLImageStickerContainerDelegate where Self: UIView { @objc var selectImageBlock: ( (UIImage) -> Void )? { get set } @objc var hideBlock: ( () -> Void )? { get set } @objc func show(in view: UIView) }
35.590244
181
0.641996
21232b26635474f4adb7c770cedfd428468461d2
2,161
// // Authorization.swift // QuadratTouch // // Created by Constantine Fry on 08/11/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation import UIKit /** The delegate of authorization view controller. */ @objc public protocol SessionAuthorizationDelegate: class { /** It can be useful if one needs 1password integration. */ optional func sessionWillPresentAuthorizationViewController(controller: AuthorizationViewController) optional func sessionWillDismissAuthorizationViewController(controller: AuthorizationViewController) } extension Session { public func canUseNativeOAuth() -> Bool { let baseURL = self.configuration.server.nativeOauthBaseURL let URL = NSURL(string: baseURL) as NSURL! return UIApplication.sharedApplication().canOpenURL(URL) } public func handleURL(URL: NSURL) -> Bool { if let nativeAuthorizer = self.authorizer as? NativeTouchAuthorizer { return nativeAuthorizer.handleURL(URL) as Bool! } let nativeAuthorizer = NativeTouchAuthorizer(configuration: self.configuration) return nativeAuthorizer.handleURL(URL) as Bool! } public func authorizeWithViewController(viewController: UIViewController, delegate: SessionAuthorizationDelegate?, completionHandler: AuthorizationHandler) { if (self.authorizer == nil) { let block = { (accessToken: String?, error: NSError?) -> Void in self.authorizer = nil completionHandler(accessToken != nil, error) } if (self.canUseNativeOAuth()) { let nativeAuthorizer = NativeTouchAuthorizer(configuration: self.configuration) nativeAuthorizer.authorize(block) self.authorizer = nativeAuthorizer } else { let touchAuthorizer = TouchAuthorizer(configuration: self.configuration) touchAuthorizer.authorize(viewController, delegate: delegate, completionHandler: block) self.authorizer = touchAuthorizer } } } }
37.258621
161
0.671911
03f817d8dda6039ba0f5d24a48e7cd3b498fb091
433
// // Shot.swift // DribbbleTest // // Created by dede.exe on 24/01/17. // Copyright © 2017 dede.exe. All rights reserved. // import Foundation public class Shot { public var id : Int? public var title : String? public var author : String? public var viewsCount : Int? public var shotImage : String? public var authorImage : String? public var description : String? }
19.681818
51
0.614319
56cfc894d39518530f281b234c5f08d631f4dc43
5,083
// // MessageViewLayout.swift // Tinodios // // Copyright © 2019 Tinode. All rights reserved. // import UIKit protocol MessageViewLayoutDelegate: class { func collectionView(_ collectionView: UICollectionView, fillAttributes: MessageViewLayoutAttributes) } class MessageViewLayout: UICollectionViewLayout { // MARK: private vars weak var delegate: MessageViewLayoutDelegate! fileprivate var contentHeight: CGFloat = 0 fileprivate var attributeCache: [MessageViewLayoutAttributes] = [] fileprivate var contentWidth: CGFloat { guard let collectionView = collectionView else { return 0 } let insets = collectionView.contentInset return collectionView.bounds.width - (insets.left + insets.right) } // MARK: overriden methods override class var layoutAttributesClass: AnyClass { return MessageViewLayoutAttributes.self } override var collectionViewContentSize: CGSize { return CGSize(width: contentWidth, height: contentHeight) } override func prepare() { guard let collectionView = collectionView else { return } let itemCount = collectionView.numberOfItems(inSection: 0) if attributeCache.count == itemCount { // Item count did not change. Skip update return } // Calculate and cache cell attributes. attributeCache.removeAll(keepingCapacity: true) var yOffset: CGFloat = 0 //collectionView.layoutMargins.top let leftMargin = collectionView.layoutMargins.left for item in 0 ..< itemCount { let indexPath = IndexPath(item: item, section: 0) let attr = MessageViewLayoutAttributes(forCellWith: indexPath) delegate.collectionView(collectionView, fillAttributes: attr) // Adjust frame origin: add margin and shift down. attr.frame.origin.y += yOffset attr.frame.origin.x += leftMargin attributeCache.append(attr) yOffset = attr.frame.maxY + attr.cellSpacing contentHeight = attr.frame.maxY } } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var visibleAttributes = [UICollectionViewLayoutAttributes]() // Loop through the cache and look for items in the rect for attr in attributeCache { if attr.frame.intersects(rect) { visibleAttributes.append(attr) } } return visibleAttributes } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return attributeCache[indexPath.item] } override func invalidateLayout() { super.invalidateLayout() attributeCache.removeAll(keepingCapacity: true) } // MARK: helper methods } class MessageViewLayoutAttributes: UICollectionViewLayoutAttributes { // Avatar position and size var avatarFrame: CGRect = .zero // Sender name label position and size var senderNameFrame: CGRect = .zero // Message bubble position and size var containerFrame: CGRect = .zero // Message content inside the bubble. var contentFrame: CGRect = .zero // Delivery marker. var deliveryMarkerFrame: CGRect = .zero // Timestamp. var timestampFrame: CGRect = .zero // Optional new date label above message bubble var newDateFrame: CGRect = .zero // Vertical spacing between cells var cellSpacing: CGFloat = 0 // Progress bar. var progressBarFrame: CGRect = .zero // Cancel upload button. var cancelUploadButtonFrame: CGRect = .zero override func copy(with zone: NSZone? = nil) -> Any { let copy = super.copy(with: zone) as! MessageViewLayoutAttributes copy.avatarFrame = avatarFrame copy.senderNameFrame = senderNameFrame copy.containerFrame = containerFrame copy.contentFrame = contentFrame copy.deliveryMarkerFrame = deliveryMarkerFrame copy.timestampFrame = timestampFrame copy.newDateFrame = newDateFrame copy.cellSpacing = cellSpacing copy.progressBarFrame = progressBarFrame copy.cancelUploadButtonFrame = cancelUploadButtonFrame return copy } override func isEqual(_ object: Any?) -> Bool { guard let other = object as? MessageViewLayoutAttributes else { return false } return super.isEqual(object) && other.avatarFrame == avatarFrame && other.senderNameFrame == senderNameFrame && other.containerFrame == containerFrame && other.contentFrame == contentFrame && other.deliveryMarkerFrame == deliveryMarkerFrame && other.timestampFrame == timestampFrame && other.newDateFrame == newDateFrame && other.cellSpacing == cellSpacing && other.progressBarFrame == progressBarFrame && other.cancelUploadButtonFrame == cancelUploadButtonFrame } }
32.375796
105
0.668896
4b131310201b45ec6a28d82d4d4ad87e8712e585
398
// // Player.swift // Swift Radio // // Created by Matthew Fecher on 7/13/15. // Copyright (c) 2015 MatthewFecher.com. All rights reserved. // import MediaPlayer //***************************************************************** // This is a singleton struct using Swift //***************************************************************** struct Player { static let radio = RadioKit() }
23.411765
67
0.452261
3a673d2b4153660b6aba13141f14f5aea0d4024c
346
// // DetailImageInteractor.swift // AloBasta // // Created by Agus Cahyono on 17/10/19. // Copyright © 2019 Agus Cahyono. All rights reserved. // import UIKit class DetailImageInteractor { // TODO: Declare view methods weak var output: DetailImageInteractorOutput! } extension DetailImageInteractor: DetailImageUseCase { }
18.210526
55
0.722543
f401341bb5b0b3b1ed35203be6b32221a6ebbcd2
2,221
// // LaunchInfo.swift // SpaceXClient // // Created by Alin Gorgan on 6/3/21. // import Foundation struct LaunchInfo: Equatable { let mission: MissonInfo let rocketInfo: RocketInfo? } extension Array where Element == LaunchInfo { init(dataModels: [LaunchInfoDataModel]) { self = dataModels.map { .init(dataModel: $0) } } } extension LaunchInfo { init(dataModel: LaunchInfoDataModel, rocketInfoDataModel: RocketInfoDataModel? = nil) { var dateFormatted = "" var timeFormatted = "" var etdFormatted = "" let dateInputFormatter = DateFormatter() dateInputFormatter.locale = .current dateInputFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" if let inputDate = dateInputFormatter.date(from: dataModel.fireDateTime) { let dateFormatter = DateFormatter() dateFormatter.locale = .current dateFormatter.dateFormat = "YYYY-MM-dd" dateFormatted = dateFormatter.string(from: inputDate) let timeForFormatter = DateFormatter() dateFormatter.locale = .current dateFormatter.dateFormat = "HH:mm:ss" timeFormatted = timeForFormatter.string(from: inputDate) let diffComponents = Calendar.current.dateComponents([.day], from: .init(), to: inputDate) if let days = diffComponents.day { etdFormatted = "\(days)" } } let rocketInfo: RocketInfo if let rocketInfoDataModel = rocketInfoDataModel { rocketInfo = RocketInfo(dataModel: rocketInfoDataModel) } else { rocketInfo = RocketInfo(id: dataModel.rocketId, name: nil, type: nil) } self.init(mission: .init(name: dataModel.name, imageUrl: dataModel.imageURL, dateFormatted: dateFormatted, timeFormatted: timeFormatted, etdFormatted: etdFormatted, isSuccessfullLaunch: dataModel.isSuccessfullLaunch), rocketInfo: rocketInfo) } }
34.703125
102
0.585322
de5a9ea7c375efb5cf2786a7d370d8d5bb41c3be
1,041
// // MainCoordinator.swift // ios-recruiting-hsa // // Created by Hans Fehrmann on 5/27/19. // Copyright © 2019 Hans Fehrmann. All rights reserved. // import UIKit class MainCoordinator: Coordinator { private let window: UIWindow private var articleCoordinator: ArticleCoordinator! private lazy var appDependecies = buildDependencies() init(window: UIWindow) { self.window = window } func start() { let navigation = UINavigationController() articleCoordinator = ArticleCoordinator( navigationController: navigation, appDependencies: appDependecies ) articleCoordinator.start() window.rootViewController = navigation window.makeKeyAndVisible() } } private extension MainCoordinator { func buildDependencies() -> AppDependencies { let dependencies = AppDependencies( articleManager: articleManagerDefault() ) dependencies.articleManager.load() return dependencies } }
23.133333
57
0.668588
edda0cd232e74543762a1a53dd0f6404d2230a74
975
// // Copyright © 2021 Jesús Alfredo Hernández Alarcón. All rights reserved. // import Foundation public struct Story: Equatable { public let id: Int public let title: String? public let text: String? public let author: String public let score: Int? public let createdAt: Date public let totalComments: Int? public let comments: [Int]? public let type: String public let url: URL? public init( id: Int, title: String?, text: String?, author: String, score: Int?, createdAt: Date, totalComments: Int?, comments: [Int]?, type: String, url: URL? ) { self.id = id self.title = title self.text = text self.author = author self.score = score self.createdAt = createdAt self.totalComments = totalComments self.comments = comments self.type = type self.url = url } }
22.674419
74
0.57641
abe7cd402c6da44eba24ed2f398658701adf29c4
2,000
// // UIButton+Extension.swift // Swift_Sudoku_Solver // // Created by NowOrNever on 14/04/2017. // Copyright © 2017 Focus. All rights reserved. // import UIKit extension UIButton{ class func ll_button(backGroundImageName: String, title: String, target: Any?, action: Selector, layerCornerRadius: CGFloat) -> UIButton { return ll_button_full_parameters(title: title, target: target, action: action, color: nil, layerCornerRadius: layerCornerRadius, backGroundImageName: backGroundImageName) } class func ll_button(title: String, target: Any?, action: Selector) -> UIButton { return ll_button_full_parameters(title: title, target: target, action: action, color: nil, layerCornerRadius: nil, backGroundImageName: nil) } class func ll_button(title: String, target: Any?, action: Selector, color: UIColor) -> UIButton { return ll_button_full_parameters(title: title, target: target, action: action, color: color, layerCornerRadius: nil, backGroundImageName: nil) } class func ll_button_full_parameters(title: String?, target: Any?, action: Selector, color: UIColor?, layerCornerRadius: CGFloat?, backGroundImageName:String?) -> UIButton { let button = UIButton.init() button.setTitle(title, for: .normal) button.setTitleColor(color, for: .normal) button.addTarget(target, action: action, for: .touchUpInside) if layerCornerRadius != nil { button.layer.cornerRadius = layerCornerRadius! button.layer.masksToBounds = true } if backGroundImageName != nil { button.setBackgroundImage(UIImage.init(named: backGroundImageName!), for: .normal) } button.sizeToFit() return button } } extension UIButton{ convenience init(title:String,target:Any?,action:Selector){ self.init() setTitle(title, for: .normal) addTarget(target, action:action, for: .touchUpInside) sizeToFit() } }
39.215686
178
0.688
7134e0349535865aa9cda7422faf1e306997a272
5,568
// // FinalLayout-Main.swift // Trivia // // Created by Can Özcan on 28.10.2019. // Copyright © 2019 CanOzcan. All rights reserved. // import UIKit extension Main { public class FinalLayout: TRLayout { private var tv_header: TRTextView! private var tv_money: TRTextView! public var lv: RoomUserList! // public var btn_start: TRButton! /* - - // MARK: Construction - - */ public override func onConstruct() { super.onConstruct() self.applyBackgroundGradient(colors: [ colorProvider.getNormalBlue().cgColor, colorProvider.getNormalBlue().cgColor, colorProvider.getLightBlue().cgColor, colorProvider.getWhiteFull().cgColor ], rect: self.bounds,isHorizontal: false) constructListView() constructHeaderTextView() constructMoneyTextView() // constructStartButton() } private func constructListView() { lv = RoomUserList(items: []) self.addSubview(lv) } private func constructHeaderTextView() { tv_header = TRTextView() tv_header.text = "Winners get:" tv_header.textAlignment = .center tv_header.font = fontProvider.getSemiboldBiggest() tv_header.textColor = colorProvider.getWhiteFull() self.addSubview(tv_header) } private func constructMoneyTextView() { tv_money = TRTextView() tv_money.text = "$ 15.00" tv_money.textAlignment = .center tv_money.font = fontProvider.getSemiboldBiggest() tv_money.textColor = colorProvider.getWhiteFull() self.addSubview(tv_money) } // private func constructStartButton() { // // btn_start = TRButton() // btn_start.setTitle("Start Trivia", for: .normal) // btn_start.backgroundColor = colorProvider.getLightBlue() // self.addSubview(btn_start) // // } /* - - // MARK: Constraining - - */ public override func onConstrain(set: inout [NSLayoutConstraint]) { super.onConstrain(set: &set) constrainListView(set: &set) constrainHeaderTextView(set: &set) constrainMoneyTextView(set: &set) // constrainStartButton(set: &set) } private func constrainListView(set: inout [NSLayoutConstraint]) { set.append(NSLayoutConstraint(item: lv, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)) set.append(NSLayoutConstraint(item: lv, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)) set.append(NSLayoutConstraint(item: lv, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -50)) set.append(NSLayoutConstraint(item: lv, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 250)) } private func constrainHeaderTextView(set: inout [NSLayoutConstraint]) { set.append(NSLayoutConstraint(item: tv_header, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)) set.append(NSLayoutConstraint(item: tv_header, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 40)) set.append(NSLayoutConstraint(item: tv_header, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -50)) set.append(NSLayoutConstraint(item: tv_header, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 50)) } private func constrainMoneyTextView(set: inout [NSLayoutConstraint]) { set.append(NSLayoutConstraint(item: tv_money, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)) set.append(NSLayoutConstraint(item: tv_money, attribute: .top, relatedBy: .equal, toItem: tv_header, attribute: .bottom, multiplier: 1, constant: 10)) set.append(NSLayoutConstraint(item: tv_money, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -50)) set.append(NSLayoutConstraint(item: tv_money, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 50)) } // private func constrainStartButton(set: inout [NSLayoutConstraint]) { // // set.append(NSLayoutConstraint(item: btn_start, attribute: .left, relatedBy: .equal, toItem: lv, attribute: .left, multiplier: 1, constant: 0)) // set.append(NSLayoutConstraint(item: btn_start, attribute: .top, relatedBy: .equal, toItem: lv, attribute: .bottom, multiplier: 1, constant: 20)) // set.append(NSLayoutConstraint(item: btn_start, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -50)) // set.append(NSLayoutConstraint(item: btn_start, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 50)) // // } } }
38.666667
170
0.622665
d6dd589d53329e8b50d3e325cb18eca568dbbb9e
4,289
// // EzsigndocumentRequestCompound.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation #if canImport(AnyCodable) import AnyCodable #endif /** An Ezsigndocument Object and children to create a complete structure */ public struct EzsigndocumentRequestCompound: Codable, Hashable { public enum EEzsigndocumentSource: String, Codable, CaseIterable { case base64 = "Base64" case url = "Url" } public enum EEzsigndocumentFormat: String, Codable, CaseIterable { case pdf = "Pdf" } /** Indicates where to look for the document binary content. */ public var eEzsigndocumentSource: EEzsigndocumentSource /** Indicates the format of the document. */ public var eEzsigndocumentFormat: EEzsigndocumentFormat /** The Base64 encoded binary content of the document. This field is Required when eEzsigndocumentSource = Base64. */ public var sEzsigndocumentBase64: Data? /** The url where the document content resides. This field is Required when eEzsigndocumentSource = Url. */ public var sEzsigndocumentUrl: String? /** Try to repair the document or flatten it if it cannot be used for electronic signature. */ public var bEzsigndocumentForcerepair: Bool? = true /** If the source document is password protected, the password to open/modify it. */ public var sEzsigndocumentPassword: String? = "" /** The unique ID of the Ezsignfolder */ public var fkiEzsignfolderID: Int /** The maximum date and time at which the document can be signed. */ public var dtEzsigndocumentDuedate: String /** The unique ID of the Language. Valid values: |Value|Description| |-|-| |1|French| |2|English| */ public var fkiLanguageID: Int /** The name of the document that will be presented to Ezsignfoldersignerassociations */ public var sEzsigndocumentName: String public init(eEzsigndocumentSource: EEzsigndocumentSource, eEzsigndocumentFormat: EEzsigndocumentFormat, sEzsigndocumentBase64: Data? = nil, sEzsigndocumentUrl: String? = nil, bEzsigndocumentForcerepair: Bool? = true, sEzsigndocumentPassword: String? = "", fkiEzsignfolderID: Int, dtEzsigndocumentDuedate: String, fkiLanguageID: Int, sEzsigndocumentName: String) { self.eEzsigndocumentSource = eEzsigndocumentSource self.eEzsigndocumentFormat = eEzsigndocumentFormat self.sEzsigndocumentBase64 = sEzsigndocumentBase64 self.sEzsigndocumentUrl = sEzsigndocumentUrl self.bEzsigndocumentForcerepair = bEzsigndocumentForcerepair self.sEzsigndocumentPassword = sEzsigndocumentPassword self.fkiEzsignfolderID = fkiEzsignfolderID self.dtEzsigndocumentDuedate = dtEzsigndocumentDuedate self.fkiLanguageID = fkiLanguageID self.sEzsigndocumentName = sEzsigndocumentName } public enum CodingKeys: String, CodingKey, CaseIterable { case eEzsigndocumentSource case eEzsigndocumentFormat case sEzsigndocumentBase64 case sEzsigndocumentUrl case bEzsigndocumentForcerepair case sEzsigndocumentPassword case fkiEzsignfolderID case dtEzsigndocumentDuedate case fkiLanguageID case sEzsigndocumentName } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(eEzsigndocumentSource, forKey: .eEzsigndocumentSource) try container.encode(eEzsigndocumentFormat, forKey: .eEzsigndocumentFormat) try container.encodeIfPresent(sEzsigndocumentBase64, forKey: .sEzsigndocumentBase64) try container.encodeIfPresent(sEzsigndocumentUrl, forKey: .sEzsigndocumentUrl) try container.encodeIfPresent(bEzsigndocumentForcerepair, forKey: .bEzsigndocumentForcerepair) try container.encodeIfPresent(sEzsigndocumentPassword, forKey: .sEzsigndocumentPassword) try container.encode(fkiEzsignfolderID, forKey: .fkiEzsignfolderID) try container.encode(dtEzsigndocumentDuedate, forKey: .dtEzsigndocumentDuedate) try container.encode(fkiLanguageID, forKey: .fkiLanguageID) try container.encode(sEzsigndocumentName, forKey: .sEzsigndocumentName) } }
49.298851
367
0.748659
288af1aa9373f56830d03657f391c87551965f78
1,494
// // Copyright © 2020 Anonyome Labs, Inc. All rights reserved. // // SPDX-License-Identifier: Apache-2.0 // import Foundation extension Dictionary where Value: AnyObject { /// Intializes a new `Dictionary` instance from an array /// of name/value pairs. /// /// - Parameter pairs: Array of name/value pairs. init(_ pairs: [Element]) { self.init() for (k, v) in pairs { self[k] = v } } /// Converts Dictionary to JSON data. /// /// - Returns: JSON data. func toJSONData() -> Data? { guard JSONSerialization.isValidJSONObject(self), let data = try? JSONSerialization.data(withJSONObject: self, options: []) else { return nil } return data } /// Converts Dictionary to pretty formatted JSON string. /// /// - Returns: Pretty formatted JSON string. func toJSONPrettyString() -> String? { guard JSONSerialization.isValidJSONObject(self), let data = try? JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) else { return nil } return String(data: data, encoding: String.Encoding.utf8) } /// Adds the content of another dictionary to this dictionary. /// /// - Parameter dictionary: Dictionary to add. mutating func addDictionary(_ dictionary: Dictionary) { dictionary.forEach { updateValue($1, forKey: $0) } } }
27.666667
104
0.595047
5bb83e61a8f6cae06be45ae73521628c6a7c5255
1,257
// // InstapodUITests.swift // InstapodUITests // // Created by Christopher Reitz on 18.02.16. // Copyright © 2016 Christopher Reitz. All rights reserved. // import XCTest class InstapodUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.972973
182
0.665871
d5447a3dfdbfa50a514b5a86e697c80f5975de5e
623
// // MovieCell.swift // Flicks // // Created by Sang Saephan on 1/12/17. // Copyright © 2017 Sang Saephan. All rights reserved. // import UIKit class MovieCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var overviewLabel: UILabel! @IBOutlet weak var posterImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
21.482759
65
0.670947
e080ee8939118300422f53df7511556de829dd84
5,503
/// Copyright (c) 2018 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. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import UIKit @IBDesignable public class Knob: UIControl { /** Contains the minimum value of the receiver. */ public var minimumValue: Float = 0 /** Contains the maximum value of the receiver. */ public var maximumValue: Float = 1 /** Contains the receiver’s current value. */ public private (set) var value: Float = 0 /** Sets the receiver’s current value, allowing you to animate the change visually. */ public func setValue(_ newValue: Float, animated: Bool = false) { value = min(maximumValue, max(minimumValue, newValue)) let angleRange = endAngle - startAngle let valueRange = maximumValue - minimumValue let angleValue = CGFloat(value - minimumValue) / CGFloat(valueRange) * angleRange + startAngle renderer.setPointerAngle(angleValue, animated: animated) } /** Contains a Boolean value indicating whether changes in the sliders value generate continuous update events. */ public var isContinuous = true private let renderer = KnobRenderer() /** Specifies the width in points of the knob control track. Defaults to 2 */ @IBInspectable public var lineWidth: CGFloat { get { return renderer.lineWidth } set { renderer.lineWidth = newValue } } /** Specifies the angle of the start of the knob control track. Defaults to -11π/8 */ public var startAngle: CGFloat { get { return renderer.startAngle } set { renderer.startAngle = newValue } } /** Specifies the end angle of the knob control track. Defaults to 3π/8 */ public var endAngle: CGFloat { get { return renderer.endAngle } set { renderer.endAngle = newValue } } /** Specifies the length in points of the pointer on the knob. Defaults to 6 */ @IBInspectable public var pointerLength: CGFloat { get { return renderer.pointerLength } set { renderer.pointerLength = newValue } } /** Specifies the color of the knob, including the pointer. Defaults to blue */ @IBInspectable public var color: UIColor { get { return renderer.color } set { renderer.color = newValue } } override public init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override public func tintColorDidChange() { renderer.color = tintColor } private func commonInit() { renderer.updateBounds(bounds) renderer.color = tintColor renderer.setPointerAngle(renderer.startAngle) layer.addSublayer(renderer.trackLayer) layer.addSublayer(renderer.pointerLayer) let gestureRecognizer = RotationGestureRecognizer(target: self, action: #selector(Knob.handleGesture(_:))) addGestureRecognizer(gestureRecognizer) } @objc private func handleGesture(_ gesture: RotationGestureRecognizer) { // 1 let midPointAngle = (2 * CGFloat(Double.pi) + startAngle - endAngle) / 2 + endAngle // 2 var boundedAngle = gesture.touchAngle if boundedAngle > midPointAngle { boundedAngle -= 2 * CGFloat(Double.pi) } else if boundedAngle < (midPointAngle - 2 * CGFloat(Double.pi)) { boundedAngle -= 2 * CGFloat(Double.pi) } // 3 boundedAngle = min(endAngle, max(startAngle, boundedAngle)) // 4 let angleRange = endAngle - startAngle let valueRange = maximumValue - minimumValue let angleValue = Float(boundedAngle - startAngle) / Float(angleRange) * valueRange + minimumValue // 5 setValue(angleValue) if isContinuous { sendActions(for: .valueChanged) } else { if gesture.state == .ended || gesture.state == .cancelled { sendActions(for: .valueChanged) } } } } extension Knob { public override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() renderer.updateBounds(bounds) } }
35.733766
110
0.713429
6175e34bf62f5b73ae197d47781e2d815eb53743
1,947
/** * (C) Copyright IBM Corp. 2018, 2019. * * 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 XCTest import RestKit @testable import DiscoveryV1 class DiscoveryUnitTests: XCTestCase { private var discovery: Discovery! private let timeout = 1.0 override func setUp() { discovery = Discovery(version: versionDate, accessToken: accessToken) #if !os(Linux) let configuration = URLSessionConfiguration.ephemeral #else let configuration = URLSessionConfiguration.default #endif configuration.protocolClasses = [MockURLProtocol.self] let mockSession = URLSession(configuration: configuration) discovery.session = mockSession } // MARK: - Inject Credentials #if os(Linux) func testInjectCredentialsFromFile() { setenv("IBM_CREDENTIALS_FILE", "Source/SupportingFiles/ibm-credentials.env", 1) let discovery = Discovery(version: versionDate) XCTAssertNotNil(discovery) XCTAssert(discovery?.authMethod is BasicAuthentication) } #endif } #if os(Linux) extension DiscoveryUnitTests { static var allTests: [(String, (DiscoveryUnitTests) -> () throws -> ())] { let tests: [(String, (DiscoveryUnitTests) -> () throws -> Void)] = [ // Inject Credentials ("testInjectCredentialsFromFile", testInjectCredentialsFromFile), ] return tests } } #endif
31.403226
87
0.689779
0ee57c164a6543202fd80d8e0f7e5160b810eb9c
470
// // UIViewController.swift // My University // // Created by Yura Voevodin on 13.05.2020. // Copyright © 2020 Yura Voevodin. All rights reserved. // import UIKit extension UIViewController { typealias SegueIdentifier = String func performSegue(withIdentifier: SegueIdentifier) { performSegue(withIdentifier: withIdentifier, sender: nil) } } // MARK: - StoryboardIdentifiable extension UIViewController: StoryboardIdentifiable { }
20.434783
65
0.721277
f50b6a6744e3e3f48391879028a65689a2f9b9e0
2,538
// // cloneTests.swift // OysterKit Mac // // Created by Nigel Hughes on 14/07/2014. // Copyright (c) 2014 RED When Excited Limited. All rights reserved. // import OysterKit import XCTest class cloneTests: XCTestCase { var ot = Tokenizer() var ct = Tokenizer() let aToken = Characters(from: "A").token("A") let bToken = Characters(from: "B").token("B") let testABString = "AABBBAABA" override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. ot = Tokenizer() ct = Tokenizer() } func tokenizersProduceSameOutput(startState:TokenizationState, testString:String = "AABBBAABA"){ ot.branch(startState) ct.branch(startState.clone()) let originalTokens = ot.tokenize(testString) let clonedTokens = ct.tokenize(testString) XCTAssert(originalTokens.count > 0, "Original tokens array is empty, bad test: \(startState)") assertTokenListsEqual(clonedTokens, reference: originalTokens) } func testCloneChar(){ tokenizersProduceSameOutput(aToken) } func testCloneBranchAndChar() { tokenizersProduceSameOutput( Branch(states: [aToken.clone(), bToken.clone()] ) ) } func testCloneRepeatAndChar() { tokenizersProduceSameOutput( Repeat(state:aToken.clone()).token("A's") ) } func testCloneRepeatBranchWithChar() { tokenizersProduceSameOutput( Repeat(state:Branch().branch(aToken.clone(),bToken.clone())).token("A's and B's") ) } func testChainedClone() { tokenizersProduceSameOutput(Branch().branch( aToken.clone().sequence(aToken.clone(),bToken.clone(),bToken.clone(),bToken.clone(),aToken.clone()) ) ) } func testChainedRepeatClone() { let repeatB = Repeat(state: bToken.clone()) let repeatAB = Repeat(state: aToken.clone()).branch(repeatB).token("AB") tokenizersProduceSameOutput(Repeat(state:repeatAB).token("AB's")) } func testDelimitedClone() { let sentance = Branch().branch( OKStandard.blanks, OKStandard.word, OKStandard.Code.quotedCharacterIncludingQuotes, OKStandard.eot ) tokenizersProduceSameOutput(sentance, testString: "The 'quick' brown fox jumped over the 'lazy' dog") } }
28.516854
111
0.619385
14f52342f4399925311a4316e389a09e1e70c076
976
// swift-tools-version:5.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "MimeParser", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "MimeParser", targets: ["MimeParser"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "MimeParser", dependencies: []), .testTarget(name: "MimeParserTests", dependencies: ["MimeParser"]), ] )
37.538462
122
0.657787
21f2bd8eecc75dcfb9b5ebe7ddcdd971ad7479e8
443
// // ChainRouteBuilder.swift // FIOSDK // // Created by Vitor Navarro on 2019-04-02. // Copyright © 2019 Dapix, Inc. All rights reserved. // import Foundation internal struct ChainRouteBuilder { static func build(route: ChainRoutes) -> String { return ChainRouteBuilder.getBaseURL() + route.rawValue } private static func getBaseURL() -> String { return Utilities.sharedInstance().URL } }
20.136364
62
0.659142
5640f65519481c26fc4c5760ab62d8f10c2ae958
3,092
// // ContentView.swift // ios // // Created by Boerni on 14.04.20. // Copyright © 2020 stream-steam. All rights reserved. // import SwiftUI import MatomoTracker func initTracker() -> MatomoTracker { // get tracking server URl from plist var resourceFileDictionary: NSDictionary? if let path = Bundle.main.path(forResource: "Info", ofType: "plist") { resourceFileDictionary = NSDictionary(contentsOfFile: path) } // actual tracker let matomoTracker = MatomoTracker(siteId: "1", baseURL: URL(string: resourceFileDictionary?["TrackingServerURL"] as! String)!) matomoTracker.logger = DefaultLogger(minLevel: .debug) return matomoTracker } let matomoTracker = initTracker() struct ViewTab1: View { var body: some View { VStack { Text("First View") Text("change tab to fire page view event") Text("---------") Text("Click Button to fire play.slide.volume event with value=1.0") Button(action: { matomoTracker.track(eventWithCategory: "player", action: "slide", name: "volume", value: 1.0) matomoTracker.dispatch() }) { Image(systemName: "volume") .font(.largeTitle) .foregroundColor(.red) } } } } struct ViewTab2: View { var body: some View { VStack { Text("Second View") Text("change tab to fire page view event") Text("---------") Text("Click Button to fire play.slide.volume event with value=9.5") Button(action: { matomoTracker.track(eventWithCategory: "player", action: "slide", name: "volume", value: 9.5) matomoTracker.dispatch() }) { Image(systemName: "volume") .font(.largeTitle) .foregroundColor(.red) } } } } struct ContentView: View { @State private var selection = 0 var body: some View { TabView(selection: $selection) { ViewTab1() .font(.title) .tabItem { VStack { Image("first") Text("First") } } .tag(0).onAppear{ print("Track First View") matomoTracker.track(view: ["First View"]) matomoTracker.dispatch() } ViewTab2() .font(.title) .tabItem { VStack { Image("second") Text("Second") } } .tag(1).onAppear { print("Track Second View") matomoTracker.track(view: ["Second View"]) matomoTracker.dispatch() } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
28.897196
130
0.496442
91fb092d53b367d7b27336cf228dde8241fe5c2d
2,994
// // AppDelegate.swift // BookMe5iOS // // Created by Remi Robert on 06/12/15. // Copyright © 2015 Remi Robert. All rights reserved. // import UIKit import FBSDKCoreKit import IQKeyboardManagerSwift import SocketIO let socket = SocketIOClient(socketURL: NSURL(string: "http://api.bookme5.com:3000")!, config: [ .Log(true), .Reconnects(true), .ForcePolling(true), .ExtraHeaders(["auth_token": TokenAccess.accessToken ?? "notoken"]) ]) @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private lazy var appCoordinator: AppCoordinator = AppCoordinator(window: self.window!) func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { var error: NSError? = nil GGLContext.sharedInstance().configureWithError(&error) assert(error == nil, "Error configuring Google services: \(error)") FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) self.window = UIWindow(frame: UIScreen.mainScreen().bounds) TokenAccess.initTokenFromSecureStore() IQKeyboardManager.sharedManager().enable = true self.appCoordinator.start() self.setupApparence() self.window?.makeKeyAndVisible() return true } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { if url.scheme.rangeOfString("com.googleusercontent") != nil { let options: [String: AnyObject] = [UIApplicationOpenURLOptionsSourceApplicationKey: sourceApplication!, UIApplicationOpenURLOptionsAnnotationKey: annotation] return GIDSignIn.sharedInstance().handleURL(url, sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as! String, annotation: options[UIApplicationOpenURLOptionsAnnotationKey]) } else { return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } } func applicationDidBecomeActive(application: UIApplication) { FBSDKAppEvents.activateApp() } } extension AppDelegate { func setupApparence() { // let navBar = UINavigationBar.appearance() // navBar.opaque = false // navBar.shadowImage = UIImage() // navBar.setBackgroundImage(UIImage(), forBarMetrics: .Default) let tabBar = UITabBar.appearance() tabBar.opaque = false tabBar.shadowImage = UIImage() tabBar.backgroundColor = UIColor(red:1, green:0.38, blue:0.21, alpha:1) } }
36.962963
161
0.652973
90f184a91eca8d7664c58123b7cde3cb9fbd8ad1
251
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum b { class d { var b { { deinit { case var { struct D { func g { class case ,
15.6875
87
0.717131
d76f75a45ca35a60e6b67968ec3750a32b20309a
6,155
// // OAuth2Swift.swift // OAuthSwift // // Created by Dongri Jin on 6/22/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation import UIKit public class OAuth2Swift: NSObject { public var client: OAuthSwiftClient public var webViewController: UIViewController? var consumer_key: String var consumer_secret: String var authorize_url: String var access_token_url: String? var response_type: String var observer: AnyObject? public convenience init(consumerKey: String, consumerSecret: String, authorizeUrl: String, accessTokenUrl: String, responseType: String){ self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, authorizeUrl: authorizeUrl, responseType: responseType) self.access_token_url = accessTokenUrl } public init(consumerKey: String, consumerSecret: String, authorizeUrl: String, responseType: String){ self.consumer_key = consumerKey self.consumer_secret = consumerSecret self.authorize_url = authorizeUrl self.response_type = responseType self.client = OAuthSwiftClient(consumerKey: consumerKey, consumerSecret: consumerSecret) } struct CallbackNotification { static let notificationName = "OAuthSwiftCallbackNotificationName" static let optionsURLKey = "OAuthSwiftCallbackNotificationOptionsURLKey" } struct OAuthSwiftError { static let domain = "OAuthSwiftErrorDomain" static let appOnlyAuthenticationErrorCode = 1 } public typealias TokenSuccessHandler = (credential: OAuthSwiftCredential, response: NSURLResponse?) -> Void public typealias FailureHandler = (error: NSError) -> Void public func authorizeWithCallbackURL(callbackURL: NSURL, scope: String, state: String, params: Dictionary<String, String> = Dictionary<String, String>(), success: TokenSuccessHandler, failure: ((error: NSError) -> Void)) { self.observer = NSNotificationCenter.defaultCenter().addObserverForName(CallbackNotification.notificationName, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock:{ notification in NSNotificationCenter.defaultCenter().removeObserver(self.observer!) let url = notification.userInfo![CallbackNotification.optionsURLKey] as! NSURL var parameters: Dictionary<String, String> = Dictionary() if ((url.query) != nil){ parameters = url.query!.parametersFromQueryString() } if ((url.fragment) != nil && url.fragment!.isEmpty == false) { parameters = url.fragment!.parametersFromQueryString() } if (parameters["access_token"] != nil){ self.client.credential.oauth_token = parameters["access_token"]! success(credential: self.client.credential, response: nil) } if (parameters["code"] != nil){ self.postOAuthAccessTokenWithRequestTokenByCode(parameters["code"]!.stringByRemovingPercentEncoding!, callbackURL:callbackURL, success: { credential, response in success(credential: credential, response: response) }, failure: failure) } }) //let authorizeURL = NSURL(string: ) var urlString = String() urlString += self.authorize_url urlString += (self.authorize_url.has("?") ? "&" : "?") + "client_id=\(self.consumer_key)" urlString += "&redirect_uri=\(callbackURL.absoluteString!)" urlString += "&response_type=\(self.response_type)" if (scope != "") { urlString += "&scope=\(scope)" } if (state != "") { urlString += "&state=\(state)" } for param in params { urlString += "&\(param.0)=\(param.1)" } let queryURL = NSURL(string: urlString) if ( self.webViewController != nil ) { if let webView = self.webViewController as? WebViewProtocol { webView.setUrl(queryURL!) UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController( self.webViewController!, animated: true, completion: nil) } } else { UIApplication.sharedApplication().openURL(queryURL!) } } func postOAuthAccessTokenWithRequestTokenByCode(code: String, callbackURL: NSURL, success: TokenSuccessHandler, failure: FailureHandler?) { var parameters = Dictionary<String, AnyObject>() parameters["client_id"] = self.consumer_key parameters["client_secret"] = self.consumer_secret parameters["code"] = code parameters["grant_type"] = "authorization_code" parameters["redirect_uri"] = callbackURL.absoluteString! self.client.post(self.access_token_url!, parameters: parameters, success: { data, response in var responseJSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) var accessToken = "" if let parameters:NSDictionary = responseJSON as? NSDictionary{ accessToken = parameters["access_token"] as! String } else { let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as String! let parameters = responseString.parametersFromQueryString() accessToken = parameters["access_token"]! } self.client.credential.oauth_token = accessToken self.client.credential.oauth2 = true success(credential: self.client.credential, response: response) }, failure: failure) } public class func handleOpenURL(url: NSURL) { let notification = NSNotification(name: CallbackNotification.notificationName, object: nil, userInfo: [CallbackNotification.optionsURLKey: url]) NSNotificationCenter.defaultCenter().postNotification(notification) } }
44.280576
226
0.651015
9ceeea14c8e43505c9c61bd9eefc2040d65bb83e
747
// // KVODisposeBag.swift // MobfiqKit // // Created by Gustavo Vergara Garcia on 12/12/17. // Copyright © 2017 Mobfiq. All rights reserved. // import Foundation public class KVODisposeBag { private var observations: [NSKeyValueObservation] public init() { self.observations = [] } deinit { self.clear() } public func add(_ observation: NSKeyValueObservation) { self.observations.append(observation) } public func clear() { self.observations.forEach { $0.invalidate() } self.observations = [] } } public extension NSKeyValueObservation { func dispose(in disposeBag: KVODisposeBag) { disposeBag.add(self) } }
18.219512
59
0.61178
90b0942f540f44467dce726a997016799abb3b25
602
import UIKit extension UIWindow { public func set(newRootController: UIViewController) { let transition = CATransition() transition.type = CATransitionType.fade transition.duration = 0.3 transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) layer.add(transition, forKey: kCATransition) let oldRootController = rootViewController rootViewController = newRootController oldRootController?.dismiss(animated: false) { oldRootController?.view.removeFromSuperview() } } }
26.173913
98
0.699336
878c81f07d0e0e5ba5294675074af525a6376e84
264
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol B : Int b protocol P { enum e { } typealias B : B) t: NSObject " func f<T B } var a B
18.857143
87
0.719697
0a81ec2523396cde4803cba1042b0cc6804fdbf9
4,751
// // ViewController.swift // DNStepsToModify // // Created by mainone on 2017/2/21. // Copyright © 2017年 mainone. All rights reserved. // import UIKit import HealthKit class ViewController: UIViewController { // 定义健康中心 let healthStore: HKHealthStore? = { if HKHealthStore.isHealthDataAvailable() { return HKHealthStore() } else { return nil } }() @IBOutlet weak var stepsNumberLabel: UILabel! @IBOutlet weak var addStepsTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() self.refreshSteps() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.refreshSteps() } func refreshSteps() { // 设置请求的权限,这里我们只获取读取和写入步数 let stepType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .stepCount) let dataTypesToRead = NSSet(objects: stepType as Any) // 权限请求 self.healthStore?.requestAuthorization(toShare: dataTypesToRead as? Set<HKSampleType>, read: dataTypesToRead as? Set<HKObjectType>, completion: { [unowned self] (success, error) in // 得到权限后就可以获取步数和写入了 if success { self.fetchSumOfSamplesToday(for: stepType!, unit: HKUnit.count()) { (stepCount, error) in // 获取到步数后,在主线程中更新数字 DispatchQueue.main.async { self.stepsNumberLabel.text = "\(stepCount!)" } } } else { let alert = UIAlertController(title: "提示", message: "不给权限我还怎么给你瞎写步数呢,可以去设置界面打开权限", defaultActionButtonTitle: "确定", tintColor: UIColor.red) alert.show() } }) } // 添加数据 @IBAction func addStepsBtnClick(_ sender: UIButton) { if let num = addStepsTextField.text { self.addstep(withStepNum: Double(num)!) } } func fetchSumOfSamplesToday(for quantityType: HKQuantityType, unit: HKUnit, completion completionHandler: @escaping (Double?, NSError?)->()) { let predicate: NSPredicate? = self.predicateForSamplesToday() let query = HKStatisticsQuery(quantityType: quantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { query, result, error in var totalCalories = 0.0 if let quantity = result?.sumQuantity() { let unit = HKUnit.count() totalCalories = quantity.doubleValue(for: unit) } completionHandler(totalCalories, error as NSError?) } self.healthStore?.execute(query) } func predicateForSamplesToday() -> NSPredicate { let calendar = Calendar.current let now = Date() let startDate: Date? = calendar.startOfDay(for: now) let endDate: Date? = calendar.date(byAdding: .day, value: 1, to: startDate!) return HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate) } func addstep(withStepNum stepNum: Double) { let stepCorrelationItem: HKQuantitySample? = self.stepCorrelation(withStepNum: stepNum) self.healthStore?.save(stepCorrelationItem!, withCompletion: { (success, error) in DispatchQueue.main.async(execute: {() -> Void in if success { self.view.endEditing(true) self.addStepsTextField.text = "" self.refreshSteps() let alert = UIAlertController(title: "提示", message: "添加步数成功", defaultActionButtonTitle: "确定", tintColor: UIColor.red) alert.show() } else { let alert = UIAlertController(title: "提示", message: "添加步数失败", defaultActionButtonTitle: "确定", tintColor: UIColor.red) alert.show() return } }) }) } func stepCorrelation(withStepNum stepNum: Double) -> HKQuantitySample { let endDate = Date() let startDate = Date(timeInterval: -300, since: endDate) let stepQuantityConsumed = HKQuantity(unit: HKUnit.count(), doubleValue: stepNum) let stepConsumedType = HKQuantityType.quantityType(forIdentifier: .stepCount) let stepConsumedSample = HKQuantitySample(type: stepConsumedType!, quantity: stepQuantityConsumed, start: startDate, end: endDate, metadata: nil) return stepConsumedSample } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) self.view.endEditing(true) } }
38.314516
188
0.605557
2069229a4d1637dc3770bb51764a38112663401d
7,986
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// struct _StringBufferIVars { init(_ elementWidth: Int) { _sanityCheck(elementWidth == 1 || elementWidth == 2) usedEnd = nil capacityAndElementShift = elementWidth - 1 } init( usedEnd: UnsafeMutablePointer<RawByte>, byteCapacity: Int, elementWidth: Int ) { _sanityCheck(elementWidth == 1 || elementWidth == 2) _sanityCheck((byteCapacity & 0x1) == 0) self.usedEnd = usedEnd self.capacityAndElementShift = byteCapacity + (elementWidth - 1) } // This stored property should be stored at offset zero. We perform atomic // operations on it using _HeapBuffer's pointer. var usedEnd: UnsafeMutablePointer<RawByte> var capacityAndElementShift: Int var byteCapacity: Int { return capacityAndElementShift & ~0x1 } var elementShift: Int { return capacityAndElementShift & 0x1 } } // FIXME: Wanted this to be a subclass of // _HeapBuffer<_StringBufferIVars,UTF16.CodeUnit>, but // <rdar://problem/15520519> (Can't call static method of derived // class of generic class with dependent argument type) prevents it. public struct _StringBuffer { // Make this a buffer of UTF-16 code units so that it's properly // aligned for them if that's what we store. typealias _Storage = _HeapBuffer<_StringBufferIVars, UTF16.CodeUnit> typealias HeapBufferStorage = _HeapBufferStorage<_StringBufferIVars, UTF16.CodeUnit> init(_ storage: _Storage) { _storage = storage } public init(capacity: Int, initialSize: Int, elementWidth: Int) { _sanityCheck(elementWidth == 1 || elementWidth == 2) _sanityCheck(initialSize <= capacity) // We don't check for elementWidth overflow and underflow because // elementWidth is known to be 1 or 2. let elementShift = elementWidth &- 1 // We need at least 1 extra byte if we're storing 8-bit elements, // because indexing will always grab 2 consecutive bytes at a // time. let capacityBump = 1 &- elementShift // Used to round capacity up to nearest multiple of 16 bits, the // element size of our storage. let divRound = 1 &- elementShift _storage = _Storage( HeapBufferStorage.self, _StringBufferIVars(elementWidth), (capacity + capacityBump + divRound) >> divRound ) self.usedEnd = start + (initialSize << elementShift) _storage.value.capacityAndElementShift = ((_storage._capacity() - capacityBump) << 1) + elementShift } @warn_unused_result static func fromCodeUnits< Encoding : UnicodeCodecType, Input : CollectionType // SequenceType? where Input.Generator.Element == Encoding.CodeUnit >( encoding: Encoding.Type, input: Input, repairIllFormedSequences: Bool, minimumCapacity: Int = 0 ) -> (_StringBuffer?, hadError: Bool) { // Determine how many UTF-16 code units we'll need let inputStream = input.generate() guard let (utf16Count, isAscii) = UTF16.measure(encoding, input: inputStream, repairIllFormedSequences: repairIllFormedSequences) else { return (.None, true) } // Allocate storage let result = _StringBuffer( capacity: max(utf16Count, minimumCapacity), initialSize: utf16Count, elementWidth: isAscii ? 1 : 2) if isAscii { var p = UnsafeMutablePointer<UTF8.CodeUnit>(result.start) let sink: (UTF32.CodeUnit) -> Void = { (p++).memory = UTF8.CodeUnit($0) } let hadError = transcode( encoding, UTF32.self, input.generate(), sink, stopOnError: true) _sanityCheck(!hadError, "string can not be ASCII if there were decoding errors") return (result, hadError) } else { var p = result._storage.baseAddress let sink: (UTF16.CodeUnit) -> Void = { (p++).memory = $0 } let hadError = transcode( encoding, UTF16.self, input.generate(), sink, stopOnError: !repairIllFormedSequences) return (result, hadError) } } /// A pointer to the start of this buffer's data area. public var start: UnsafeMutablePointer<RawByte> { return UnsafeMutablePointer(_storage.baseAddress) } /// A past-the-end pointer for this buffer's stored data. var usedEnd: UnsafeMutablePointer<RawByte> { get { return _storage.value.usedEnd } set(newValue) { _storage.value.usedEnd = newValue } } var usedCount: Int { return (usedEnd - start) >> elementShift } /// A past-the-end pointer for this buffer's available storage. var capacityEnd: UnsafeMutablePointer<RawByte> { return start + _storage.value.byteCapacity } /// The number of elements that can be stored in this buffer. public var capacity: Int { return _storage.value.byteCapacity >> elementShift } /// 1 if the buffer stores UTF-16; 0 otherwise. var elementShift: Int { return _storage.value.elementShift } /// The number of bytes per element. var elementWidth: Int { return elementShift + 1 } // Return true iff we have the given capacity for the indicated // substring. This is what we need to do so that users can call // reserveCapacity on String and subsequently use that capacity, in // two separate phases. Operations with one-phase growth should use // "grow()," below. @warn_unused_result func hasCapacity( cap: Int, forSubRange r: Range<UnsafePointer<RawByte>> ) -> Bool { // The substring to be grown could be pointing in the middle of this // _StringBuffer. let offset = (r.startIndex - UnsafePointer(start)) >> elementShift return cap + offset <= capacity } /// Attempt to claim unused capacity in the buffer. /// /// Operation succeeds if there is sufficient capacity, and either: /// - the buffer is uniquely-refereced, or /// - `oldUsedEnd` points to the end of the currently used capacity. /// /// - parameter subRange: Range of the substring that the caller tries /// to extend. /// - parameter newUsedCount: The desired size of the substring. mutating func grow( subRange: Range<UnsafePointer<RawByte>>, newUsedCount: Int ) -> Bool { var newUsedCount = newUsedCount // The substring to be grown could be pointing in the middle of this // _StringBuffer. Adjust the size so that it covers the imaginary // substring from the start of the buffer to `oldUsedEnd`. newUsedCount += (subRange.startIndex - UnsafePointer(start)) >> elementShift if _slowPath(newUsedCount > capacity) { return false } let newUsedEnd = start + (newUsedCount << elementShift) if _fastPath(self._storage.isUniquelyReferenced()) { usedEnd = newUsedEnd return true } // Optimization: even if the buffer is shared, but the substring we are // trying to grow is located at the end of the buffer, it can be grown in // place. The operation should be implemented in a thread-safe way, // though. // // if usedEnd == subRange.endIndex { // usedEnd = newUsedEnd // return true // } let usedEndPhysicalPtr = UnsafeMutablePointer<UnsafeMutablePointer<RawByte>>(_storage._value) var expected = UnsafeMutablePointer<RawByte>(subRange.endIndex) if _stdlib_atomicCompareExchangeStrongPtr( object: usedEndPhysicalPtr, expected: &expected, desired: newUsedEnd) { return true } return false } var _anyObject: AnyObject? { return _storage.storage != nil ? .Some(_storage.storage!) : .None } var _storage: _Storage }
33.414226
86
0.674681
f8cdf4e3b2f854041bd219872d48cdb86eb4fa95
1,137
import Foundation import Combine import FjuulAnalytics class AggregatedDailyStatsObservable: ObservableObject { @Published var isLoading: Bool = false @Published var error: ErrorHolder? @Published var fromDate: Date = Date() @Published var toDate: Date = Date() @Published var aggregation: AggregationType = .sum @Published var value: AggregatedDailyStats? private var dateObserver: AnyCancellable? init() { dateObserver = $fromDate.combineLatest($toDate, $aggregation).sink { (fromDate, toDate, aggregation) in self.fetch(fromDate, toDate, aggregation) } } func fetch(_ fromDate: Date, _ toDate: Date, _ aggregation: AggregationType) { self.isLoading = true ApiClientHolder.default.apiClient?.analytics.aggregatedDailyStats(from: fromDate, to: toDate, aggregation: aggregation) { result in self.isLoading = false switch result { case .success(let aggregatedDailyStats): self.value = aggregatedDailyStats case .failure(let err): self.error = ErrorHolder(error: err) } } } }
32.485714
139
0.677221