repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
dbahat/conventions-ios
refs/heads/sff
Conventions/Conventions/events/SearchCategoriesView.swift
apache-2.0
1
// // SearchCategoriesView.swift // Conventions // // Created by David Bahat on 9/24/16. // Copyright © 2016 Amai. All rights reserved. // import Foundation protocol SearchCategoriesProtocol : class { func filterSearchCategoriesChanged(_ enabledCategories: Array<AggregatedSearchCategory>) } class SearchCategoriesView : UIView { @IBOutlet private weak var lecturesSwitch: UISwitch! @IBOutlet private weak var workshopsSwitch: UISwitch! @IBOutlet private weak var showsSwitch: UISwitch! @IBOutlet private weak var othersSwitch: UISwitch! @IBOutlet private weak var lecturesLabel: UILabel! @IBOutlet private weak var workshopsLabel: UILabel! @IBOutlet private weak var showsLabel: UILabel! @IBOutlet private weak var othersLabel: UILabel! weak var delegate: SearchCategoriesProtocol? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); let view = Bundle.main.loadNibNamed(String(describing: SearchCategoriesView.self), owner: self, options: nil)![0] as! UIView; view.frame = self.bounds; addSubview(view); lecturesSwitch.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) workshopsSwitch.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) showsSwitch.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) othersSwitch.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) lecturesSwitch.onTintColor = Colors.switchButtonsColor workshopsSwitch.onTintColor = Colors.switchButtonsColor showsSwitch.onTintColor = Colors.switchButtonsColor othersSwitch.onTintColor = Colors.switchButtonsColor lecturesLabel.textColor = Colors.textColor workshopsLabel.textColor = Colors.textColor showsLabel.textColor = Colors.textColor othersLabel.textColor = Colors.textColor } @IBAction fileprivate func lecturesWasTapped(_ sender: UITapGestureRecognizer) { lecturesSwitch.setOn(!lecturesSwitch.isOn, animated: true) filterSearchCategoriesChanged() } @IBAction fileprivate func gamesWasTapped(_ sender: UITapGestureRecognizer) { workshopsSwitch.setOn(!workshopsSwitch.isOn, animated: true) filterSearchCategoriesChanged() } @IBAction fileprivate func showsWasTapped(_ sender: UITapGestureRecognizer) { showsSwitch.setOn(!showsSwitch.isOn, animated: true) filterSearchCategoriesChanged() } @IBAction fileprivate func othersWasTapped(_ sender: UITapGestureRecognizer) { othersSwitch.setOn(!othersSwitch.isOn, animated: true) filterSearchCategoriesChanged() } fileprivate func filterSearchCategoriesChanged() { var searchCategories = Array<AggregatedSearchCategory>() if lecturesSwitch.isOn { searchCategories.append(AggregatedSearchCategory.lectures) } if workshopsSwitch.isOn { searchCategories.append(AggregatedSearchCategory.workshops) } if showsSwitch.isOn { searchCategories.append(AggregatedSearchCategory.shows) } if othersSwitch.isOn { searchCategories.append(AggregatedSearchCategory.others) } delegate?.filterSearchCategoriesChanged(searchCategories) } }
bbb02e36c94340c7c8a95554ce2850e8
38.666667
133
0.706783
false
false
false
false
kitasuke/TwitterClientDemo
refs/heads/develop
TwitterClientDemo/Classes/ViewControllers/FollowersViewController.swift
mit
1
// // FollowersViewController.swift // TwitterClientDemo // // Created by Yusuke Kita on 5/20/15. // Copyright (c) 2015 kitasuke. All rights reserved. // import UIKit class FollowersViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView? private var users = [User]() private var paginator = Paginator() private let CellHeightUser: CGFloat = 64 private var loading = false private enum Section: Int { case Indicator = 0 case Contents = 1 } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.setupTableView() self.fetchFollowersList(readMore: false) self.fetchMeInBackground() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - UITableViewDelegate func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 // Indicator + Contents } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case Section.Indicator.rawValue: return count(users) > 0 ? 0 : 1 // show indicator if no contents case Section.Contents.rawValue: return count(users) default: return 0 } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { switch indexPath.section { case Section.Indicator.rawValue: return CGRectGetHeight(tableView.frame) case Section.Contents.rawValue: return CellHeightUser default: return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch indexPath.section { case Section.Indicator.rawValue: let cell = tableView.dequeueReusableCellWithIdentifier(CellName.Indicator.rawValue, forIndexPath: indexPath) as! IndicatorCell return cell case Section.Contents.rawValue: let cell = tableView.dequeueReusableCellWithIdentifier(CellName.User.rawValue, forIndexPath: indexPath) as! UserCell let user = users[indexPath.row] cell.setup(user, indexPath: indexPath) self.registerGestureRecognizers(cell) return cell default: return UITableViewCell() } } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { // read more if needed if paginator.hasNext && !loading && count(users) - 10 < indexPath.row { // TODO self.fetchFollowersList(readMore: true) } } // MARK: - Gesture handler internal func openMessageView(recognizer: UITapGestureRecognizer) { if let row = recognizer.view?.tag { let user = users[row] UserStore.sharedStore.currentUser = user let messageViewController = UIStoryboard(name: StoryboardName.Message.rawValue, bundle: nil).instantiateInitialViewController() as! MessageViewController self.navigationController?.pushViewController(messageViewController, animated: true) } } internal func openProfileView(recognizer: UITapGestureRecognizer) { if let row = recognizer.view?.tag { let user = users[row] UserStore.sharedStore.currentUser = user let profileViewController = UIStoryboard(name: StoryboardName.Profile.rawValue, bundle: nil).instantiateInitialViewController() as! ProfileViewController self.navigationController?.pushViewController(profileViewController, animated: true) } } // MARK: - IBAction @IBAction func openMyProfileView(sender: UIBarButtonItem) { UserStore.sharedStore.currentUser = UserStore.sharedStore.me let profileViewController = UIStoryboard(name: StoryboardName.Profile.rawValue, bundle: nil).instantiateInitialViewController() as! ProfileViewController self.navigationController?.pushViewController(profileViewController, animated: true) } // MARK: - Setup private func setupTableView() { self.tableView?.estimatedRowHeight = CellHeightUser let userCellName = CellName.User.rawValue self.tableView?.registerNib(UINib(nibName: userCellName, bundle: nil), forCellReuseIdentifier: userCellName) let indicatorCellName = CellName.Indicator.rawValue self.tableView?.registerNib(UINib(nibName: indicatorCellName, bundle: nil), forCellReuseIdentifier: indicatorCellName) } private func registerGestureRecognizers(cell: UserCell) { cell.contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("openMessageView:"))) cell.profileImageView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("openProfileView:"))) } // MARK: - Fetcher private func fetchFollowersList(#readMore: Bool) { loading = true let nextCorsor = readMore ? paginator.nextCursor : -1 // TODO UIApplication.sharedApplication().networkActivityIndicatorVisible = true dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in TwitterStore.sharedStore.fetchFollowers({ [unowned self] (result: Result<[String : AnyObject]>) -> Void in UIApplication.sharedApplication().networkActivityIndicatorVisible = false self.loading = false if let error = result.error { let alertController = ConnectionAlert.Error(message: error.description).alertController self.presentViewController(alertController, animated: true, completion: nil) return } if let values = result.value { self.users += values["users"] as! [User] self.paginator = values["paginator"] as! Paginator dispatch_async(dispatch_get_main_queue(), { () -> Void in self.tableView?.reloadData() }) } }, nextCursor: nextCorsor) }) } private func fetchMeInBackground() { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in TwitterStore.sharedStore.fetchMe({ (result: Result<User>) -> Void in // TODO }) }) } }
2ffa720135880240032c6ed7b144fa3e
39.376471
165
0.649184
false
false
false
false
LiskUser1234/SwiftyLisk
refs/heads/master
Lisk/Delegate/DelegateAPI.swift
mit
1
/* The MIT License Copyright (C) 2017 LiskUser1234 - Github: https://github.com/liskuser1234 Please vote LiskUser1234 for delegate to support this project. For donations: - Lisk: 6137947831033853925L - Bitcoin: 1NCTZwBJF7ZFpwPeQKiSgci9r2pQV3G7RG 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 SwiftyJSON class DelegateAPI { private static let moduleName = "delegates" /// Turns the account derived from the given `passphrase` into a delegate with the given `username` /// /// - Parameters: /// - passphrase: The passphrase whose derived address will become a delegate /// - publicKey: Optional: The expected public key for the account derived from the given `passphrase` /// - secondPassphrase: Optional: the second passphrase of the address that will become a delegate. Necessary to sign the delegate registration transaction /// - username: The username that will be associated with the addresss to turn into a delegate /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#enable-delegate-on-account open class func becomeDelegate(passphrase: String, publicKey: String?, secondPassphrase: String?, username: String, callback: @escaping Callback) { var data = [ "secret": passphrase, "username": username ] if let secondPassphrase = secondPassphrase { data["secondSecretKey"] = secondPassphrase } if let publicKey = publicKey { data["publicKey"] = publicKey } Api.request(module: moduleName, submodule: nil, method: .put, json: data, callback: callback) } /// Gets data about all delegates matching the given query. /// /// - Parameters: /// - query: The query to filter delegates /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#get-delegates-list open class func getAllDelegates(query: [String : String], callback: @escaping Callback) { Api.request(module: moduleName, submodule: nil, method: .get, query: query, callback: callback) } /// Gets data about a delegate with the given username /// /// - Parameters: /// - username: The username of the delegate to retrieve /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#get-delegate open class func getDelegate(username: String, callback: @escaping Callback) { let data = [ "username": username ] Api.request(module: moduleName, submodule: "get", method: .get, query: data, callback: callback) } /// Gets data about a delegate with the given public key /// /// - Parameters: /// - publicKey: The public key of the delegate to retrieve /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#get-delegate open class func getDelegate(publicKey: String, callback: @escaping Callback) { let data = [ "publicKey": publicKey ] Api.request(module: moduleName, submodule: "get", method: .get, query: data, callback: callback) } /// Gets data about all delegates whose username fuzzy-matches the given string (`partialUsername`) /// /// - Parameters: /// - partialUsername: Part of the username of the delegate to retrieve /// - limit: Maximum amount of results to return. Between 1 and 1,000 /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#search-for-delegates open class func search(partialUsername: String, limit: Int?, callback: @escaping Callback) { var data = [ "q": partialUsername ] if let limit = limit { data["limit"] = String(limit) } Api.request(module: moduleName, submodule: "search", method: .get, query: data, callback: callback) } /// Gets the total number of registered delegates. /// /// - Parameter callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#get-delegates-count open class func getDelegatesCount(callback: @escaping Callback) { Api.request(module: moduleName, submodule: "count", method: .get, callback: callback) } /// Gets all votes casted by an account. Identical to AccountAPI.getDelegates /// /// - Parameters: /// - address: The address whose votes will be retrieved /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#get-votes-of-account open class func getVotes(address: String, callback: @escaping Callback) { let data = [ "address": address ] Api.request(module: "accounts", submodule: "delegates", method: .get, query: data, callback: callback) } /// Gets the voters of the given public key. /// /// - Parameters: /// - publicKey: The public key whose votes will be retrieved /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#get-voters open class func getVoters(publicKey: String, callback: @escaping Callback) { let data = [ "publicKey": publicKey ] Api.request(module: moduleName, submodule: "voters", method: .get, query: data, callback: callback) } /// Enable forging on the delegate matching the given passphrase /// /// - Parameters: /// - passphrase: The passphrase of the delegate for which to enable forging /// - publicKey: Optional: The public key to match against the public key of the account derived from `passphrase` /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#enable-forging-on-delegate open class func enableForging(passphrase: String, publicKey: String?, callback: @escaping Callback) { toggleForging(passphrase: passphrase, publicKey: publicKey, enable: true, callback: callback) } /// Disable forging on the delegate matching the given passphrase /// /// - Parameters: /// - passphrase: The passphrase of the delegate for which to disable forging /// - publicKey: Optional: The public key to match against the public key of the account derived from `passphrase` /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#disable-forging-on-delegate open class func disableForging(passphrase: String, publicKey: String?, callback: @escaping Callback) { toggleForging(passphrase: passphrase, publicKey: publicKey, enable: false, callback: callback) } /// Gets whether the current node is forging on behalf of the delegate with the given public key /// /// - Parameters: /// - publicKey: The public key of the delegate for which the server will tell whether it is in its list of forgers /// - callback: The function that will be called with information about the request open class func isForging(publicKey: String, callback: @escaping Callback) { Api.request(module: "forging", submodule: "status", method: .get, callback: callback) } /// Gets the amount of lisks forged by the given public key. /// /// - Parameters: /// - publicKey: The public key whose forged amount will be retrieved /// - start: Optional: the minimum timestamp to consider for the search; inclusive /// - end: Optional: the maximum timestamp to consider for the search; inclusive /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#get-forged-by-account open class func getForgedByAccount(publicKey: String, start: Int64?, end: Int64?, callback: @escaping Callback) { var data = [ "generatorPublicKey": publicKey ] if let start = start { data["start"] = String(start) } if let end = end { data["end"] = String(end) } Api.request(module: moduleName, submodule: "forging/getForgedByAccount", method: .get, query: data, callback: callback) } /// Gets the schedule of forgers for the future blocks. /// /// - Parameters: /// - limit: The maximum amount of future blocks to get /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#get-next-forgers open class func getNextForgers(limit: Int?, callback: @escaping Callback) { var data: [String : String] = [:] if let limit = limit { data["limit"] = String(limit) } Api.request(module: moduleName, submodule: "getNextForgers", method: .get, query: data, callback: callback) } /// Gets the fee to register as a delegate. /// /// - Parameter callback: The function that will be called with information about the request open class func getFee(callback: @escaping Callback) { Api.request(module: moduleName, submodule: "fee", method: .get, callback: callback) } // Helper methods private static func toggleForging(passphrase: String, publicKey: String?, enable: Bool, callback: @escaping Callback) { var data = [ "secret": passphrase ] if let publicKey = publicKey { data["publicKey"] = publicKey } Api.request(module: moduleName, submodule: (enable ? "forging/enable" : "forging/disable"), method: .post, json: data, callback: callback) } }
6363f2e23f7aeb7af7ef7f57d81a9715
39.319088
161
0.575961
false
false
false
false
nuudles/RecyclingCenter
refs/heads/master
Example/RecyclingCenterExample/ViewController.swift
mit
1
// // ViewController.swift // RecyclingCenterExample // // Created by Christopher Luu on 10/14/15. // Copyright © 2015 Nuudles. All rights reserved. // import UIKit import RecyclingCenter class ViewController: UIViewController { // MARK: - Private constants private static let redReuseIdentifier = "redReuseIdentifier" private static let blueReuseIdentifier = "blueReuseIdentifier" // MARK: - Private properties private var redViews: [RecyclableView] = [] private var blueViews: [RecyclableView] = [] private lazy var recyclingCenter: RecyclingCenter<RecyclableView> = { let recyclingCenter = RecyclingCenter<RecyclableView>() recyclingCenter.registerInitHandler({ (_) in NSLog("Creating red"); return RecyclableView(color: .redColor()) }, forReuseIdentifier: ViewController.redReuseIdentifier) recyclingCenter.registerInitHandler({ (_) in NSLog("Creating blue"); return RecyclableView(color: .blueColor()) }, forReuseIdentifier: ViewController.blueReuseIdentifier) return recyclingCenter }() // MARK: - View methods override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItems = [ UIBarButtonItem(title: "+Red", style: .Plain, target: self, action: #selector(ViewController.addRed)), UIBarButtonItem(title: "-Red", style: .Plain, target: self, action: #selector(ViewController.deleteRed)), UIBarButtonItem(title: "+Blue", style: .Plain, target: self, action: #selector(ViewController.addBlue)), UIBarButtonItem(title: "-Blue", style: .Plain, target: self, action: #selector(ViewController.deleteBlue)) ] } // MARK: - Button action methods func addRed() { let redView = try! recyclingCenter.dequeueObjectWithReuseIdentifier(ViewController.redReuseIdentifier, context: nil) redViews.append(redView) redView.center = CGPoint(x: CGFloat(arc4random_uniform(UInt32(view.bounds.size.width))), y: CGFloat(arc4random_uniform(UInt32(view.bounds.size.height)))) view.addSubview(redView) } func addBlue() { let blueView = try! recyclingCenter.dequeueObjectWithReuseIdentifier(ViewController.blueReuseIdentifier, context: nil) blueViews.append(blueView) blueView.center = CGPoint(x: CGFloat(arc4random_uniform(UInt32(view.bounds.size.width))), y: CGFloat(arc4random_uniform(UInt32(view.bounds.size.height)))) view.addSubview(blueView) } func deleteRed() { guard redViews.count > 0 else { return } let redView = redViews.removeFirst() redView.removeFromSuperview() try! recyclingCenter.enqueueObject(redView, withReuseIdentifier: ViewController.redReuseIdentifier) } func deleteBlue() { guard blueViews.count > 0 else { return } let blueView = blueViews.removeFirst() blueView.removeFromSuperview() try! recyclingCenter.enqueueObject(blueView, withReuseIdentifier: ViewController.blueReuseIdentifier) } } class RecyclableView: UIView, Recyclable { // MARK: - Init methods init(color: UIColor) { super.init(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) backgroundColor = color } required init?(coder aDecoder: NSCoder) { fatalError("This init method should never be called") } }
db82057bfde560c1301ccb2a4ee3c9be
32.085106
172
0.755949
false
false
false
false
sarunw/SWCardViewController
refs/heads/master
SWCardViewController/Classes/SWCardViewCollectionViewFlowLayout.swift
mit
1
// // SWCardViewCollectionViewFlowLayout.swift // Pods // // Created by Sarun Wongpatcharapakorn on 8/9/16. // // import UIKit class SWCardViewCollectionViewFlowLayout: UICollectionViewFlowLayout { override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { guard let collectionView = self.collectionView else { return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity) } let bounds = collectionView.bounds let halfWidth = bounds.size.width * 0.5; let proposedContentOffsetCenterX = proposedContentOffset.x + halfWidth; if let attributesForVisibleCells = layoutAttributesForElements(in: bounds) { var candidateAttributes : UICollectionViewLayoutAttributes? for attributes in attributesForVisibleCells { // == Skip comparison with non-cell items (headers and footers) == // if attributes.representedElementCategory != UICollectionElementCategory.cell { continue } if let candAttrs = candidateAttributes { let a = attributes.center.x - proposedContentOffsetCenterX let b = candAttrs.center.x - proposedContentOffsetCenterX if fabsf(Float(a)) < fabsf(Float(b)) { candidateAttributes = attributes; } } else { // == First time in the loop == // candidateAttributes = attributes; continue; } } return CGPoint(x: round(candidateAttributes!.center.x - halfWidth), y: proposedContentOffset.y) } return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity) } // override func finalLayoutAttributesForDisappearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { // let attributes = super.finalLayoutAttributesForDisappearingItemAtIndexPath(itemIndexPath) // //// attributes?.alpha = 0 // print("final \(attributes?.alpha)") // return attributes // } // // override func initialLayoutAttributesForAppearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { // let attributes = super.initialLayoutAttributesForAppearingItemAtIndexPath(itemIndexPath) // // print("initial \(attributes?.alpha)") // return attributes // } }
faa6c731b63478a197dee930db426677
38.283784
148
0.604403
false
false
false
false
lenssss/whereAmI
refs/heads/master
Whereami/View/GameQuestionHeadView.swift
mit
1
// // GameQuestionHeadView.swift // Whereami // // Created by A on 16/3/25. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit class GameQuestionHeadView: UIView { typealias theCallback = () -> Void var QuestionTitle:UILabel? = nil var QuestionPicture:UIImageView? = nil // var collectButton:UIButton? = nil // var callBack:theCallback? = nil override init(frame: CGRect) { super.init(frame:frame) self.setUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setUI() } func setUI(){ self.QuestionTitle = UILabel() self.QuestionTitle?.font = UIFont.systemFontOfSize(12.0) self.QuestionTitle?.textAlignment = .Center self.QuestionTitle?.numberOfLines = 0 self.QuestionTitle?.textColor = UIColor.whiteColor() self.addSubview(self.QuestionTitle!) self.QuestionPicture = UIImageView() self.QuestionPicture?.layer.masksToBounds = true self.QuestionPicture?.layer.cornerRadius = 10.0 self.QuestionPicture?.layer.borderColor = UIColor.whiteColor().CGColor self.QuestionPicture?.layer.borderWidth = 2.0 self.addSubview(self.QuestionPicture!) // self.collectButton = UIButton() // self.collectButton?.rac_signalForControlEvents(.TouchUpInside).subscribeNext({ (button) in // self.callBack!() // }) // self.addSubview(self.collectButton!) self.QuestionTitle?.autoPinEdgeToSuperviewEdge(.Top, withInset: 0) self.QuestionTitle?.autoPinEdgeToSuperviewEdge(.Left, withInset: 80) self.QuestionTitle?.autoPinEdgeToSuperviewEdge(.Right, withInset: 80) self.QuestionTitle?.autoSetDimension(.Height, toSize: 60) self.QuestionTitle?.autoPinEdge(.Bottom, toEdge: .Top, ofView: self.QuestionPicture!, withOffset: 0) // self.QuestionPicture?.autoAlignAxisToSuperviewAxis(.Vertical) // self.QuestionPicture?.autoSetDimensionsToSize(CGSize(width: 220,height: 220)) self.QuestionPicture?.autoPinEdgeToSuperviewEdge(.Left, withInset: 80) self.QuestionPicture?.autoPinEdgeToSuperviewEdge(.Right, withInset: 80) self.QuestionPicture?.autoMatchDimension(.Height, toDimension: .Width, ofView: self.QuestionPicture!) // self.collectButton?.autoPinEdgeToSuperviewEdge(.Left, withInset: 90) // self.collectButton?.autoPinEdgeToSuperviewEdge(.Right, withInset: 90) // self.collectButton?.autoPinEdge(.Top, toEdge: .Bottom, ofView: self.QuestionTitle!) // self.collectButton?.autoSetDimension(.Height, toSize: 50) } }
c2df9edd9347ea48edd89dfe755fffba
39.014706
109
0.674384
false
false
false
false
PureSwift/Bluetooth
refs/heads/master
Sources/BluetoothHCI/HCILEEnhancedReceiverTest.swift
mit
1
// // HCILEEnhancedReceiverTest.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation // MARK: - Method public extension BluetoothHostControllerInterface { /// LE Enhanced Receiver Test Command /// /// This command is used to start a test where the DUT receives test /// reference packets at a fixed interval. The tester generates the test /// reference packets. func lowEnergyEnhancedReceiverTest(rxChannel: LowEnergyRxChannel, phy: HCILEEnhancedReceiverTest.Phy, modulationIndex: HCILEEnhancedReceiverTest.ModulationIndex, timeout: HCICommandTimeout = .default) async throws { let parameters = HCILEEnhancedReceiverTest(rxChannel: rxChannel, phy: phy, modulationIndex: modulationIndex) try await deviceRequest(parameters, timeout: timeout) } } // MARK: - Command /// LE Enhanced Receiver Test Command /// /// This command is used to start a test where the DUT receives test reference packets at a /// fixed interval. The tester generates the test reference packets. @frozen public struct HCILEEnhancedReceiverTest: HCICommandParameter { public static let command = HCILowEnergyCommand.enhancedReceiverTest //0x0033 public let rxChannel: LowEnergyRxChannel public let phy: Phy public let modulationIndex: ModulationIndex public init(rxChannel: LowEnergyRxChannel, phy: Phy, modulationIndex: ModulationIndex) { self.rxChannel = rxChannel self.phy = phy self.modulationIndex = modulationIndex } public var data: Data { return Data([rxChannel.rawValue, phy.rawValue, modulationIndex.rawValue]) } public enum Phy: UInt8 { /// Receiver set to use the LE 1M PHY case le1MPhy = 0x01 /// Receiver set to use the LE 2M PHY case le2MPhy = 0x02 /// Receiver set to use the LE Coded PHY case leCodedPhy = 0x03 } public enum ModulationIndex: UInt8 { /// Assume transmitter will have a standard modulation index case standard = 0x00 /// Assume transmitter will have a stable modulation index case stable = 0x01 } }
fb6abb32bef867d0be6885df52e60b78
30.876712
219
0.673829
false
true
false
false
PGSSoft/AutoMate
refs/heads/master
AutoMateExample/AutoMateExample/ReminderViewModel.swift
mit
1
// // ReminderViewModel.swift // AutoMateExample // // Created by Joanna Bednarz on 10/03/2017. // Copyright © 2017 PGS Software. All rights reserved. // import EventKit // MARK: - ReminderViewModel struct ReminderViewModel { // MARK: Properties let title: String let startDate: Date? let completionDate: Date? let calendar: String let notes: String? var startDateString: String? { guard let date = startDate else { return nil } return DateFormatter.fullDate.string(from: date) } var completionDateString: String? { guard let date = completionDate else { return nil } return DateFormatter.fullDate.string(from: date) } fileprivate let reminderIdentifier: String // MARK: Initialization init(reminder: EKReminder) { reminderIdentifier = reminder.calendarItemIdentifier title = reminder.title startDate = reminder.startDateComponents?.date completionDate = reminder.completionDate calendar = reminder.calendar.title notes = reminder.notes } } func < (lhs: ReminderViewModel, rhs: ReminderViewModel) -> Bool { if let lhsStartDate = lhs.startDate, let rhsStartDate = rhs.startDate, lhsStartDate != rhsStartDate { return lhsStartDate < rhsStartDate } else if lhs.title != rhs.title { return lhs.title < rhs.title } return lhs.reminderIdentifier < rhs.reminderIdentifier }
1caf76ea02ae8ca2e9dd021aa48c1523
27.372549
105
0.683483
false
false
false
false
Zipabout/ZPBTTracker
refs/heads/master
Example/ManualTracking/ManualTracking/FourthViewController.swift
mit
1
// // FourthViewController.swift // ManualTracking // // Created by Siju Satheesachandran on 12/01/2017. // Copyright © 2017 Siju Satheesachandran. All rights reserved. // import UIKit import ZPBTTracker class FourthViewController: UIViewController,UITextFieldDelegate { @IBOutlet weak var txtFourthValue: UITextField! @IBOutlet weak var txtFourth: UITextField! override func viewDidLoad() { super.viewDidLoad() txtFourthValue.delegate = self txtFourth.delegate = self // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let session:ZPBTSessionManager = ZPBTSessionManager.sharedInstance() //track current page session.trackSession(inPage: NSStringFromClass(type(of: self))) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } @IBAction func sendEventFourth(_ sender: AnyObject) { txtFourthValue.resignFirstResponder() txtFourth.resignFirstResponder() let event:ZPBTEventManager = ZPBTEventManager.sharedInstance() var customParameter: [String: String] = [:] customParameter[txtFourth.text!] = txtFourthValue.text! event.trackEvent(inPage: NSStringFromClass(type(of: self)), customParameter: customParameter) } @IBOutlet weak var sendEventFourth: UIButton! override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
5c7d25e9916778a0073c350f46178cc5
30.030303
106
0.679688
false
false
false
false
zmian/xcore.swift
refs/heads/main
Sources/Xcore/SwiftUI/Components/PageView/StoryView/StoryView.swift
mit
1
// // Xcore // Copyright © 2021 Xcore // MIT license, see LICENSE file for details // import SwiftUI public struct StoryView<Page, Content, Background>: View where Page: Identifiable, Content: View, Background: View { @Environment(\.storyProgressIndicatorInsets) private var insets @ObservedObject private var storyTimer: StoryTimer private let pages: [Page] private let content: (Page) -> Content private let background: (Page) -> Background public var body: some View { ZStack(alignment: .top) { // Background if Background.self != Never.self { background(pages[Int(storyTimer.progress)]) .frame(maxWidth: .infinity) .ignoresSafeArea() .animation(.none) } // Tap to advance or rewind HStack(spacing: 0) { advanceView(isLeft: true) advanceView(isLeft: false) } .ignoresSafeArea() // Content content(pages[Int(storyTimer.progress)]) .frame(maxWidth: .infinity) // Progress Indicator progressIndicator } .onAppear(perform: storyTimer.start) .onDisappear(perform: storyTimer.stop) } private var progressIndicator: some View { HStack(spacing: 4) { ForEach(pages.indices) { index in StoryProgressIndicator(progress: storyTimer.progress(for: index)) } } .padding(insets) } private func advanceView(isLeft: Bool) -> some View { Rectangle() .foregroundColor(.clear) .contentShape(Rectangle()) .onTapGesture { storyTimer.advance(by: isLeft ? -1 : 1) } .onLongPressGesture(minimumDuration: 10, maximumDistance: 10) { storyTimer.pause() } onPressingChanged: { isPressing in if isPressing { storyTimer.pause() } else { storyTimer.resume() } } } /// A closure invoked on every cycle completion. /// /// - Parameter callback: The block to execute with a parameter indicating /// remaining number of cycles. public func onCycleComplete( _ callback: @escaping (_ remainingCycles: Count) -> Void ) -> Self { storyTimer.onCycleComplete = callback return self } } // MARK: - Inits extension StoryView { public init( interval: TimeInterval = 4, cycle: Count = .infinite, pages: [Page], @ViewBuilder content: @escaping (Page) -> Content, @ViewBuilder background: @escaping (Page) -> Background ) { self.storyTimer = .init( pagesCount: pages.count, interval: interval, cycle: cycle ) self.pages = pages self.content = content self.background = background } } extension StoryView where Background == Never { public init( interval: TimeInterval = 4, cycle: Count = .infinite, pages: [Page], @ViewBuilder content: @escaping (Page) -> Content ) { self.init( interval: interval, cycle: cycle, pages: pages, content: content, background: { _ in fatalError() } ) } } // MARK: - Previews struct StoryView_Previews: PreviewProvider { static var previews: some View { struct Colorful: Identifiable { let id: Int let color: Color } let pages = [ Colorful(id: 1, color: .green), Colorful(id: 2, color: .blue), Colorful(id: 3, color: .purple) ] return StoryView(cycle: .once, pages: pages) { page in VStack { Text("Page") Text("#") .baselineOffset(70) .font(.system(size: 100)) + Text("\(page.id)") .font(.system(size: 200)) } .frame(maxWidth: .infinity, maxHeight: .infinity) } background: { page in page.color } .onCycleComplete { count in print(count) } } }
f976b0d20dfb5810d3720599c27fa962
27.529412
116
0.526919
false
false
false
false
gouyz/GYZBaking
refs/heads/master
baking/Classes/Tool/3rdLib/ZLaunchAd/ZLaunchAdVC.swift
mit
1
// // ZLaunchAdVC.swift // ZLaunchAdDemo // // Created by mengqingzheng on 2017/4/5. // Copyright © 2017年 meng. All rights reserved. // import UIKit class ZLaunchAdVC: UIViewController { fileprivate var skipBtnConfig: SkipBtnModel = SkipBtnModel() /// viewController display 3s without ads fileprivate var defaultTime = 3 /// distance of your ad to window's bottom fileprivate var adViewBottomDistance: CGFloat = 100 /// transition type when change rootViewController fileprivate var transitionType: TransitionType = .fade /// ad's show time fileprivate var adDuration: Int = 0 /// original timer fileprivate var originalTimer: DispatchSourceTimer? /// ad timer fileprivate var dataTimer: DispatchSourceTimer? /// click adImg closure fileprivate var adImgViewClick: ZClosure? /// layer fileprivate var animationLayer: CAShapeLayer? fileprivate var rootViewController: UIViewController? /// the launch imageView fileprivate lazy var launchImageView: UIImageView = { let imgView = UIImageView(frame: UIScreen.main.bounds) imgView.image = self.getLaunchImage() return imgView }() /// your ad imgView fileprivate lazy var launchAdImgView: UIImageView = { let height = Z_SCREEN_HEIGHT - self.adViewBottomDistance let imgView = UIImageView(frame: CGRect(x: 0, y: 0, width: Z_SCREEN_WIDTH, height: height)) imgView.isUserInteractionEnabled = true imgView.alpha = 0.2 let tap = UITapGestureRecognizer.init(target: self, action: #selector(launchAdTapAction(sender:))) imgView.addGestureRecognizer(tap) return imgView }() /// the skip button fileprivate lazy var skipBtn: UIButton = { let button = UIButton(type: .custom) button.addTarget(self, action: #selector(skipBtnClick), for: .touchUpInside) return button }() /// tap your ad action @objc fileprivate func launchAdTapAction(sender: UITapGestureRecognizer) { dataTimer?.cancel() launchAdVCRemove { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.4, execute: { if self.adImgViewClick != nil { self.adImgViewClick!() } }) } } /// skipButton's action @objc fileprivate func skipBtnClick() { dataTimer?.cancel() launchAdVCRemove(completion: nil) } override func viewDidLoad() { super.viewDidLoad() view.addSubview(launchImageView) startTimer() } deinit { print("byebye") } } // MARK: - API extension ZLaunchAdVC { /// @discardableResult public func defaultDuration(_ defaultDuration: Int) -> Self { if defaultDuration >= 1 { self.defaultTime = defaultDuration } return self } /// set skip button's params @discardableResult public func configSkipBtn(_ config: (inout SkipBtnModel) -> Void) -> ZLaunchAdVC { config(&skipBtnConfig) return self } /// distance of adImg to launchImage's bottom @discardableResult public func adBottom(_ adViewBottom: CGFloat) -> Self { adViewBottomDistance = adViewBottom return self } /// set transition animation type @discardableResult public func transition(_ transitionType: TransitionType) -> Self { self.transitionType = transitionType return self } /// set app's rootViewController @discardableResult public func rootVC(_ rootViewController: UIViewController) -> Self { self.rootViewController = rootViewController return self } /// set img parametes /// /// - Parameters: /// - url: url /// - duration: display seconds /// - adImgViewClick: click ad & do something public func configNetImage(url: String, duration: Int, adImgViewClick: ZClosure?) { if url == "" { return } adDuration = duration < 1 ? 1 : duration view.addSubview(launchAdImgView) launchAdImgView.setImage(with: url, completion: { self.configSkipBtn() if self.originalTimer?.isCancelled == true { return } self.adStartTimer() UIView.animate(withDuration: 0.8, animations: { self.launchAdImgView.alpha = 1 }) }) self.adImgViewClick = adImgViewClick } /// set local image /// /// - Parameters: /// - image: pic name /// - duration: display seconds /// - adImgViewClick: do something click ad public func configLocalImage(image: UIImage?, duration: Int, adImgViewClick: ZClosure?) { if let image = image { adDuration = duration < 1 ? 1 : duration view.addSubview(launchAdImgView) launchAdImgView.image = image self.configSkipBtn() if self.originalTimer?.isCancelled == true { return } self.adStartTimer() UIView.animate(withDuration: 0.8, animations: { self.launchAdImgView.alpha = 1 }) } self.adImgViewClick = adImgViewClick } /// set local GIF /// /// - Parameters: /// - name: pic's name /// - duration: display seconds /// - adImgViewClick: do something when click ad public func configLocalGif(name: String, duration: Int, adImgViewClick: ZClosure?) { adDuration = duration < 1 ? 1 : duration view.addSubview(launchAdImgView) launchAdImgView.gifImage(named: name) { self.configSkipBtn() if self.originalTimer?.isCancelled == true { return } self.adStartTimer() UIView.animate(withDuration: 0.8, animations: { self.launchAdImgView.alpha = 1 }) } self.adImgViewClick = adImgViewClick } } // MARK: - configure skip button extension ZLaunchAdVC { /// setup skip button fileprivate func configSkipBtn() -> Void { skipBtn.removeFromSuperview() if animationLayer != nil { animationLayer?.removeFromSuperlayer() animationLayer = nil } if skipBtnConfig.skipBtnType != .none { skipBtn.backgroundColor = skipBtnConfig.backgroundColor skipBtn.setTitleColor(skipBtnConfig.titleColor, for: .normal) skipBtn.titleLabel?.font = skipBtnConfig.titleFont if skipBtnConfig.skipBtnType == .circle { skipBtn.frame = CGRect(x: 0, y: 0, width: skipBtnConfig.height, height: skipBtnConfig.height) skipBtn.layer.cornerRadius = skipBtnConfig.height*0.5 circleBtnAddLayer(strokeColor: skipBtnConfig.strokeColor, lineWidth: skipBtnConfig.lineWidth) } else { skipBtn.frame = CGRect(x: 0, y: 0, width: skipBtnConfig.width, height: skipBtnConfig.height) skipBtn.layer.cornerRadius = skipBtnConfig.cornerRadius skipBtn.layer.borderColor = skipBtnConfig.borderColor.cgColor skipBtn.layer.borderWidth = skipBtnConfig.borderWidth } skipBtn.center = CGPoint(x: skipBtnConfig.centerX, y: skipBtnConfig.centerY) skipBtn.setTitle(skipBtnConfig.skipBtnType == .timer ? "\(adDuration) 跳过" : "跳过", for: .normal) view.addSubview(skipBtn) } } /// circle button add animation fileprivate func circleBtnAddLayer(strokeColor: UIColor, lineWidth: CGFloat) { let bezierPath = UIBezierPath(ovalIn: skipBtn.bounds) animationLayer = CAShapeLayer() animationLayer?.path = bezierPath.cgPath animationLayer?.lineWidth = lineWidth animationLayer?.strokeColor = strokeColor.cgColor animationLayer?.fillColor = UIColor.clear.cgColor let animation = CABasicAnimation(keyPath: "strokeStart") animation.duration = Double(adDuration) animation.fromValue = 0 animation.toValue = 1 animationLayer?.add(animation, forKey: nil) skipBtn.layer.addSublayer(animationLayer!) } } // MARK: - ZLaunchAdVC remove extension ZLaunchAdVC { /// remove the launch viewController, change rootViewController or do something fileprivate func launchAdVCRemove(completion: (()->())?) { if self.originalTimer?.isCancelled == false { self.originalTimer?.cancel() } if self.dataTimer?.isCancelled == false { self.dataTimer?.cancel() } guard self.rootViewController != nil else { return } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.1, execute: { self.transitionAnimation() UIApplication.shared.keyWindow?.rootViewController = self.rootViewController guard completion != nil else { return } completion!() }) } /// add tansition animation to window when viewController will dealloc private func transitionAnimation() { let trans = CATransition() trans.duration = 0.5 switch transitionType { case .rippleEffect: trans.type = "rippleEffect" case .filpFromLeft: trans.type = "oglFlip" trans.subtype = kCATransitionFromLeft case .filpFromRight: trans.type = "oglFlip" trans.subtype = kCATransitionFromRight case .flipFromTop: trans.type = "oglFlip" trans.subtype = kCATransitionFromTop case .filpFromBottom: trans.type = "oglFlip" trans.subtype = kCATransitionFromBottom default: trans.type = "fade" } UIApplication.shared.keyWindow?.layer.add(trans, forKey: nil) } } //MARK: - GCD timer /// APP启动后开始默认定时器,默认3s /// 3s内若网络图片加载完成,默认定时器关闭,开启图片倒计时 /// 3s内若图片加载未完成,执行completion闭包 extension ZLaunchAdVC { /// start original timer fileprivate func startTimer() { originalTimer = DispatchSource.makeTimerSource(flags: [], queue:DispatchQueue.global()) originalTimer?.scheduleRepeating(deadline: DispatchTime.now(), interval: DispatchTimeInterval.seconds(1), leeway: DispatchTimeInterval.milliseconds(defaultTime)) originalTimer?.setEventHandler(handler: { printLog("original timer:" + "\(self.defaultTime)") if self.defaultTime == 0 { DispatchQueue.main.async { self.launchAdVCRemove(completion: nil) } } self.defaultTime -= 1 }) originalTimer?.resume() } /// start your ad's timer fileprivate func adStartTimer() { if self.originalTimer?.isCancelled == false { self.originalTimer?.cancel() } dataTimer = DispatchSource.makeTimerSource(flags: [], queue:DispatchQueue.global()) dataTimer?.scheduleRepeating(deadline: DispatchTime.now(), interval: DispatchTimeInterval.seconds(1), leeway: DispatchTimeInterval.milliseconds(adDuration)) dataTimer?.setEventHandler(handler: { printLog("ad timer:" + "\(self.adDuration)") DispatchQueue.main.async { self.skipBtn.setTitle(self.skipBtnConfig.skipBtnType == .timer ? "\(self.adDuration) 跳过" : "跳过", for: .normal) if self.adDuration == 0 { self.launchAdVCRemove(completion: nil) } self.adDuration -= 1 } }) dataTimer?.resume() } } // MARK: - StatusBar's Color /// You can set statusBar by General -> Deployment Info extension ZLaunchAdVC { override var prefersStatusBarHidden: Bool { return Bundle.main.infoDictionary?["UIStatusBarHidden"] as! Bool } override var preferredStatusBarStyle: UIStatusBarStyle { let str = Bundle.main.infoDictionary?["UIStatusBarStyle"] as! String return str.contains("Default") ? .default : .lightContent } } // MARK: - Get LaunchImage extension ZLaunchAdVC { fileprivate func getLaunchImage() -> UIImage { if (assetsLaunchImage() != nil) || (storyboardLaunchImage() != nil) { return assetsLaunchImage() == nil ? storyboardLaunchImage()! : assetsLaunchImage()! } return UIImage() } /// From Assets private func assetsLaunchImage() -> UIImage? { let size = UIScreen.main.bounds.size let orientation = "Portrait" // "Landscape" guard let launchImages = Bundle.main.infoDictionary?["UILaunchImages"] as? [[String: Any]] else { return nil } for dict in launchImages { let imageSize = CGSizeFromString(dict["UILaunchImageSize"] as! String) if __CGSizeEqualToSize(imageSize, size) && orientation == (dict["UILaunchImageOrientation"] as! String) { let launchImageName = dict["UILaunchImageName"] as! String let image = UIImage.init(named: launchImageName) return image } } return nil } /// Form LaunchScreen.Storyboard private func storyboardLaunchImage() -> UIImage? { guard let storyboardLaunchName = Bundle.main.infoDictionary?["UILaunchStoryboardName"] as? String, let launchVC = UIStoryboard.init(name: storyboardLaunchName, bundle: nil).instantiateInitialViewController() else { return nil } let view = launchVC.view view?.frame = UIScreen.main.bounds let image = viewConvertImage(view: view!) return image } /// view convert image private func viewConvertImage(view: UIView) -> UIImage? { let size = view.bounds.size UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) view.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
bc2154148c06d2381ac8ba910c02d871
37.0271
169
0.627637
false
true
false
false
traversals/luxaforus
refs/heads/master
Luxaforus/AppDelegate.swift
mit
1
// // AppDelegate.swift // Luxaforus // // Created by Mike Gouline on 30/6/17. // Copyright © 2017 Traversal.space. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, StateObserverDelegate, MenuControllerDelegate, LightControllerDelegate, SlackControllerDelegate { private let stateObserver = StateObserver() private let persistenceManager = PersistenceManager() private var notificationManager = NotificationManager() private let menuController: MenuController private let lightController: LightController private let slackController: SlackController private let updateController: UpdateController override init() { menuController = MenuController() lightController = LightController() slackController = SlackController(persistenceManager: persistenceManager) updateController = UpdateController(notificationManager: notificationManager, persistenceManager: persistenceManager) super.init() lightController(connectedChanged: LXDevice.sharedInstance()?.connected == true) menuController.delegate = self } func applicationDidFinishLaunching(_ aNotification: Notification) { // Check that Notification Center defaults can be inaccessible if !stateObserver.checkNotificationCenterAvailable() { let alert = NSAlert() alert.messageText = "This application requires the Notification Center, which cannot be found." alert.informativeText = "You must be running macOS before OS X 10.8, which is currently not supported." alert.alertStyle = .critical alert.addButton(withTitle: "OK") if alert.runModal() == NSApplication.ModalResponse.alertFirstButtonReturn { NSApplication.shared.terminate(self) } } menuController.update(imageState: MenuImageState.unknown) lightController.attach(delegate: self) lightController.update(transitionSpeed: 30) update(lightDimmed: persistenceManager.fetchDimmed(), updatePersistence: false, updateMenu: true) update(ignoreUpdates: persistenceManager.fetchIgnoreUpdates(), updatePersistence: false, updateMenu: true) notificationManager.attach() slackController.attach(delegate: self) stateObserver.attach(delegate: self) // Delay update check to avoid overwhelming user with information DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) { self.updateController.check(automatic: true) } } func applicationWillTerminate(_ aNotification: Notification) { stateObserver.detach() slackController.detach() lightController.detach() notificationManager.detach() } // MARK: - Actions private func update(lightDimmed isDimmed: Bool, updatePersistence: Bool, updateMenu: Bool) { if updatePersistence { persistenceManager.set(dimmed: isDimmed) } if updateMenu { menuController.update(dimState: isDimmed) } lightController.update(dimmed: isDimmed) } private func update(ignoreUpdates isIgnored: Bool, updatePersistence: Bool, updateMenu: Bool) { if updatePersistence { persistenceManager.set(ignoreUpdates: isIgnored) } if updateMenu { menuController.update(ignoreUpdates: isIgnored) } } private func update(slackLoggedIn isLoggedIn: Bool, updateMenu: Bool) { if updateMenu { menuController.update(slackLoggedIn: isLoggedIn) } } // MARK: - Delegates // StateObserverDelegate func stateObserver(valueChanged value: StateObserverValue) { let (color, imageState, snoozed) = { () -> (NSColor, MenuImageState, Bool?) in switch value { case .doNotDisturbOff: return (LightColor.available, .available, false) case .doNotDisturbOn: return (LightColor.busy, .busy, true) case .screenLocked, .detached: return (LightColor.locked, .unknown, nil) } }() lightController.update(color: color) menuController.update(imageState: imageState) if let snoozed = snoozed { slackController.update(snoozed: snoozed) } } // MenuControllerDelegate func menu(action theAction: MenuAction) -> Bool { switch theAction { case .opening: break case .dimState(let enabled): update(lightDimmed: enabled, updatePersistence: true, updateMenu: false) case .ignoreUpdatesState(let enabled): update(ignoreUpdates: enabled, updatePersistence: true, updateMenu: false) case .slackIntegration: if slackController.isLoggedIn { slackController.removeIntegration() } else { slackController.addIntegration() } case .setKeyboardShortcut: let alert = NSAlert() alert.messageText = "Open keyboard shortcuts?" alert.informativeText = "Select 'Mission Control' from the sidebar, enable 'Turn Do Not Disturb On/Off' and double-click the keyboard shortcut to set a new one." alert.alertStyle = .informational alert.addButton(withTitle: "Proceed") alert.addButton(withTitle: "Cancel") if alert.runModal() == NSApplication.ModalResponse.alertFirstButtonReturn { ActionHelper.preferencesKeyboardShortcuts() } case .checkForUpdates: updateController.check(automatic: false) case .quit: NSApplication.shared.terminate(self) } return true } // LightControllerDelegate func lightController(connectedChanged connected: Bool) { menuController.update(connectionState: connected ? .connected : .disconnected) } // SlackControllerDelegate func slackController(stateChanged loggedIn: Bool) { menuController.update(slackLoggedIn: loggedIn) } }
df16b02d000e204c78a8e194ec204a20
36.682635
173
0.651518
false
false
false
false
hengZhuo/DouYuZhiBo
refs/heads/master
swift-DYZB/swift-DYZB/Classes/Main/Model/AnchorModel.swift
mit
1
// // AnchorModel.swift // swift-DYZB // // Created by chenrin on 2016/11/16. // Copyright © 2016年 zhuoheng. All rights reserved. // import UIKit class AnchorModel: NSObject { //房间号 var room_id : Int = 0 //房间图片 var vertical_src = "" //判断是手机还是电脑直播 0:手机 1:电脑 var isVertical : Int = 0 //房间名字 var room_name = "" //主播昵称 var nickname = "" //观看人数 var online : Int = 0 //所在城市 var anchor_city = "" init(dict:[String : NSObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
514d5d7e245f6c2a7d1fc5ccadc12f5b
16.076923
72
0.540541
false
false
false
false
ResearchSuite/ResearchSuiteExtensions-iOS
refs/heads/master
source/Core/Classes/RSEnhancedInstructionStepViewController.swift
apache-2.0
1
// // RSEnhancedInstructionStepViewController.swift // Pods // // Created by James Kizer on 7/30/17. // // import UIKit import SwiftyGif open class RSEnhancedInstructionStepViewController: RSQuestionViewController { var stackView: UIStackView! override open func viewDidLoad() { super.viewDidLoad() guard let step = self.step as? RSEnhancedInstructionStep else { return } var stackedViews: [UIView] = [] if let image = step.image { let imageView = UIImageView(image: image) imageView.contentMode = .scaleAspectFit stackedViews.append(imageView) } else if let gifURL = step.gifURL { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.setGifFromURL(gifURL) stackedViews.append(imageView) } if let audioTitle = step.audioTitle, let path = Bundle.main.path(forResource: audioTitle, ofType: nil) { let url = URL(fileURLWithPath: path) if let audioPlayer = RSAudioPlayer(fileURL: url) { stackedViews.append(audioPlayer) } } let stackView = UIStackView(arrangedSubviews: stackedViews) stackView.distribution = .equalCentering stackView.frame = self.contentView.bounds self.stackView = stackView if step.moveForwardOnTap { let tapHandler = UITapGestureRecognizer(target: self, action: #selector(stackViewTapped(_:))) stackView.addGestureRecognizer(tapHandler) } self.contentView.addSubview(stackView) if let skipButtonText = step.skipButtonText { self.skipButton.isHidden = false self.setSkipButtonTitle(title: skipButtonText) } } @objc public func stackViewTapped(_ gestureRecognizer: UIGestureRecognizer) { self.goForward() } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.stackView.frame = self.contentView.bounds } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.stackView.frame = self.contentView.bounds } }
ed0cb4b8175e55a16da113c77c4d8e48
28.772152
105
0.614371
false
false
false
false
Tyrant2013/LeetCodePractice
refs/heads/master
LeetCodePractice/Easy/20_Valid_Parentheses.swift
mit
1
// // Valid_Parentheses.swift // LeetCodePractice // // Created by 庄晓伟 on 2018/2/9. // Copyright © 2018年 Zhuang Xiaowei. All rights reserved. // import UIKit class Valid_Parentheses: Solution { override func ExampleTest() { ["[", "()", "()[]{}", "(]", "([)]", "()[((()))]", "((", "{{)}", "(])"].forEach { str in print("input str: \(str), isValid: \(self.isValid(str))") } } func isValid(_ s: String) -> Bool { let strArray = s.map({ $0 }) var queue = [Character]() var ret = true for ch in strArray { if ch == "(" || ch == "[" || ch == "{" { queue.append(ch) } else { if queue.count == 0 { ret = false break } let popCh = queue.popLast() switch ch { case ")": ret = popCh! == "(" case "]": ret = popCh! == "[" case "}": ret = popCh! == "{" default: ret = false } if ret == false { queue.append(popCh!) break } } } return queue.count == 0 && ret } }
8360c5e0eee96855999f9fd23952c2c8
23.551724
69
0.332865
false
false
false
false
dreamsxin/swift
refs/heads/master
test/Constraints/function.swift
apache-2.0
2
// RUN: %target-parse-verify-swift func f0(_ x: Float) -> Float {} func f1(_ x: Float) -> Float {} func f2(_ x: @autoclosure () -> Float) {} var f : Float _ = f0(f0(f)) _ = f0(1) _ = f1(f1(f)) f2(f) f2(1.0) func call_lvalue(_ rhs: @autoclosure () -> Bool) -> Bool { return rhs() } // Function returns func weirdCast<T, U>(_ x: T) -> U {} func ff() -> (Int) -> (Float) { return weirdCast } // Block <-> function conversions var funct: (Int) -> Int = { $0 } var block: @convention(block) (Int) -> Int = funct funct = block block = funct // Application of implicitly unwrapped optional functions var optFunc: ((String) -> String)! = { $0 } var s: String = optFunc("hi") // <rdar://problem/17652759> Default arguments cause crash with tuple permutation func testArgumentShuffle(_ first: Int = 7, third: Int = 9) { } testArgumentShuffle(third: 1, 2) func rejectsAssertStringLiteral() { assert("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}} precondition("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}} } // <rdar://problem/22243469> QoI: Poor error message with throws, default arguments, & overloads func process(_ line: UInt = #line, _ fn: () -> Void) {} func process(_ line: UInt = #line) -> Int { return 0 } func dangerous() throws {} func test() { process { // expected-error {{invalid conversion from throwing function of type '() throws -> ()' to non-throwing function type '() -> Void'}} try dangerous() test() } } // <rdar://problem/19962010> QoI: argument label mismatches produce not-great diagnostic class A { func a(_ text:String) { } func a(_ text:String, something:Int?=nil) { } } A().a(text:"sometext") // expected-error{{extraneous argument label 'text:' in call}}{{7-12=}} // <rdar://problem/22451001> QoI: incorrect diagnostic when argument to print has the wrong type func r22451001() -> AnyObject {} print(r22451001(5)) // expected-error {{argument passed to call that takes no arguments}} // SR-590 Passing two parameters to a function that takes one argument of type Any crashes the compiler // SR-1028: Segmentation Fault: 11 when superclass init takes parameter of type 'Any' func sr590(_ x: Any) {} sr590(3,4) // expected-error {{extra argument in call}} sr590() // expected-error {{missing argument for parameter #1 in call}} // Make sure calling with structural tuples still works. sr590(()) sr590((1, 2))
a35a6a67d5e4328b3ef712421c185d04
28.317647
152
0.666533
false
false
false
false
softermii/ASSwiftContactBook
refs/heads/master
ContactBook/Controllers/ASContactPicker.swift
mit
2
// // ViewController.swift // ASContacts // // Created by Anton Stremovskiy on 6/9/17. // Copyright © 2017 áSoft. All rights reserved. // import UIKit import Contacts public enum SubtitleType: String { case email case phone case birthday case organization case job case message } open class ASContactPicker: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! var doneButton: UIBarButtonItem! public var didSelectContacts: ((_ selectedContacts: [Contact]) -> Void)? = nil public var didSelectSingleContact: ((_ selectedContact: Contact) -> Void)? = nil public var didSelectSinglePhoneNumber: ((_ selectedPhone: String) -> Void)? = nil var category = [String]() var contacts = [Contact]() { didSet { category = Array(Set(self.contacts.map { String($0.firstName.substring(to: 1).uppercased() ) })).sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending } DispatchQueue.main.async { self.tableView.reloadData() } } } var selectedContacts = [Contact]() { didSet { doneButton.isEnabled = selectedContacts.count > 0 ? true : false } } // MARK: - Settings public static var barColor = UIColor.coolBlue public static var indexColor = barColor public static var indexBackgroundColor = UIColor.lightText public static var cancelButtonTittle = "Cancel" public static var doneButtonTittle = "Done" public static var mainTitle = "Contacts" public static var subtitleType = SubtitleType.phone public static var multiSelection = true public static var shouldOpenContactDetail = false override open func viewDidLoad() { super.viewDidLoad() setupTableView() setupController() initButtons() fetchContacts() } convenience public init() { let bundle = Bundle(for: ASContactPicker.self) self.init(nibName: ASContactPicker.className, bundle: bundle) } convenience public init(subTitle: SubtitleType, shouldOpenContactDetail: Bool = false) { let bundle = Bundle(for: ASContactPicker.self) self.init(nibName: ASContactPicker.className, bundle: bundle) ASContactPicker.subtitleType = subTitle ASContactPicker.shouldOpenContactDetail = shouldOpenContactDetail } convenience public init(subTitle: SubtitleType, multipleSelection: Bool, barColor: UIColor = .coolBlue, shouldOpenContactDetail: Bool = false) { let bundle = Bundle(for: ASContactPicker.self) self.init(nibName: ASContactPicker.className, bundle: bundle) ASContactPicker.subtitleType = subTitle ASContactPicker.multiSelection = multipleSelection ASContactPicker.barColor = barColor ASContactPicker.shouldOpenContactDetail = shouldOpenContactDetail } private func fetchContacts() { ContactsData().getContactsAccess(success: { (success) in self.contacts = ContactsData().getAllContacts() }) { (error) in debugPrint(error.localizedDescription) } } private func setupController() { title = ASContactPicker.mainTitle navigationController?.navigationBar.barTintColor = ASContactPicker.barColor navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.systemFont(ofSize: 16, weight: UIFontWeightBold)] } fileprivate func initButtons() { let closeButton = UIBarButtonItem(title: ASContactPicker.cancelButtonTittle, style: .plain, target: self, action: #selector(ASContactPicker.close)) closeButton.tintColor = UIColor.white navigationItem.leftBarButtonItem = closeButton doneButton = UIBarButtonItem(title: ASContactPicker.doneButtonTittle, style: .plain, target: self, action: #selector(ASContactPicker.done)) doneButton.tintColor = UIColor.white doneButton.isEnabled = false navigationItem.rightBarButtonItem = doneButton } @objc private func close() { self.dismiss(animated: true, completion: nil) } @objc private func done() { self.dismiss(animated: true) { self.didSelectContacts?(self.selectedContacts) } } private func setupTableView() { let bundle = Bundle(for: ASContactPicker.self) tableView.register(UINib(nibName: ContactCell.className, bundle: bundle), forCellReuseIdentifier: ContactCell.className) tableView.tableFooterView = UIView() tableView.estimatedRowHeight = 44 tableView.rowHeight = UITableViewAutomaticDimension tableView.setContentOffset(CGPoint(x: 0, y: searchBar.frame.size.height), animated: false) tableView.sectionIndexColor = ASContactPicker.indexColor tableView.sectionIndexBackgroundColor = ASContactPicker.indexBackgroundColor } } extension ASContactPicker: UITableViewDataSource { public func numberOfSections(in tableView: UITableView) -> Int { return category.count } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contacts.filter { $0.firstName.substring(to: 1) == category[section] }.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let bundle = Bundle(for: ASContactPicker.self) let cell = tableView.dequeueReusableCell(withIdentifier: ContactCell.className, for: indexPath) as! ContactCell let contact = contacts.filter { $0.firstName.substring(to: 1) == category[indexPath.section]}[indexPath.row] cell.setupCell(contact: contact, subtitleType: ASContactPicker.subtitleType) cell.contactDetail = { contact in let detail = ContactDetailController(nibName: ContactDetailController.className, bundle: bundle) detail.contact = contact self.show(detail, sender: self) } return cell } } extension ASContactPicker: UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! ContactCell guard let contact = cell.contactData else { return } let bundle = Bundle(for: ASContactPicker.self) if ASContactPicker.multiSelection { if !selectedContacts.contains(contact) { selectedContacts.append(contact) cell.select.image = UIImage(named: "check", in: bundle, compatibleWith: nil) } else { selectedContacts = selectedContacts.filter { $0.contactId != contact.contactId } cell.select.image = UIImage(named: "uncheck", in: bundle, compatibleWith: nil) } } else { let detail = ContactDetailController(nibName: ContactDetailController.className, bundle: bundle) detail.contact = contact detail.delegate = self self.show(detail, sender: self) /*selectedContacts = selectedContacts.filter { $0.contactId != contact.contactId } self.dismiss(animated: true, completion: { self.didSelectSingleContact?(contact) })*/ } debugPrint("Selected \(contact.firstName, contact.lastName)") } public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return category[section] } public func sectionIndexTitles(for tableView: UITableView) -> [String]? { return category } } extension ASContactPicker: UISearchBarDelegate { public func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { searchBar.showsCancelButton = true return true } public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() searchBar.text = nil searchBar.showsCancelButton = false contacts = ContactsData().getAllContacts() } public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if !searchText.isEmpty { contacts = ContactsData().getAllContacts() let filteredContacts = contacts.filter { ($0.firstName.contains(searchText) || $0.lastName.contains(searchText)) } contacts = filteredContacts } else { searchBar.resignFirstResponder() contacts = ContactsData().getAllContacts() } } } extension ASContactPicker: ContactDetailControllerDelegate { func getPhone(_ phone: String) { self.dismiss(animated: true, completion: { self.didSelectSinglePhoneNumber?(phone) }) } }
e300209285d8264eb41b68aa7653be60
35.779528
155
0.647827
false
false
false
false
Quick/Nimble
refs/heads/main
Tests/NimbleTests/Helpers/utils.swift
apache-2.0
1
#if !os(WASI) import Dispatch #endif import Foundation @testable import Nimble import XCTest func failsWithErrorMessage(_ messages: [String], file: FileString = #file, line: UInt = #line, preferOriginalSourceLocation: Bool = false, closure: () throws -> Void) { var filePath = file var lineNumber = line let recorder = AssertionRecorder() withAssertionHandler(recorder, file: file, line: line, closure: closure) for msg in messages { var lastFailure: AssertionRecord? var foundFailureMessage = false for assertion in recorder.assertions where assertion.message.stringValue == msg && !assertion.success { lastFailure = assertion foundFailureMessage = true break } if foundFailureMessage { continue } if preferOriginalSourceLocation { if let failure = lastFailure { filePath = failure.location.file lineNumber = failure.location.line } } let message: String if let lastFailure = lastFailure { message = "Got failure message: \"\(lastFailure.message.stringValue)\", but expected \"\(msg)\"" } else { let knownFailures = recorder.assertions.filter { !$0.success }.map { $0.message.stringValue } let knownFailuresJoined = knownFailures.joined(separator: ", ") message = """ Expected error message (\(msg)), got (\(knownFailuresJoined)) Assertions Received: \(recorder.assertions) """ } NimbleAssertionHandler.assert(false, message: FailureMessage(stringValue: message), location: SourceLocation(file: filePath, line: lineNumber)) } } func failsWithErrorMessage(_ message: String, file: FileString = #file, line: UInt = #line, preferOriginalSourceLocation: Bool = false, closure: () throws -> Void) { failsWithErrorMessage( [message], file: file, line: line, preferOriginalSourceLocation: preferOriginalSourceLocation, closure: closure ) } func failsWithErrorMessageForNil(_ message: String, file: FileString = #file, line: UInt = #line, preferOriginalSourceLocation: Bool = false, closure: () throws -> Void) { failsWithErrorMessage("\(message) (use beNil() to match nils)", file: file, line: line, preferOriginalSourceLocation: preferOriginalSourceLocation, closure: closure) } func failsWithErrorMessage(_ messages: [String], file: FileString = #file, line: UInt = #line, preferOriginalSourceLocation: Bool = false, closure: () async throws -> Void) async { var filePath = file var lineNumber = line let recorder = AssertionRecorder() await withAssertionHandler(recorder, file: file, line: line, closure: closure) for msg in messages { var lastFailure: AssertionRecord? var foundFailureMessage = false for assertion in recorder.assertions where assertion.message.stringValue == msg && !assertion.success { lastFailure = assertion foundFailureMessage = true break } if foundFailureMessage { continue } if preferOriginalSourceLocation { if let failure = lastFailure { filePath = failure.location.file lineNumber = failure.location.line } } let message: String if let lastFailure = lastFailure { message = "Got failure message: \"\(lastFailure.message.stringValue)\", but expected \"\(msg)\"" } else { let knownFailures = recorder.assertions.filter { !$0.success }.map { $0.message.stringValue } let knownFailuresJoined = knownFailures.joined(separator: ", ") message = """ Expected error message (\(msg)), got (\(knownFailuresJoined)) Assertions Received: \(recorder.assertions) """ } NimbleAssertionHandler.assert(false, message: FailureMessage(stringValue: message), location: SourceLocation(file: filePath, line: lineNumber)) } } func failsWithErrorMessage(_ message: String, file: FileString = #file, line: UInt = #line, preferOriginalSourceLocation: Bool = false, closure: () async throws -> Void) async { await failsWithErrorMessage( [message], file: file, line: line, preferOriginalSourceLocation: preferOriginalSourceLocation, closure: closure ) } func failsWithErrorMessageForNil(_ message: String, file: FileString = #file, line: UInt = #line, preferOriginalSourceLocation: Bool = false, closure: () async throws -> Void) async { await failsWithErrorMessage("\(message) (use beNil() to match nils)", file: file, line: line, preferOriginalSourceLocation: preferOriginalSourceLocation, closure: closure) } @discardableResult func suppressErrors<T>(closure: () -> T) -> T { var output: T? let recorder = AssertionRecorder() withAssertionHandler(recorder) { output = closure() } return output! } func producesStatus<Exp: Expectation, T>(_ status: ExpectationStatus, file: FileString = #file, line: UInt = #line, closure: () -> Exp) where Exp.Value == T { let expectation = suppressErrors(closure: closure) expect(file: file, line: line, expectation.status).to(equal(status)) } #if !os(WASI) func deferToMainQueue(action: @escaping () -> Void) { DispatchQueue.main.async { Thread.sleep(forTimeInterval: 0.01) action() } } #endif #if canImport(Darwin) && !SWIFT_PACKAGE public class NimbleHelper: NSObject { @objc public class func expectFailureMessage(_ message: NSString, block: () -> Void, file: FileString, line: UInt) { failsWithErrorMessage(String(describing: message), file: file, line: line, preferOriginalSourceLocation: true, closure: block) } @objc public class func expectFailureMessages(_ messages: [NSString], block: () -> Void, file: FileString, line: UInt) { failsWithErrorMessage(messages.map({String(describing: $0)}), file: file, line: line, preferOriginalSourceLocation: true, closure: block) } @objc public class func expectFailureMessageForNil(_ message: NSString, block: () -> Void, file: FileString, line: UInt) { failsWithErrorMessageForNil(String(describing: message), file: file, line: line, preferOriginalSourceLocation: true, closure: block) } } #endif #if !os(WASI) extension Date { init(dateTimeString: String) { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" dateFormatter.locale = Locale(identifier: "en_US_POSIX") let date = dateFormatter.date(from: dateTimeString)! self.init(timeInterval: 0, since: date) } } extension NSDate { convenience init(dateTimeString: String) { let date = Date(dateTimeString: dateTimeString) self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate) } } #endif
186114b6a1ae6387690806346178eab5
37.484043
183
0.643262
false
false
false
false
Intel-tensorflow/tensorflow
refs/heads/master
tensorflow/lite/swift/Sources/Tensor.swift
apache-2.0
11
// Copyright 2018 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import TensorFlowLiteC /// An input or output tensor in a TensorFlow Lite graph. public struct Tensor: Equatable, Hashable { /// The name of the `Tensor`. public let name: String /// The data type of the `Tensor`. public let dataType: DataType /// The shape of the `Tensor`. public let shape: Shape /// The data of the `Tensor`. The data is created with copied memory content. See creating data /// from raw memory at https://developer.apple.com/documentation/foundation/data. public let data: Data /// The quantization parameters for the `Tensor` if using a quantized model. public let quantizationParameters: QuantizationParameters? /// Creates a new input or output `Tensor` instance. /// /// - Parameters: /// - name: The name of the `Tensor`. /// - dataType: The data type of the `Tensor`. /// - shape: The shape of the `Tensor`. /// - data: The data in the input `Tensor`. /// - quantizationParameters Parameters for the `Tensor` if using a quantized model. The default /// is `nil`. init( name: String, dataType: DataType, shape: Shape, data: Data, quantizationParameters: QuantizationParameters? = nil ) { self.name = name self.dataType = dataType self.shape = shape self.data = data self.quantizationParameters = quantizationParameters } } extension Tensor { /// The supported `Tensor` data types. public enum DataType: Equatable, Hashable { /// A boolean. case bool /// An 8-bit unsigned integer. case uInt8 /// A 16-bit signed integer. case int16 /// A 32-bit signed integer. case int32 /// A 64-bit signed integer. case int64 /// A 16-bit half precision floating point. case float16 /// A 32-bit single precision floating point. case float32 /// A 64-bit double precision floating point. case float64 /// Creates a new instance from the given `TfLiteType` or `nil` if the data type is unsupported /// or could not be determined because there was an error. /// /// - Parameter type: A data type for a tensor. init?(type: TfLiteType) { switch type { case kTfLiteBool: self = .bool case kTfLiteUInt8: self = .uInt8 case kTfLiteInt16: self = .int16 case kTfLiteInt32: self = .int32 case kTfLiteInt64: self = .int64 case kTfLiteFloat16: self = .float16 case kTfLiteFloat32: self = .float32 case kTfLiteFloat64: self = .float64 case kTfLiteNoType: fallthrough default: return nil } } } } extension Tensor { /// The shape of a `Tensor`. public struct Shape: Equatable, Hashable { /// The number of dimensions of the `Tensor`. public let rank: Int /// An array of dimensions for the `Tensor`. public let dimensions: [Int] /// An array of `Int32` dimensions for the `Tensor`. var int32Dimensions: [Int32] { return dimensions.map(Int32.init) } /// Creates a new instance with the given array of dimensions. /// /// - Parameters: /// - dimensions: Dimensions for the `Tensor`. public init(_ dimensions: [Int]) { self.rank = dimensions.count self.dimensions = dimensions } /// Creates a new instance with the given elements representing the dimensions. /// /// - Parameters: /// - elements: Dimensions for the `Tensor`. public init(_ elements: Int...) { self.init(elements) } } } extension Tensor.Shape: ExpressibleByArrayLiteral { /// Creates a new instance with the given array literal representing the dimensions. /// /// - Parameters: /// - arrayLiteral: Dimensions for the `Tensor`. public init(arrayLiteral: Int...) { self.init(arrayLiteral) } } /// A tensor's function level purpose: input or output. internal enum TensorType: String { case input case output }
e6831b873c2ce2470f33e5d51c39c153
28.346154
100
0.6564
false
false
false
false
tardieu/swift
refs/heads/master
test/IDE/print_ast_tc_decls.swift
apache-2.0
1
// RUN: rm -rf %t && mkdir -p %t // // Build swift modules this test depends on. // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/foo_swift_module.swift // // FIXME: BEGIN -enable-source-import hackaround // RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift // FIXME: END -enable-source-import hackaround // // This file should not have any syntax or type checker errors. // RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -typecheck -verify %s -F %S/Inputs/mock-sdk -disable-objc-attr-requires-foundation-module // // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=false -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_PRINT_AST -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_RW_PROP_GET_SET -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_2200 -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE_TYPE -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PREFER_TYPE_PRINTING -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt // // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=true -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_PRINT_AST -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_RW_PROP_GET_SET -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_2200 -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE_TYPEREPR -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PREFER_TYPE_REPR_PRINTING -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt // // RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t -F %S/Inputs/mock-sdk -disable-objc-attr-requires-foundation-module %s // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -module-to-print=print_ast_tc_decls -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_RW_PROP_NO_GET_SET -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_2200_DESERIALIZED -strict-whitespace < %t.printed.txt // FIXME: rdar://15167697 // FIXME: %FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PREFER_TYPE_REPR_PRINTING -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt // // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=SYNTHESIZE_SUGAR_ON_TYPES -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -fully-qualified-types-if-ambiguous=true -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_QUAL_IF_AMBIGUOUS -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=SYNTHESIZE_SUGAR_ON_TYPES -strict-whitespace < %t.printed.txt // FIXME: %FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt // FIXME: rdar://problem/19648117 Needs splitting objc parts out // XFAIL: linux import Bar import ObjectiveC import class Foo.FooClassBase import struct Foo.FooStruct1 import func Foo.fooFunc1 @_exported import FooHelper import foo_swift_module // FIXME: enum tests //import enum FooClangModule.FooEnum1 // PASS_COMMON: {{^}}import Bar{{$}} // PASS_COMMON: {{^}}import class Foo.FooClassBase{{$}} // PASS_COMMON: {{^}}import struct Foo.FooStruct1{{$}} // PASS_COMMON: {{^}}import func Foo.fooFunc1{{$}} // PASS_COMMON: {{^}}@_exported import FooHelper{{$}} // PASS_COMMON: {{^}}import foo_swift_module{{$}} //===--- //===--- Helper types. //===--- struct FooStruct {} class FooClass {} class BarClass {} protocol FooProtocol {} protocol BarProtocol {} protocol BazProtocol { func baz() } protocol QuxProtocol { associatedtype Qux } protocol SubFooProtocol : FooProtocol { } class FooProtocolImpl : FooProtocol {} class FooBarProtocolImpl : FooProtocol, BarProtocol {} class BazProtocolImpl : BazProtocol { func baz() {} } //===--- //===--- Basic smoketest. //===--- struct d0100_FooStruct { // PASS_COMMON-LABEL: {{^}}struct d0100_FooStruct {{{$}} var instanceVar1: Int = 0 // PASS_COMMON-NEXT: {{^}} var instanceVar1: Int{{$}} var computedProp1: Int { get { return 42 } } // PASS_COMMON-NEXT: {{^}} var computedProp1: Int { get }{{$}} func instanceFunc0() {} // PASS_COMMON-NEXT: {{^}} func instanceFunc0(){{$}} func instanceFunc1(a: Int) {} // PASS_COMMON-NEXT: {{^}} func instanceFunc1(a: Int){{$}} func instanceFunc2(a: Int, b: inout Double) {} // PASS_COMMON-NEXT: {{^}} func instanceFunc2(a: Int, b: inout Double){{$}} func instanceFunc3(a: Int, b: Double) { var a = a; a = 1; _ = a } // PASS_COMMON-NEXT: {{^}} func instanceFunc3(a: Int, b: Double){{$}} func instanceFuncWithDefaultArg1(a: Int = 0) {} // PASS_COMMON-NEXT: {{^}} func instanceFuncWithDefaultArg1(a: Int = default){{$}} func instanceFuncWithDefaultArg2(a: Int = 0, b: Double = 0) {} // PASS_COMMON-NEXT: {{^}} func instanceFuncWithDefaultArg2(a: Int = default, b: Double = default){{$}} func varargInstanceFunc0(v: Int...) {} // PASS_COMMON-NEXT: {{^}} func varargInstanceFunc0(v: Int...){{$}} func varargInstanceFunc1(a: Float, v: Int...) {} // PASS_COMMON-NEXT: {{^}} func varargInstanceFunc1(a: Float, v: Int...){{$}} func varargInstanceFunc2(a: Float, b: Double, v: Int...) {} // PASS_COMMON-NEXT: {{^}} func varargInstanceFunc2(a: Float, b: Double, v: Int...){{$}} func overloadedInstanceFunc1() -> Int { return 0; } // PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc1() -> Int{{$}} func overloadedInstanceFunc1() -> Double { return 0.0; } // PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc1() -> Double{{$}} func overloadedInstanceFunc2(x: Int) -> Int { return 0; } // PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc2(x: Int) -> Int{{$}} func overloadedInstanceFunc2(x: Double) -> Int { return 0; } // PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc2(x: Double) -> Int{{$}} func builderFunc1(a: Int) -> d0100_FooStruct { return d0100_FooStruct(); } // PASS_COMMON-NEXT: {{^}} func builderFunc1(a: Int) -> d0100_FooStruct{{$}} subscript(i: Int) -> Double { get { return Double(i) } } // PASS_COMMON-NEXT: {{^}} subscript(i: Int) -> Double { get }{{$}} subscript(i: Int, j: Int) -> Double { get { return Double(i + j) } } // PASS_COMMON-NEXT: {{^}} subscript(i: Int, j: Int) -> Double { get }{{$}} func bodyNameVoidFunc1(a: Int, b x: Float) {} // PASS_COMMON-NEXT: {{^}} func bodyNameVoidFunc1(a: Int, b x: Float){{$}} func bodyNameVoidFunc2(a: Int, b x: Float, c y: Double) {} // PASS_COMMON-NEXT: {{^}} func bodyNameVoidFunc2(a: Int, b x: Float, c y: Double){{$}} func bodyNameStringFunc1(a: Int, b x: Float) -> String { return "" } // PASS_COMMON-NEXT: {{^}} func bodyNameStringFunc1(a: Int, b x: Float) -> String{{$}} func bodyNameStringFunc2(a: Int, b x: Float, c y: Double) -> String { return "" } // PASS_COMMON-NEXT: {{^}} func bodyNameStringFunc2(a: Int, b x: Float, c y: Double) -> String{{$}} struct NestedStruct {} // PASS_COMMON-NEXT: {{^}} struct NestedStruct {{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} class NestedClass {} // PASS_COMMON-NEXT: {{^}} class NestedClass {{{$}} // PASS_COMMON-NEXT: {{^}} @objc deinit{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} enum NestedEnum {} // PASS_COMMON-NEXT: {{^}} enum NestedEnum {{{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} // Cannot declare a nested protocol. // protocol NestedProtocol {} typealias NestedTypealias = Int // PASS_COMMON-NEXT: {{^}} typealias NestedTypealias = Int{{$}} static var staticVar1: Int = 42 // PASS_COMMON-NEXT: {{^}} static var staticVar1: Int{{$}} static var computedStaticProp1: Int { get { return 42 } } // PASS_COMMON-NEXT: {{^}} static var computedStaticProp1: Int { get }{{$}} static func staticFunc0() {} // PASS_COMMON-NEXT: {{^}} static func staticFunc0(){{$}} static func staticFunc1(a: Int) {} // PASS_COMMON-NEXT: {{^}} static func staticFunc1(a: Int){{$}} static func overloadedStaticFunc1() -> Int { return 0 } // PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc1() -> Int{{$}} static func overloadedStaticFunc1() -> Double { return 0.0 } // PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc1() -> Double{{$}} static func overloadedStaticFunc2(x: Int) -> Int { return 0 } // PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc2(x: Int) -> Int{{$}} static func overloadedStaticFunc2(x: Double) -> Int { return 0 } // PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc2(x: Double) -> Int{{$}} } // PASS_COMMON-NEXT: {{^}} init(instanceVar1: Int){{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} extension d0100_FooStruct { // PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct {{{$}} var extProp: Int { get { return 42 } } // PASS_COMMON-NEXT: {{^}} var extProp: Int { get }{{$}} func extFunc0() {} // PASS_COMMON-NEXT: {{^}} func extFunc0(){{$}} static var extStaticProp: Int { get { return 42 } } // PASS_COMMON-NEXT: {{^}} static var extStaticProp: Int { get }{{$}} static func extStaticFunc0() {} // PASS_COMMON-NEXT: {{^}} static func extStaticFunc0(){{$}} struct ExtNestedStruct {} // PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct {{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} class ExtNestedClass {} // PASS_COMMON-NEXT: {{^}} class ExtNestedClass {{{$}} // PASS_COMMON-NEXT: {{^}} @objc deinit{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} enum ExtNestedEnum { case ExtEnumX(Int) } // PASS_COMMON-NEXT: {{^}} enum ExtNestedEnum {{{$}} // PASS_COMMON-NEXT: {{^}} case ExtEnumX(Int){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} typealias ExtNestedTypealias = Int // PASS_COMMON-NEXT: {{^}} typealias ExtNestedTypealias = Int{{$}} } // PASS_COMMON-NEXT: {{^}}}{{$}} extension d0100_FooStruct.NestedStruct { // PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct.NestedStruct {{{$}} struct ExtNestedStruct2 {} // PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct2 {{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} } extension d0100_FooStruct.ExtNestedStruct { // PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct.ExtNestedStruct {{{$}} struct ExtNestedStruct3 {} // PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct3 {{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} } // PASS_COMMON-NEXT: {{^}}}{{$}} var fooObject: d0100_FooStruct = d0100_FooStruct() // PASS_ONE_LINE-DAG: {{^}}var fooObject: d0100_FooStruct{{$}} struct d0110_ReadWriteProperties { // PASS_RW_PROP_GET_SET-LABEL: {{^}}struct d0110_ReadWriteProperties {{{$}} // PASS_RW_PROP_NO_GET_SET-LABEL: {{^}}struct d0110_ReadWriteProperties {{{$}} var computedProp1: Int { get { return 42 } set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp1: Int { get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp1: Int{{$}} subscript(i: Int) -> Int { get { return 42 } set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} subscript(i: Int) -> Int { get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} subscript(i: Int) -> Int{{$}} static var computedStaticProp1: Int { get { return 42 } set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} static var computedStaticProp1: Int { get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} static var computedStaticProp1: Int{{$}} var computedProp2: Int { mutating get { return 42 } set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp2: Int { mutating get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp2: Int { mutating get set }{{$}} var computedProp3: Int { get { return 42 } nonmutating set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp3: Int { get nonmutating set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp3: Int { get nonmutating set }{{$}} var computedProp4: Int { mutating get { return 42 } nonmutating set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp4: Int { mutating get nonmutating set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp4: Int { mutating get nonmutating set }{{$}} subscript(i: Float) -> Int { get { return 42 } nonmutating set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} subscript(i: Float) -> Int { get nonmutating set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} subscript(i: Float) -> Int { get nonmutating set }{{$}} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} init(){{$}} // PASS_RW_PROP_GET_SET-NEXT: {{^}}}{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} init(){{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}}}{{$}} extension d0110_ReadWriteProperties { // PASS_RW_PROP_GET_SET-LABEL: {{^}}extension d0110_ReadWriteProperties {{{$}} // PASS_RW_PROP_NO_GET_SET-LABEL: {{^}}extension d0110_ReadWriteProperties {{{$}} var extProp: Int { get { return 42 } set(v) {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} var extProp: Int { get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var extProp: Int{{$}} static var extStaticProp: Int { get { return 42 } set(v) {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} static var extStaticProp: Int { get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} static var extStaticProp: Int{{$}} } // PASS_RW_PROP_GET_SET-NEXT: {{^}}}{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}}}{{$}} class d0120_TestClassBase { // PASS_COMMON-LABEL: {{^}}class d0120_TestClassBase {{{$}} required init() {} // PASS_COMMON-NEXT: {{^}} required init(){{$}} // FIXME: Add these once we can SILGen them reasonable. // init?(fail: String) { } // init!(iuoFail: String) { } final func baseFunc1() {} // PASS_COMMON-NEXT: {{^}} final func baseFunc1(){{$}} func baseFunc2() {} // PASS_COMMON-NEXT: {{^}} func baseFunc2(){{$}} subscript(i: Int) -> Int { return 0 } // PASS_COMMON-NEXT: {{^}} subscript(i: Int) -> Int { get }{{$}} class var baseClassVar1: Int { return 0 } // PASS_COMMON-NEXT: {{^}} class var baseClassVar1: Int { get }{{$}} // FIXME: final class var not allowed to have storage, but static is? // final class var baseClassVar2: Int = 0 final class var baseClassVar3: Int { return 0 } // PASS_COMMON-NEXT: {{^}} final class var baseClassVar3: Int { get }{{$}} static var baseClassVar4: Int = 0 // PASS_COMMON-NEXT: {{^}} static var baseClassVar4: Int{{$}} static var baseClassVar5: Int { return 0 } // PASS_COMMON-NEXT: {{^}} static var baseClassVar5: Int { get }{{$}} class func baseClassFunc1() {} // PASS_COMMON-NEXT: {{^}} class func baseClassFunc1(){{$}} final class func baseClassFunc2() {} // PASS_COMMON-NEXT: {{^}} final class func baseClassFunc2(){{$}} static func baseClassFunc3() {} // PASS_COMMON-NEXT: {{^}} static func baseClassFunc3(){{$}} } class d0121_TestClassDerived : d0120_TestClassBase { // PASS_COMMON-LABEL: {{^}}class d0121_TestClassDerived : d0120_TestClassBase {{{$}} required init() { super.init() } // PASS_COMMON-NEXT: {{^}} required init(){{$}} final override func baseFunc2() {} // PASS_COMMON-NEXT: {{^}} {{(override |final )+}}func baseFunc2(){{$}} override final subscript(i: Int) -> Int { return 0 } // PASS_COMMON-NEXT: {{^}} override final subscript(i: Int) -> Int { get }{{$}} } protocol d0130_TestProtocol { // PASS_COMMON-LABEL: {{^}}protocol d0130_TestProtocol {{{$}} associatedtype NestedTypealias // PASS_COMMON-NEXT: {{^}} associatedtype NestedTypealias{{$}} var property1: Int { get } // PASS_COMMON-NEXT: {{^}} var property1: Int { get }{{$}} var property2: Int { get set } // PASS_COMMON-NEXT: {{^}} var property2: Int { get set }{{$}} func protocolFunc1() // PASS_COMMON-NEXT: {{^}} func protocolFunc1(){{$}} } @objc protocol d0140_TestObjCProtocol { // PASS_COMMON-LABEL: {{^}}@objc protocol d0140_TestObjCProtocol {{{$}} @objc optional var property1: Int { get } // PASS_COMMON-NEXT: {{^}} @objc optional var property1: Int { get }{{$}} @objc optional func protocolFunc1() // PASS_COMMON-NEXT: {{^}} @objc optional func protocolFunc1(){{$}} } protocol d0150_TestClassProtocol : class {} // PASS_COMMON-LABEL: {{^}}protocol d0150_TestClassProtocol : class {{{$}} @objc protocol d0151_TestClassProtocol {} // PASS_COMMON-LABEL: {{^}}@objc protocol d0151_TestClassProtocol {{{$}} class d0170_TestAvailability { // PASS_COMMON-LABEL: {{^}}class d0170_TestAvailability {{{$}} @available(*, unavailable) func f1() {} // PASS_COMMON-NEXT: {{^}} @available(*, unavailable){{$}} // PASS_COMMON-NEXT: {{^}} func f1(){{$}} @available(*, unavailable, message: "aaa \"bbb\" ccc\nddd\0eee") func f2() {} // PASS_COMMON-NEXT: {{^}} @available(*, unavailable, message: "aaa \"bbb\" ccc\nddd\0eee"){{$}} // PASS_COMMON-NEXT: {{^}} func f2(){{$}} @available(iOS, unavailable) @available(OSX, unavailable) func f3() {} // PASS_COMMON-NEXT: {{^}} @available(iOS, unavailable){{$}} // PASS_COMMON-NEXT: {{^}} @available(OSX, unavailable){{$}} // PASS_COMMON-NEXT: {{^}} func f3(){{$}} @available(iOS 8.0, OSX 10.10, *) func f4() {} // PASS_COMMON-NEXT: {{^}} @available(iOS 8.0, OSX 10.10, *){{$}} // PASS_COMMON-NEXT: {{^}} func f4(){{$}} // Convert long-form @available() to short form when possible. @available(iOS, introduced: 8.0) @available(OSX, introduced: 10.10) func f5() {} // PASS_COMMON-NEXT: {{^}} @available(iOS 8.0, OSX 10.10, *){{$}} // PASS_COMMON-NEXT: {{^}} func f5(){{$}} } @objc class d0180_TestIBAttrs { // PASS_COMMON-LABEL: {{^}}@objc class d0180_TestIBAttrs {{{$}} @IBAction func anAction(_: AnyObject) {} // PASS_COMMON-NEXT: {{^}} @IBAction @objc func anAction(_: AnyObject){{$}} @IBDesignable class ADesignableClass {} // PASS_COMMON-NEXT: {{^}} @IBDesignable class ADesignableClass {{{$}} } @objc class d0181_TestIBAttrs { // PASS_EXPLODE_PATTERN-LABEL: {{^}}@objc class d0181_TestIBAttrs {{{$}} @IBOutlet weak var anOutlet: d0181_TestIBAttrs! // PASS_EXPLODE_PATTERN-NEXT: {{^}} @IBOutlet @objc weak var anOutlet: @sil_weak d0181_TestIBAttrs!{{$}} @IBInspectable var inspectableProp: Int = 0 // PASS_EXPLODE_PATTERN-NEXT: {{^}} @IBInspectable @objc var inspectableProp: Int{{$}} @GKInspectable var inspectableProp2: Int = 0 // PASS_EXPLODE_PATTERN-NEXT: {{^}} @GKInspectable @objc var inspectableProp2: Int{{$}} } struct d0190_LetVarDecls { // PASS_PRINT_AST-LABEL: {{^}}struct d0190_LetVarDecls {{{$}} // PASS_PRINT_MODULE_INTERFACE-LABEL: {{^}}struct d0190_LetVarDecls {{{$}} let instanceVar1: Int = 0 // PASS_PRINT_AST-NEXT: {{^}} let instanceVar1: Int{{$}} // PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} let instanceVar1: Int{{$}} let instanceVar2 = 0 // PASS_PRINT_AST-NEXT: {{^}} let instanceVar2: Int{{$}} // PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} let instanceVar2: Int{{$}} static let staticVar1: Int = 42 // PASS_PRINT_AST-NEXT: {{^}} static let staticVar1: Int{{$}} // PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} static let staticVar1: Int{{$}} static let staticVar2 = 42 // FIXME: PRINTED_WITHOUT_TYPE // PASS_PRINT_AST-NEXT: {{^}} static let staticVar2: Int{{$}} // PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} static let staticVar2: Int{{$}} } struct d0200_EscapedIdentifiers { // PASS_COMMON-LABEL: {{^}}struct d0200_EscapedIdentifiers {{{$}} struct `struct` {} // PASS_COMMON-NEXT: {{^}} struct `struct` {{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} enum `enum` { case `case` } // PASS_COMMON-NEXT: {{^}} enum `enum` {{{$}} // PASS_COMMON-NEXT: {{^}} case `case`{{$}} // PASS_COMMON-NEXT: {{^}} static func ==(a: d0200_EscapedIdentifiers.`enum`, b: d0200_EscapedIdentifiers.`enum`) -> Bool // PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} class `class` {} // PASS_COMMON-NEXT: {{^}} class `class` {{{$}} // PASS_COMMON-NEXT: {{^}} @objc deinit{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} typealias `protocol` = `class` // PASS_ONE_LINE_TYPE-DAG: {{^}} typealias `protocol` = d0200_EscapedIdentifiers.`class`{{$}} // PASS_ONE_LINE_TYPEREPR-DAG: {{^}} typealias `protocol` = `class`{{$}} class `extension` : `class` {} // PASS_ONE_LINE_TYPE-DAG: {{^}} class `extension` : d0200_EscapedIdentifiers.`class` {{{$}} // PASS_ONE_LINE_TYPEREPR-DAG: {{^}} class `extension` : `class` {{{$}} // PASS_COMMON: {{^}} @objc deinit{{$}} // PASS_COMMON-NEXT: {{^}} {{(override )?}}init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} func `func`<`let`: `protocol`, `where`>( class: Int, struct: `protocol`, foo: `let`, bar: `where`) where `where` : `protocol` {} // PASS_COMMON-NEXT: {{^}} func `func`<`let`, `where`>(class: Int, struct: {{(d0200_EscapedIdentifiers.)?}}`protocol`, foo: `let`, bar: `where`) where `let` : {{(d0200_EscapedIdentifiers.)?}}`protocol`, `where` : {{(d0200_EscapedIdentifiers.)?}}`protocol`{{$}} var `var`: `struct` = `struct`() // PASS_COMMON-NEXT: {{^}} var `var`: {{(d0200_EscapedIdentifiers.)?}}`struct`{{$}} var tupleType: (`var`: Int, `let`: `struct`) // PASS_COMMON-NEXT: {{^}} var tupleType: (`var`: Int, `let`: {{(d0200_EscapedIdentifiers.)?}}`struct`){{$}} var accessors1: Int { get { return 0 } set(`let`) {} } // PASS_COMMON-NEXT: {{^}} var accessors1: Int{{( { get set })?}}{{$}} static func `static`(protocol: Int) {} // PASS_COMMON-NEXT: {{^}} static func `static`(protocol: Int){{$}} // PASS_COMMON-NEXT: {{^}} init(`var`: {{(d0200_EscapedIdentifiers.)?}}`struct`, tupleType: (`var`: Int, `let`: {{(d0200_EscapedIdentifiers.)?}}`struct`)){{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} } struct d0210_Qualifications { // PASS_QUAL_UNQUAL: {{^}}struct d0210_Qualifications {{{$}} // PASS_QUAL_IF_AMBIGUOUS: {{^}}struct d0210_Qualifications {{{$}} var propFromStdlib1: Int = 0 // PASS_QUAL_UNQUAL-NEXT: {{^}} var propFromStdlib1: Int{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} var propFromStdlib1: Int{{$}} var propFromSwift1: FooSwiftStruct = FooSwiftStruct() // PASS_QUAL_UNQUAL-NEXT: {{^}} var propFromSwift1: FooSwiftStruct{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} var propFromSwift1: foo_swift_module.FooSwiftStruct{{$}} var propFromClang1: FooStruct1 = FooStruct1(x: 0, y: 0.0) // PASS_QUAL_UNQUAL-NEXT: {{^}} var propFromClang1: FooStruct1{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} var propFromClang1: FooStruct1{{$}} func instanceFuncFromStdlib1(a: Int) -> Float { return 0.0 } // PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromStdlib1(a: Int) -> Float{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromStdlib1(a: Int) -> Float{{$}} func instanceFuncFromStdlib2(a: ObjCBool) {} // PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromStdlib2(a: ObjCBool){{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromStdlib2(a: ObjCBool){{$}} func instanceFuncFromSwift1(a: FooSwiftStruct) -> FooSwiftStruct { return FooSwiftStruct() } // PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromSwift1(a: FooSwiftStruct) -> FooSwiftStruct{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromSwift1(a: foo_swift_module.FooSwiftStruct) -> foo_swift_module.FooSwiftStruct{{$}} func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1 { return FooStruct1(x: 0, y: 0.0) } // PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1{{$}} } // FIXME: this should be printed reasonably in case we use // -prefer-type-repr=true. Either we should print the types we inferred, or we // should print the initializers. class d0250_ExplodePattern { // PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0250_ExplodePattern {{{$}} var instanceVar1 = 0 var instanceVar2 = 0.0 var instanceVar3 = "" // PASS_EXPLODE_PATTERN: {{^}} var instanceVar1: Int{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar2: Double{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar3: String{{$}} var instanceVar4 = FooStruct() var (instanceVar5, instanceVar6) = (FooStruct(), FooStruct()) var (instanceVar7, instanceVar8) = (FooStruct(), FooStruct()) var (instanceVar9, instanceVar10) : (FooStruct, FooStruct) = (FooStruct(), FooStruct()) final var (instanceVar11, instanceVar12) = (FooStruct(), FooStruct()) // PASS_EXPLODE_PATTERN: {{^}} var instanceVar4: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar5: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar6: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar7: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar8: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar9: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar10: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final var instanceVar11: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final var instanceVar12: FooStruct{{$}} let instanceLet1 = 0 let instanceLet2 = 0.0 let instanceLet3 = "" // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet1: Int{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet2: Double{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet3: String{{$}} let instanceLet4 = FooStruct() let (instanceLet5, instanceLet6) = (FooStruct(), FooStruct()) let (instanceLet7, instanceLet8) = (FooStruct(), FooStruct()) let (instanceLet9, instanceLet10) : (FooStruct, FooStruct) = (FooStruct(), FooStruct()) // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet4: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet5: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet6: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet7: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet8: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet9: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet10: FooStruct{{$}} } class d0260_ExplodePattern_TestClassBase { // PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0260_ExplodePattern_TestClassBase {{{$}} init() { baseProp1 = 0 } // PASS_EXPLODE_PATTERN-NEXT: {{^}} init(){{$}} final var baseProp1: Int // PASS_EXPLODE_PATTERN-NEXT: {{^}} final var baseProp1: Int{{$}} var baseProp2: Int { get { return 0 } set {} } // PASS_EXPLODE_PATTERN-NEXT: {{^}} var baseProp2: Int{{$}} } class d0261_ExplodePattern_TestClassDerived : d0260_ExplodePattern_TestClassBase { // PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0261_ExplodePattern_TestClassDerived : d0260_ExplodePattern_TestClassBase {{{$}} override final var baseProp2: Int { get { return 0 } set {} } // PASS_EXPLODE_PATTERN-NEXT: {{^}} override final var baseProp2: Int{{$}} } //===--- //===--- Inheritance list in structs. //===--- struct StructWithoutInheritance1 {} // PASS_ONE_LINE-DAG: {{^}}struct StructWithoutInheritance1 {{{$}} struct StructWithInheritance1 : FooProtocol {} // PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance1 : FooProtocol {{{$}} struct StructWithInheritance2 : FooProtocol, BarProtocol {} // PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance2 : FooProtocol, BarProtocol {{{$}} struct StructWithInheritance3 : QuxProtocol, SubFooProtocol { typealias Qux = Int } // PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}} //===--- //===--- Inheritance list in classes. //===--- class ClassWithoutInheritance1 {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithoutInheritance1 {{{$}} class ClassWithInheritance1 : FooProtocol {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance1 : FooProtocol {{{$}} class ClassWithInheritance2 : FooProtocol, BarProtocol {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance2 : FooProtocol, BarProtocol {{{$}} class ClassWithInheritance3 : FooClass {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance3 : FooClass {{{$}} class ClassWithInheritance4 : FooClass, FooProtocol {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance4 : FooClass, FooProtocol {{{$}} class ClassWithInheritance5 : FooClass, FooProtocol, BarProtocol {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance5 : FooClass, FooProtocol, BarProtocol {{{$}} class ClassWithInheritance6 : QuxProtocol, SubFooProtocol { typealias Qux = Int } // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance6 : QuxProtocol, SubFooProtocol {{{$}} //===--- //===--- Inheritance list in enums. //===--- enum EnumWithoutInheritance1 {} // PASS_ONE_LINE-DAG: {{^}}enum EnumWithoutInheritance1 {{{$}} enum EnumWithInheritance1 : FooProtocol {} // PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance1 : FooProtocol {{{$}} enum EnumWithInheritance2 : FooProtocol, BarProtocol {} // PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance2 : FooProtocol, BarProtocol {{{$}} enum EnumDeclWithUnderlyingType1 : Int { case X } // PASS_ONE_LINE-DAG: {{^}}enum EnumDeclWithUnderlyingType1 : Int {{{$}} enum EnumDeclWithUnderlyingType2 : Int, FooProtocol { case X } // PASS_ONE_LINE-DAG: {{^}}enum EnumDeclWithUnderlyingType2 : Int, FooProtocol {{{$}} enum EnumWithInheritance3 : QuxProtocol, SubFooProtocol { typealias Qux = Int } // PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}} //===--- //===--- Inheritance list in protocols. //===--- protocol ProtocolWithoutInheritance1 {} // PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithoutInheritance1 {{{$}} protocol ProtocolWithInheritance1 : FooProtocol {} // PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance1 : FooProtocol {{{$}} protocol ProtocolWithInheritance2 : FooProtocol, BarProtocol { } // PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance2 : FooProtocol, BarProtocol {{{$}} protocol ProtocolWithInheritance3 : QuxProtocol, SubFooProtocol { } // PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}} //===--- //===--- Inheritance list in extensions //===--- struct StructInherited { } // PASS_ONE_LINE-DAG: {{.*}}extension StructInherited : QuxProtocol, SubFooProtocol {{{$}} extension StructInherited : QuxProtocol, SubFooProtocol { typealias Qux = Int } //===--- //===--- Typealias printing. //===--- // Normal typealiases. typealias SimpleTypealias1 = FooProtocol // PASS_ONE_LINE-DAG: {{^}}typealias SimpleTypealias1 = FooProtocol{{$}} // Associated types. protocol AssociatedType1 { associatedtype AssociatedTypeDecl1 = Int // PASS_ONE_LINE-DAG: {{^}} associatedtype AssociatedTypeDecl1 = Int{{$}} associatedtype AssociatedTypeDecl2 : FooProtocol // PASS_ONE_LINE-DAG: {{^}} associatedtype AssociatedTypeDecl2 : FooProtocol{{$}} associatedtype AssociatedTypeDecl3 : FooProtocol, BarProtocol // PASS_ONE_LINE_TYPEREPR-DAG: {{^}} associatedtype AssociatedTypeDecl3 : FooProtocol, BarProtocol{{$}} } //===--- //===--- Variable declaration printing. //===--- var d0300_topLevelVar1: Int = 42 // PASS_COMMON: {{^}}var d0300_topLevelVar1: Int{{$}} // PASS_COMMON-NOT: d0300_topLevelVar1 var d0400_topLevelVar2: Int = 42 // PASS_COMMON: {{^}}var d0400_topLevelVar2: Int{{$}} // PASS_COMMON-NOT: d0400_topLevelVar2 var d0500_topLevelVar2: Int { get { return 42 } } // PASS_COMMON: {{^}}var d0500_topLevelVar2: Int { get }{{$}} // PASS_COMMON-NOT: d0500_topLevelVar2 class d0600_InClassVar1 { // PASS_O600-LABEL: d0600_InClassVar1 var instanceVar1: Int // PASS_COMMON: {{^}} var instanceVar1: Int{{$}} // PASS_COMMON-NOT: instanceVar1 var instanceVar2: Int = 42 // PASS_COMMON: {{^}} var instanceVar2: Int{{$}} // PASS_COMMON-NOT: instanceVar2 // FIXME: this is sometimes printed without a type, see PASS_EXPLODE_PATTERN. // FIXME: PRINTED_WITHOUT_TYPE var instanceVar3 = 42 // PASS_COMMON: {{^}} var instanceVar3 // PASS_COMMON-NOT: instanceVar3 var instanceVar4: Int { get { return 42 } } // PASS_COMMON: {{^}} var instanceVar4: Int { get }{{$}} // PASS_COMMON-NOT: instanceVar4 // FIXME: uncomment when we have static vars. // static var staticVar1: Int init() { instanceVar1 = 10 } } //===--- //===--- Subscript declaration printing. //===--- class d0700_InClassSubscript1 { // PASS_COMMON-LABEL: d0700_InClassSubscript1 subscript(i: Int) -> Int { get { return 42 } } subscript(index i: Float) -> Int { return 42 } class `class` {} subscript(x: Float) -> `class` { return `class`() } // PASS_COMMON: {{^}} subscript(i: Int) -> Int { get }{{$}} // PASS_COMMON: {{^}} subscript(index i: Float) -> Int { get }{{$}} // PASS_COMMON: {{^}} subscript(x: Float) -> {{.*}} { get }{{$}} // PASS_COMMON-NOT: subscript // PASS_ONE_LINE_TYPE: {{^}} subscript(x: Float) -> d0700_InClassSubscript1.`class` { get }{{$}} // PASS_ONE_LINE_TYPEREPR: {{^}} subscript(x: Float) -> `class` { get }{{$}} } // PASS_COMMON: {{^}}}{{$}} //===--- //===--- Constructor declaration printing. //===--- struct d0800_ExplicitConstructors1 { // PASS_COMMON-LABEL: d0800_ExplicitConstructors1 init() {} // PASS_COMMON: {{^}} init(){{$}} init(a: Int) {} // PASS_COMMON: {{^}} init(a: Int){{$}} } struct d0900_ExplicitConstructorsSelector1 { // PASS_COMMON-LABEL: d0900_ExplicitConstructorsSelector1 init(int a: Int) {} // PASS_COMMON: {{^}} init(int a: Int){{$}} init(int a: Int, andFloat b: Float) {} // PASS_COMMON: {{^}} init(int a: Int, andFloat b: Float){{$}} } struct d1000_ExplicitConstructorsSelector2 { // PASS_COMMON-LABEL: d1000_ExplicitConstructorsSelector2 init(noArgs _: ()) {} // PASS_COMMON: {{^}} init(noArgs _: ()){{$}} init(_ a: Int) {} // PASS_COMMON: {{^}} init(_ a: Int){{$}} init(_ a: Int, withFloat b: Float) {} // PASS_COMMON: {{^}} init(_ a: Int, withFloat b: Float){{$}} init(int a: Int, _ b: Float) {} // PASS_COMMON: {{^}} init(int a: Int, _ b: Float){{$}} } //===--- //===--- Destructor declaration printing. //===--- class d1100_ExplicitDestructor1 { // PASS_COMMON-LABEL: d1100_ExplicitDestructor1 deinit {} // PASS_COMMON: {{^}} @objc deinit{{$}} } //===--- //===--- Enum declaration printing. //===--- enum d2000_EnumDecl1 { case ED1_First case ED1_Second } // PASS_COMMON: {{^}}enum d2000_EnumDecl1 {{{$}} // PASS_COMMON-NEXT: {{^}} case ED1_First{{$}} // PASS_COMMON-NEXT: {{^}} case ED1_Second{{$}} // PASS_COMMON-NEXT: {{^}} static func ==(a: d2000_EnumDecl1, b: d2000_EnumDecl1) -> Bool // PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} enum d2100_EnumDecl2 { case ED2_A(Int) case ED2_B(Float) case ED2_C(Int, Float) case ED2_D(x: Int, y: Float) case ED2_E(x: Int, y: (Float, Double)) case ED2_F(x: Int, (y: Float, z: Double)) } // PASS_COMMON: {{^}}enum d2100_EnumDecl2 {{{$}} // PASS_COMMON-NEXT: {{^}} case ED2_A(Int){{$}} // PASS_COMMON-NEXT: {{^}} case ED2_B(Float){{$}} // PASS_COMMON-NEXT: {{^}} case ED2_C(Int, Float){{$}} // PASS_COMMON-NEXT: {{^}} case ED2_D(x: Int, y: Float){{$}} // PASS_COMMON-NEXT: {{^}} case ED2_E(x: Int, y: (Float, Double)){{$}} // PASS_COMMON-NEXT: {{^}} case ED2_F(x: Int, (y: Float, z: Double)){{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} enum d2200_EnumDecl3 { case ED3_A, ED3_B case ED3_C(Int), ED3_D case ED3_E, ED3_F(Int) case ED3_G(Int), ED3_H(Int) case ED3_I(Int), ED3_J(Int), ED3_K } // PASS_2200: {{^}}enum d2200_EnumDecl3 {{{$}} // PASS_2200-NEXT: {{^}} case ED3_A, ED3_B{{$}} // PASS_2200-NEXT: {{^}} case ED3_C(Int), ED3_D{{$}} // PASS_2200-NEXT: {{^}} case ED3_E, ED3_F(Int){{$}} // PASS_2200-NEXT: {{^}} case ED3_G(Int), ED3_H(Int){{$}} // PASS_2200-NEXT: {{^}} case ED3_I(Int), ED3_J(Int), ED3_K{{$}} // PASS_2200-NEXT: {{^}}}{{$}} // PASS_2200_DESERIALIZED: {{^}}enum d2200_EnumDecl3 {{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_A{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_B{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_C(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_D{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_E{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_F(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_G(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_H(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_I(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_J(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_K{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}}}{{$}} enum d2300_EnumDeclWithValues1 : Int { case EDV2_First = 10 case EDV2_Second } // PASS_COMMON: {{^}}enum d2300_EnumDeclWithValues1 : Int {{{$}} // PASS_COMMON-NEXT: {{^}} case EDV2_First{{$}} // PASS_COMMON-NEXT: {{^}} case EDV2_Second{{$}} // PASS_COMMON-NEXT: {{^}} typealias RawValue = Int // PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}} // PASS_COMMON-NEXT: {{^}} init?(rawValue: Int){{$}} // PASS_COMMON-NEXT: {{^}} var rawValue: Int { get }{{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} enum d2400_EnumDeclWithValues2 : Double { case EDV3_First = 10 case EDV3_Second } // PASS_COMMON: {{^}}enum d2400_EnumDeclWithValues2 : Double {{{$}} // PASS_COMMON-NEXT: {{^}} case EDV3_First{{$}} // PASS_COMMON-NEXT: {{^}} case EDV3_Second{{$}} // PASS_COMMON-NEXT: {{^}} typealias RawValue = Double // PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}} // PASS_COMMON-NEXT: {{^}} init?(rawValue: Double){{$}} // PASS_COMMON-NEXT: {{^}} var rawValue: Double { get }{{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} //===--- //===--- Custom operator printing. //===--- postfix operator <*> // PASS_2500-LABEL: {{^}}postfix operator <*>{{$}} protocol d2600_ProtocolWithOperator1 { static postfix func <*>(_: Self) } // PASS_2500: {{^}}protocol d2600_ProtocolWithOperator1 {{{$}} // PASS_2500-NEXT: {{^}} postfix static func <*>(_: Self){{$}} // PASS_2500-NEXT: {{^}}}{{$}} struct d2601_TestAssignment {} infix operator %%% func %%%(lhs: inout d2601_TestAssignment, rhs: d2601_TestAssignment) -> Int { return 0 } // PASS_2500-LABEL: {{^}}infix operator %%%{{$}} // PASS_2500: {{^}}func %%%(lhs: inout d2601_TestAssignment, rhs: d2601_TestAssignment) -> Int{{$}} precedencegroup BoringPrecedence { // PASS_2500-LABEL: {{^}}precedencegroup BoringPrecedence {{{$}} associativity: left // PASS_2500-NEXT: {{^}} associativity: left{{$}} higherThan: AssignmentPrecedence // PASS_2500-NEXT: {{^}} higherThan: AssignmentPrecedence{{$}} // PASS_2500-NOT: assignment // PASS_2500-NOT: lowerThan } precedencegroup ReallyBoringPrecedence { // PASS_2500-LABEL: {{^}}precedencegroup ReallyBoringPrecedence {{{$}} associativity: right // PASS_2500-NEXT: {{^}} associativity: right{{$}} // PASS_2500-NOT: higherThan // PASS_2500-NOT: lowerThan // PASS_2500-NOT: assignment } precedencegroup BoringAssignmentPrecedence { // PASS_2500-LABEL: {{^}}precedencegroup BoringAssignmentPrecedence {{{$}} lowerThan: AssignmentPrecedence assignment: true // PASS_2500-NEXT: {{^}} assignment: true{{$}} // PASS_2500-NEXT: {{^}} lowerThan: AssignmentPrecedence{{$}} // PASS_2500-NOT: associativity // PASS_2500-NOT: higherThan } // PASS_2500: {{^}}}{{$}} //===--- //===--- Printing of deduced associated types. //===--- protocol d2700_ProtocolWithAssociatedType1 { associatedtype TA1 func returnsTA1() -> TA1 } // PREFER_TYPE_PRINTING: {{^}}protocol d2700_ProtocolWithAssociatedType1 {{{$}} // PREFER_TYPE_PRINTING-NEXT: {{^}} associatedtype TA1{{$}} // PREFER_TYPE_PRINTING-NEXT: {{^}} func returnsTA1() -> Self.TA1{{$}} // PREFER_TYPE_PRINTING-NEXT: {{^}}}{{$}} // PREFER_TYPEREPR_PRINTING: {{^}}protocol d2700_ProtocolWithAssociatedType1 {{{$}} // PREFER_TYPEREPR_PRINTING-NEXT: {{^}} associatedtype TA1{{$}} // PREFER_TYPEREPR_PRINTING-NEXT: {{^}} func returnsTA1() -> TA1{{$}} // PREFER_TYPEREPR_PRINTING-NEXT: {{^}}}{{$}} struct d2800_ProtocolWithAssociatedType1Impl : d2700_ProtocolWithAssociatedType1 { func returnsTA1() -> Int { return 42 } } // PASS_COMMON: {{^}}struct d2800_ProtocolWithAssociatedType1Impl : d2700_ProtocolWithAssociatedType1 {{{$}} // PASS_COMMON-NEXT: {{^}} func returnsTA1() -> Int{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} typealias TA1 = Int // PASS_COMMON-NEXT: {{^}}}{{$}} //===--- //===--- Generic parameter list printing. //===--- struct GenericParams1< StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : FooProtocol & BarProtocol, StructGenericBaz> { // PASS_ONE_LINE_TYPE-DAG: {{^}}struct GenericParams1<StructGenericFoo, StructGenericFooX, StructGenericBar, StructGenericBaz> where StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : BarProtocol, StructGenericBar : FooProtocol {{{$}} // PASS_ONE_LINE_TYPEREPR-DAG: {{^}}struct GenericParams1<StructGenericFoo, StructGenericFooX, StructGenericBar, StructGenericBaz> where StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : BarProtocol, StructGenericBar : FooProtocol {{{$}} init< GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : FooProtocol & BarProtocol, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) {} // PASS_ONE_LINE_TYPE-DAG: {{^}} init<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}} // FIXME: in protocol compositions protocols are listed in reverse order. // // PASS_ONE_LINE_TYPEREPR-DAG: {{^}} init<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}} func genericParams1< GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : FooProtocol & BarProtocol, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) {} // PASS_ONE_LINE_TYPE-DAG: {{^}} func genericParams1<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}} // FIXME: in protocol compositions protocols are listed in reverse order. // // PASS_ONE_LINE_TYPEREPR-DAG: {{^}} func genericParams1<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}} } struct GenericParams2<T : FooProtocol> where T : BarProtocol {} // PASS_ONE_LINE-DAG: {{^}}struct GenericParams2<T> where T : BarProtocol, T : FooProtocol {{{$}} struct GenericParams3<T : FooProtocol> where T : BarProtocol, T : QuxProtocol {} // PASS_ONE_LINE-DAG: {{^}}struct GenericParams3<T> where T : BarProtocol, T : FooProtocol, T : QuxProtocol {{{$}} struct GenericParams4<T : QuxProtocol> where T.Qux : FooProtocol {} // PASS_ONE_LINE-DAG: {{^}}struct GenericParams4<T> where T : QuxProtocol, T.Qux : FooProtocol {{{$}} struct GenericParams5<T : QuxProtocol> where T.Qux : FooProtocol & BarProtocol {} // PREFER_TYPE_PRINTING: {{^}}struct GenericParams5<T> where T : QuxProtocol, T.Qux : BarProtocol, T.Qux : FooProtocol {{{$}} // PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams5<T> where T : QuxProtocol, T.Qux : BarProtocol, T.Qux : FooProtocol {{{$}} struct GenericParams6<T : QuxProtocol, U : QuxProtocol> where T.Qux == U.Qux {} // PREFER_TYPE_PRINTING: {{^}}struct GenericParams6<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux {{{$}} // PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams6<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux {{{$}} struct GenericParams7<T : QuxProtocol, U : QuxProtocol> where T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux {} // PREFER_TYPE_PRINTING: {{^}}struct GenericParams7<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux {{{$}} // PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams7<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux {{{$}} //===--- //===--- Tupe sugar for library types. //===--- struct d2900_TypeSugar1 { // PASS_COMMON-LABEL: {{^}}struct d2900_TypeSugar1 {{{$}} // SYNTHESIZE_SUGAR_ON_TYPES-LABEL: {{^}}struct d2900_TypeSugar1 {{{$}} func f1(x: [Int]) {} // PASS_COMMON-NEXT: {{^}} func f1(x: [Int]){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f1(x: [Int]){{$}} func f2(x: Array<Int>) {} // PASS_COMMON-NEXT: {{^}} func f2(x: Array<Int>){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f2(x: [Int]){{$}} func f3(x: Int?) {} // PASS_COMMON-NEXT: {{^}} func f3(x: Int?){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f3(x: Int?){{$}} func f4(x: Optional<Int>) {} // PASS_COMMON-NEXT: {{^}} func f4(x: Optional<Int>){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f4(x: Int?){{$}} func f5(x: [Int]...) {} // PASS_COMMON-NEXT: {{^}} func f5(x: [Int]...){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f5(x: [Int]...){{$}} func f6(x: Array<Int>...) {} // PASS_COMMON-NEXT: {{^}} func f6(x: Array<Int>...){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f6(x: [Int]...){{$}} func f7(x: [Int : Int]...) {} // PASS_COMMON-NEXT: {{^}} func f7(x: [Int : Int]...){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f7(x: [Int : Int]...){{$}} func f8(x: Dictionary<String, Int>...) {} // PASS_COMMON-NEXT: {{^}} func f8(x: Dictionary<String, Int>...){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f8(x: [String : Int]...){{$}} } // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} // @discardableResult attribute public struct DiscardableThingy { // PASS_PRINT_AST: @discardableResult // PASS_PRINT_AST-NEXT: public init() @discardableResult public init() {} // PASS_PRINT_AST: @discardableResult // PASS_PRINT_AST-NEXT: public func useless() -> Int @discardableResult public func useless() -> Int { return 0 } } // Parameter Attributes. // <rdar://problem/19775868> Swift 1.2b1: Header gen puts @autoclosure in the wrong place // PASS_PRINT_AST: public func ParamAttrs1(a: @autoclosure () -> ()) public func ParamAttrs1(a : @autoclosure () -> ()) { a() } // PASS_PRINT_AST: public func ParamAttrs2(a: @autoclosure @escaping () -> ()) public func ParamAttrs2(a : @autoclosure @escaping () -> ()) { a() } // PASS_PRINT_AST: public func ParamAttrs3(a: () -> ()) public func ParamAttrs3(a : () -> ()) { a() } // PASS_PRINT_AST: public func ParamAttrs4(a: @escaping () -> ()) public func ParamAttrs4(a : @escaping () -> ()) { a() } // Setter // PASS_PRINT_AST: class FooClassComputed { class FooClassComputed { // PASS_PRINT_AST: var stored: (((Int) -> Int) -> Int)? var stored : (((Int) -> Int) -> Int)? = nil // PASS_PRINT_AST: var computed: ((Int) -> Int) -> Int { get set } var computed : ((Int) -> Int) -> Int { get { return stored! } set { stored = newValue } } // PASS_PRINT_AST: } } // Protocol extensions protocol ProtocolToExtend { associatedtype Assoc } extension ProtocolToExtend where Self.Assoc == Int {} // PREFER_TYPE_REPR_PRINTING: extension ProtocolToExtend where Self.Assoc == Int { #if true #elseif false #else #endif // PASS_PRINT_AST: #if // PASS_PRINT_AST: #elseif // PASS_PRINT_AST: #else // PASS_PRINT_AST: #endif public struct MyPair<A, B> { var a: A, b: B } public typealias MyPairI<B> = MyPair<Int, B> // PASS_PRINT_AST: public typealias MyPairI<B> = MyPair<Int, B> public typealias MyPairAlias<T, U> = MyPair<T, U> // PASS_PRINT_AST: public typealias MyPairAlias<T, U> = MyPair<T, U>
190d84e9a75fe107ca89fb7f1a22211e
37.208767
364
0.642964
false
false
false
false
DesenvolvimentoSwift/Taster
refs/heads/master
Taster/ShowLocationViewController.swift
mit
1
// // ShowLocationViewController.swift // pt.fca.Taster // // © 2016 Luis Marcelino e Catarina Silva // Desenvolvimento em Swift para iOS // FCA - Editora de Informática // import UIKit import MapKit class ShowLocationViewController: UIViewController, MKMapViewDelegate { var food:Food? // var annotation = MKPointAnnotation() let locationManager = CLLocationManager () @IBOutlet weak var map: MKMapView! @IBAction func cancelAction(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } @IBAction func navigateAction(_ sender: UIButton) { if let loc = food?.location { locationManager.startUpdatingLocation() let latituteFood:CLLocationDegrees = loc.latitude let longituteFood:CLLocationDegrees = loc.longitude let coordinate = CLLocationCoordinate2DMake(latituteFood, longituteFood) let placemark : MKPlacemark = MKPlacemark(coordinate: coordinate, addressDictionary:nil) let mapItem:MKMapItem = MKMapItem(placemark: placemark) mapItem.name = food!.name let launchOptions:NSDictionary = NSDictionary(object: MKLaunchOptionsDirectionsModeDriving, forKey: MKLaunchOptionsDirectionsModeKey as NSCopying) let currentLocationMapItem:MKMapItem = MKMapItem.forCurrentLocation() MKMapItem.openMaps(with: [currentLocationMapItem, mapItem], launchOptions: launchOptions as? [String : AnyObject]) } } override func viewDidLoad() { super.viewDidLoad() map.delegate = self map.showsUserLocation = true // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(_ animated: Bool) { if let loc = food?.location { showLocation(loc) } //Esta parte deixou de ser precisa, pois é feita logo no insert else if let local = food?.local { let geocoder = CLGeocoder() geocoder.geocodeAddressString(local, completionHandler: { (placemarks, error) in self.food?.location = placemarks?.first?.location?.coordinate if let loc = self.food?.location { self.showLocation(loc) } }) } else { let alertController = UIAlertController(title: "Error locating food.", message:"No location defined." , preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) present(alertController, animated: true, completion: nil) } } func showLocation (_ loc:CLLocationCoordinate2D) { var pin:CustomPin map.setRegion(MKCoordinateRegionMake(loc, MKCoordinateSpanMake(0.1, 0.1)), animated: true) pin = CustomPin(coordinate: loc, food:food!, title: food!.name, subtitle: " ") map.addAnnotation(pin) GeonamesClient.findNearbyWikipedia(loc) { (geoWiki) in if geoWiki != nil { OperationQueue.main.addOperation({ self.showNearbyWikipedia(geoWiki!) }) } } GeonamesClient.findNearbyPOI(loc, completionHandler: { (POIs) in if POIs != nil { self.showNearbyPOI(POIs!) } }) } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let identifier = "identifier" var annotationView:MKPinAnnotationView? if annotation.isKind(of: CustomPin.self) { annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView if annotationView == nil { annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) annotationView!.canShowCallout = true annotationView!.pinTintColor = UIColor.purple } else { annotationView!.annotation = annotation } return annotationView } else if annotation.isKind(of: WikipediaPin.self) { annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "wikiPin") as? MKPinAnnotationView if annotationView == nil { annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "wikiPin") annotationView!.canShowCallout = true annotationView!.pinTintColor = UIColor.green } else { annotationView!.annotation = annotation } return annotationView } return nil } func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { if let wikiPin = view.annotation as? WikipediaPin { if let url = wikiPin.geoWiki.url { UIApplication.shared.openURL(url as URL) } } } func showNearbyWikipedia (_ wikiEntries : [GeonamesWikipedia]) { for entry in wikiEntries { let wikiPin = WikipediaPin(geoWiki: entry) map.addAnnotation(wikiPin) } } func showNearbyPOI (_ poiEntries : [GeonamesPOI]) { for entry in poiEntries { let annotation = MKPointAnnotation() annotation.coordinate = entry.coordinate annotation.title = entry.name annotation.subtitle = entry.typeName map.addAnnotation(annotation) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
d8a0024c3d6937f4965fd50642ab5e60
34.627778
161
0.602058
false
false
false
false
SwiftTools/Switt
refs/heads/master
SwittTests/UnitTests/Grammar/LexicalAnalysis/Parser/TokenParser/TokenParsers/AlternativesTokenParserTests.swift
mit
1
import Quick import Nimble @testable import Switt private class Helper { static func parser(rules rules: [ParserRule]) -> TokenParser { let parser = AlternativesTokenParser( rules: rules, tokenParserFactory: TokenParserFactoryImpl( parserRules: ParserRules() ) ) return parser } } class AlternativesTokenParserTests: QuickSpec { override func spec() { describe("AlternativesTokenParser") { it("") { let stream = TokenStreamHelper.tokenStream([ "a" ]) let parser = Helper.parser( rules: [ ParserRule.Terminal(terminal: "a"), ParserRule.Terminal(terminal: "b") ] ) let result = parser.parse(stream) let tokenStrings = result?.map { tree in tree.token?.string } expect(tokenStrings).to(equal(["a"])) expect(stream.index).to(equal(1)) } it("") { let stream = TokenStreamHelper.tokenStream([ "a", "b" ]) let parser = Helper.parser( rules: [ ParserRule.Terminal(terminal: "a"), ParserRule.Terminal(terminal: "b") ] ) let result = parser.parse(stream) let tokenStrings = result?.map { tree in tree.token?.string } expect(tokenStrings).to(equal(["a"])) expect(stream.index).to(equal(1)) } it("") { let stream = TokenStreamHelper.tokenStream([ "x" ]) let parser = Helper.parser( rules: [ ParserRule.Terminal(terminal: "a") ] ) let result = parser.parse(stream) expect(result).to(beNil()) expect(stream.index).to(equal(0)) } it("") { let stream = TokenStreamHelper.tokenStream([]) let parser = Helper.parser( rules: [ ParserRule.Terminal(terminal: "a") ] ) let result = parser.parse(stream) expect(result).to(beNil()) expect(stream.index).to(equal(0)) } } } }
f9085e79747750cccf92e46120077c47
32.545455
77
0.434547
false
false
false
false
sleepsaint/OL-Language
refs/heads/master
ol-swift/ol-swift/OLSourceValue.swift
mit
1
// // OLSourceValue.swift // ol-swift // // Created by 伍 威 on 15/1/7. // Copyright (c) 2015年 sleepsaint. All rights reserved. // import Foundation class OLSourceValue: OLValue { func lookup(root: OLValue, temp: OLValue, now: OLValue) -> OLValue { return NSNull() } func toBool() -> Bool { return true } func getValueByKey(key: OLValue) -> OLValue { return NSNull() } func compare(b: OLValue) -> Int { return 0 } func filter(function: OLList, root: OLValue, temp: OLValue) -> OLValue { return self } func some(function: OLList, root: OLValue, temp: OLValue) -> Bool { return true } func toArray() -> [AnyObject] { return [] } func sort(inout array: [AnyObject], root: OLValue, temp: OLValue) { } func compare(a: OLValue, _ b: OLValue, root: OLValue, temp: OLValue) -> Int { return lookup(root, temp: temp, now: a).compare(lookup(root, temp: temp, now: b)) } } class OLString: OLSourceValue, Printable { let value: NSString init(value: NSString) { self.value = value } var description : String { return value } override func lookup(root: OLValue, temp: OLValue, now: OLValue) -> OLValue { return value } } class OLNumber: OLSourceValue, Printable { let value: NSNumber init(value: NSNumber) { self.value = value } var description : String { return "\(value)" } override func lookup(root: OLValue, temp: OLValue, now: OLValue) -> OLValue { return value } } class OLPath: OLSourceValue, Printable { let root: Character var keys = Array<OLSourceValue>() init(root: Character) { self.root = root } func addKey(key: OLSourceValue) { keys.append(key) } var description : String { return "\(root)\(keys)" } override func lookup(root: OLValue, temp: OLValue, now: OLValue) -> OLValue { var current : OLValue switch self.root { case "^": current = root case "~": current = temp case "@": current = now default: return NSNull() } for k in keys { let key = k.lookup(root, temp: temp, now: now) current = autoLookup(root, temp, now, current) current = current.getValueByKey(key) } return current } override func sort(inout array: [AnyObject], root: OLValue, temp: OLValue) { array.sort({ return self.compare(toOLValue($0), toOLValue($1), root: root, temp: temp) < 0 }) } } class OLList: OLSourceValue, Printable { let head: OLSourceValue var tail = Array<OLSourceValue>() init(head: OLSourceValue) { self.head = head } func addItem(item: OLSourceValue) { tail.append(item) } var description : String { return "\(head)(\(tail))" } override func lookup(root: OLValue, temp: OLValue, now: OLValue) -> OLValue { if let name = head.lookup(root, temp: temp, now: now) as? NSString { if let function = OLFunction[name] { return function(tail.map({$0.lookup(root, temp: temp, now: now)}), root, temp, now) } } return NSNull() } override func sort(inout array: [AnyObject], root: OLValue, temp: OLValue) { array.sort({ var ret = self.head.compare(toOLValue($0), toOLValue($1), root: root, temp: temp) for i in self.tail { if ret != 0 { return ret < 0 } else { ret = i.compare(toOLValue($0), toOLValue($1), root: root, temp: temp) } } return ret < 0 }) } } class OLNegative: OLSourceValue, Printable { let value: OLSourceValue init(value: OLSourceValue) { self.value = value } var description : String { return "!\(value)" } override func lookup(root: OLValue, temp: OLValue, now: OLValue) -> OLValue { return true } override func sort(inout array: [AnyObject], root: OLValue, temp: OLValue) { array.sort({ return self.value.compare(toOLValue($0), toOLValue($1), root: root, temp: temp) > 0 }) } override func compare(a: OLValue, _ b: OLValue, root: OLValue, temp: OLValue) -> Int { return -value.lookup(root, temp: temp, now: a).compare(value.lookup(root, temp: temp, now: b)) } } class OLQuote: OLSourceValue, Printable { let value: OLSourceValue init(value: OLSourceValue) { self.value = value } var description : String { return "#\(value)" } override func lookup(root: OLValue, temp: OLValue, now: OLValue) -> OLValue { return value } } func autoLookup(root: OLValue, temp: OLValue, now: OLValue, current: OLValue) -> OLValue { var ret = current while let source = ret as? NSString { if let value = OLSource.parse(source) { ret = value.lookup(root, temp: temp, now: now) } } return ret }
706bfe769863bc03c87213205df3dfc9
27.381215
102
0.570372
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
Wikipedia/Code/DescriptionWelcomePageViewController.swift
mit
1
import Foundation import UIKit enum DescriptionWelcomePageType { case intro case exploration } public protocol DescriptionWelcomeNavigationDelegate: AnyObject { func showNextWelcomePage(_ sender: AnyObject) } class DescriptionWelcomePageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, DescriptionWelcomeNavigationDelegate, Themeable { private var theme = Theme.standard func apply(theme: Theme) { self.theme = theme for pageController in pageControllers { if let pageController = pageController as? Themeable { pageController.apply(theme: theme) } } guard viewIfLoaded != nil else { return } skipButton.setTitleColor(UIColor(0xA2A9B1), for: .normal) nextButton.setTitleColor(theme.colors.link, for: .normal) nextButton.setTitleColor(theme.colors.disabledText, for: .disabled) nextButton.setTitleColor(theme.colors.link, for: .highlighted) } @objc var completionBlock: (() -> Void)? func showNextWelcomePage(_ sender: AnyObject) { guard let sender = sender as? UIViewController, let index = pageControllers.firstIndex(of: sender), index != pageControllers.count - 1 else { dismiss(animated: true, completion:completionBlock) return } view.isUserInteractionEnabled = false let nextIndex = index + 1 let direction:UIPageViewController.NavigationDirection = UIApplication.shared.wmf_isRTL ? .reverse : .forward let nextVC = pageControllers[nextIndex] hideButtons(for: nextVC) setViewControllers([nextVC], direction: direction, animated: true, completion: {(Bool) in self.view.isUserInteractionEnabled = true }) } private func containerControllerForWelcomePageType(_ type: DescriptionWelcomePageType) -> DescriptionWelcomeContainerViewController { let controller = DescriptionWelcomeContainerViewController.wmf_viewControllerFromDescriptionWelcomeStoryboard() controller.welcomeNavigationDelegate = self controller.pageType = type controller.nextButtonAction = { [weak self] sender in self?.skipButtonTapped(sender) } return controller } private lazy var pageControllers: [UIViewController] = { var controllers:[UIViewController] = [] controllers.append(containerControllerForWelcomePageType(.intro)) controllers.append(containerControllerForWelcomePageType(.exploration)) return controllers }() private lazy var pageControl: UIPageControl? = { return view.wmf_firstSubviewOfType(UIPageControl.self) }() let nextButton = UIButton() let skipButton = UIButton() let buttonHeight: CGFloat = 40.0 let buttonSidePadding: CGFloat = 10.0 let buttonCenterXOffset: CGFloat = 88.0 override func viewDidLoad() { super.viewDidLoad() dataSource = self delegate = self let direction:UIPageViewController.NavigationDirection = UIApplication.shared.wmf_isRTL ? .forward : .reverse setViewControllers([pageControllers.first!], direction: direction, animated: true, completion: nil) configureAndAddNextButton() configureAndAddSkipButton() if let scrollView = view.wmf_firstSubviewOfType(UIScrollView.self) { scrollView.clipsToBounds = false } updateFonts() apply(theme: theme) } private func configureAndAddNextButton() { nextButton.translatesAutoresizingMaskIntoConstraints = false nextButton.addTarget(self, action: #selector(nextButtonTapped), for: .touchUpInside) nextButton.isUserInteractionEnabled = true nextButton.setContentCompressionResistancePriority(.required, for: .horizontal) nextButton.titleLabel?.numberOfLines = 1 nextButton.setTitle(CommonStrings.nextTitle, for: .normal) view.addSubview(nextButton) nextButton.heightAnchor.constraint(equalToConstant: buttonHeight).isActive = true view.addConstraint(NSLayoutConstraint(item: nextButton, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)) let leading = NSLayoutConstraint(item: nextButton, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: buttonCenterXOffset) leading.priority = .defaultHigh let trailing = NSLayoutConstraint(item: nextButton, attribute: .trailing, relatedBy: .lessThanOrEqual, toItem: view, attribute: .trailing, multiplier: 1, constant: buttonSidePadding) trailing.priority = .required view.addConstraints([leading, trailing]) } private func configureAndAddSkipButton() { skipButton.translatesAutoresizingMaskIntoConstraints = false skipButton.addTarget(self, action: #selector(skipButtonTapped), for: .touchUpInside) skipButton.isUserInteractionEnabled = true skipButton.setContentCompressionResistancePriority(.required, for: .horizontal) skipButton.titleLabel?.numberOfLines = 1 skipButton.setTitle(CommonStrings.skipTitle, for: .normal) view.addSubview(skipButton) skipButton.heightAnchor.constraint(equalToConstant: buttonHeight).isActive = true view.addConstraint(NSLayoutConstraint(item: skipButton, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)) let leading = NSLayoutConstraint(item: skipButton, attribute: .leading, relatedBy: .greaterThanOrEqual, toItem: view, attribute: .leading, multiplier: 1, constant: buttonSidePadding) leading.priority = .required let trailing = NSLayoutConstraint(item: skipButton, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: -buttonCenterXOffset) trailing.priority = .defaultHigh view.addConstraints([leading, trailing]) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateFonts() } private func updateFonts() { skipButton.titleLabel?.font = UIFont.wmf_font(.semiboldFootnote, compatibleWithTraitCollection: traitCollection) nextButton.titleLabel?.font = UIFont.wmf_font(.semiboldFootnote, compatibleWithTraitCollection: traitCollection) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let pageControl = pageControl { pageControl.isUserInteractionEnabled = false pageControl.pageIndicatorTintColor = theme.colors.pageIndicator pageControl.currentPageIndicatorTintColor = theme.colors.pageIndicatorCurrent } } @objc func nextButtonTapped(_ sender: UIButton) { if let currentVC = viewControllers?.first { showNextWelcomePage(currentVC) } } @objc func skipButtonTapped(_ sender: UIButton) { dismiss(animated: true, completion:completionBlock) } func presentationCount(for pageViewController: UIPageViewController) -> Int { return pageControllers.count } func presentationIndex(for pageViewController: UIPageViewController) -> Int { guard let viewControllers = viewControllers, let currentVC = viewControllers.first, let presentationIndex = pageControllers.firstIndex(of: currentVC) else { return 0 } return presentationIndex } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let index = pageControllers.firstIndex(of: viewController) else { return nil } return index >= pageControllers.count - 1 ? nil : pageControllers[index + 1] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let index = pageControllers.firstIndex(of: viewController) else { return nil } return index == 0 ? nil : pageControllers[index - 1] } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if completed { hideButtons(for: pageControllers[presentationIndex(for: pageViewController)]) } } func hideButtons(for vc: UIViewController) { let isLastPage = pageControllers.firstIndex(of: vc) == pageControllers.count - 1 let newAlpha:CGFloat = isLastPage ? 0.0 : 1.0 let alphaChanged = pageControl?.alpha != newAlpha nextButton.isEnabled = !isLastPage // Gray out the next button when transitioning to last page (per design) guard alphaChanged else { return } UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveLinear, animations: { self.nextButton.alpha = newAlpha self.skipButton.alpha = newAlpha self.pageControl?.alpha = newAlpha }, completion: nil) } }
7a62b6500afada45f0cfcd6370438782
45.147059
190
0.701508
false
false
false
false
phakphumi/Chula-Expo-iOS-Application
refs/heads/master
Chula Expo 2017/Chula Expo 2017/HeaderSearchTableViewCell.swift
mit
1
// // HeaderTableViewCell.swift // Chula Expo 2017 // // Created by Ekkalak Leelasornchai on 2/3/2560 BE. // Copyright © 2560 Chula Computer Engineering Batch#41. All rights reserved. // import UIKit class HeaderSearchTableViewCell: UITableViewCell { @IBOutlet weak var engLabel: UILabel! @IBOutlet weak var thaLabel: UILabel! @IBOutlet weak var icon: UIImageView! @IBOutlet weak var background: UIView! var title1: String?{ didSet{ updateUI() } } var title2: String?{ didSet{ updateUI() } } var iconImage: String?{ didSet{ updateUI() } } private func updateUI(){ engLabel.text = nil thaLabel.text = nil icon.image = nil engLabel.text = title1 thaLabel.text = title2 if let iconI = iconImage{ icon.image = UIImage(named: iconI) } } 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 } }
d672150f0d540788ffaaa9f084525098
20.844828
78
0.573796
false
false
false
false
Sage-Bionetworks/BridgeAppSDK
refs/heads/master
BridgeAppSDKTests/SBAConsentTests.swift
bsd-3-clause
1
// // SBAConsentDocumentFactoryTests.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import XCTest @testable import BridgeAppSDK class SBAConsentDocumentFactoryTests: ResourceTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testBuildConsentFactory() { guard let consentFactory = createConsentFactory() else { return } XCTAssertNotNil(consentFactory.steps) guard let steps = consentFactory.steps else { return } let expectedSteps: [ORKStep] = [SBAInstructionStep(identifier: "reconsentIntroduction"), SBAVisualConsentStep(identifier: "consentVisual"), SBANavigationSubtaskStep(identifier: "consentQuiz"), SBAInstructionStep(identifier: "consentFailedQuiz"), SBAInstructionStep(identifier: "consentPassedQuiz"), SBAConsentSharingStep(identifier: "consentSharingOptions"), SBAConsentReviewStep(identifier: "consentReview"), SBAInstructionStep(identifier: "consentCompletion")] XCTAssertEqual(steps.count, expectedSteps.count) for (idx, expectedStep) in expectedSteps.enumerated() { if idx < steps.count { XCTAssertEqual(steps[idx].identifier, expectedStep.identifier) let stepClass = NSStringFromClass(steps[idx].classForCoder) let expectedStepClass = NSStringFromClass(expectedStep.classForCoder) XCTAssertEqual(stepClass, expectedStepClass) } } if (steps.count < expectedSteps.count) { return } } func testReconsentSteps() { guard let consentFactory = createConsentFactory() else { return } let steps = (consentFactory.reconsentStep().subtask as! SBANavigableOrderedTask).steps let expectedSteps: [ORKStep] = [SBAInstructionStep(identifier: "reconsentIntroduction"), SBAVisualConsentStep(identifier: "consentVisual"), SBANavigationSubtaskStep(identifier: "consentQuiz"), SBAInstructionStep(identifier: "consentFailedQuiz"), SBAInstructionStep(identifier: "consentPassedQuiz"), SBAConsentSharingStep(identifier: "consentSharingOptions"), SBAConsentReviewStep(identifier: "consentReview"), SBAInstructionStep(identifier: "consentCompletion")] XCTAssertEqual(steps.count, expectedSteps.count) for (idx, expectedStep) in expectedSteps.enumerated() { if idx < steps.count { XCTAssertEqual(steps[idx].identifier, expectedStep.identifier) let stepClass = NSStringFromClass(steps[idx].classForCoder) let expectedStepClass = NSStringFromClass(expectedStep.classForCoder) XCTAssertEqual(stepClass, expectedStepClass) } } if (steps.count < expectedSteps.count) { return } } func testRegistrationSteps() { guard let consentFactory = createConsentFactory() else { return } let steps = (consentFactory.registrationConsentStep().subtask as! SBANavigableOrderedTask).steps let expectedSteps: [ORKStep] = [SBAVisualConsentStep(identifier: "consentVisual"), SBANavigationSubtaskStep(identifier: "consentQuiz"), SBAInstructionStep(identifier: "consentFailedQuiz"), SBAInstructionStep(identifier: "consentPassedQuiz"), SBAConsentSharingStep(identifier: "consentSharingOptions"), SBAConsentReviewStep(identifier: "consentReview"), SBAInstructionStep(identifier: "consentCompletion")] XCTAssertEqual(steps.count, expectedSteps.count) for (idx, expectedStep) in expectedSteps.enumerated() { if idx < steps.count { XCTAssertEqual(steps[idx].identifier, expectedStep.identifier) let stepClass = NSStringFromClass(steps[idx].classForCoder) let expectedStepClass = NSStringFromClass(expectedStep.classForCoder) XCTAssertEqual(stepClass, expectedStepClass) } } if (steps.count < expectedSteps.count) { return } } func testConsentReview_Default() { guard let consentFactory = createConsentFactory() else { return } let inputStep: NSDictionary = [ "identifier" : "consentReview", "type" : "consentReview" ] let step = consentFactory.createSurveyStepWithDictionary(inputStep) let (_, reviewStep, nameStep, signatureStep) = consentReviewSteps(step) XCTAssertNotNil(nameStep) XCTAssertNotNil(signatureStep) guard reviewStep != nil && nameStep != nil && signatureStep != nil else { return } XCTAssertNotNil(reviewStep!.reasonForConsent) XCTAssertNotNil(nameStep!.formItems) let expected: [String: String] = [ "given" : "ORKTextAnswerFormat", "family" : "ORKTextAnswerFormat"] for (identifier, expectedClassName) in expected { let formItem = nameStep!.formItem(for: identifier) XCTAssertNotNil(formItem) if let classForCoder = formItem?.answerFormat?.classForCoder { let className = NSStringFromClass(classForCoder) XCTAssertEqual(className, expectedClassName) } } } func testConsentReview_NameAndBirthdate() { guard let consentFactory = createConsentFactory() else { return } let inputStep: NSDictionary = [ "identifier" : "consentReview", "type" : "consentReview", "items" : ["name", "birthdate"] ] let step = consentFactory.createSurveyStepWithDictionary(inputStep) let (_, reviewStep, nameStep, signatureStep) = consentReviewSteps(step) XCTAssertNotNil(nameStep) XCTAssertNotNil(signatureStep) guard reviewStep != nil && nameStep != nil && signatureStep != nil else { return } XCTAssertNotNil(reviewStep!.reasonForConsent) XCTAssertNotNil(nameStep!.formItems) let nameItem = nameStep!.formItem(for: "name") XCTAssertNotNil(nameItem) if let _ = nameItem?.answerFormat as? ORKTextAnswerFormat { } else { XCTAssert(false, "\(String(describing: nameItem?.answerFormat)) not of expected type") } let birthdateItem = nameStep!.formItem(for: "birthdate") XCTAssertNotNil(birthdateItem) if let birthdateFormat = birthdateItem?.answerFormat as? ORKHealthKitCharacteristicTypeAnswerFormat { XCTAssertEqual(birthdateFormat.characteristicType.identifier, HKCharacteristicTypeIdentifier.dateOfBirth.rawValue) } else { XCTAssert(false, "\(String(describing: birthdateItem?.answerFormat)) not of expected type") } } func testConsentReview_RequiresSignature_YES() { guard let consentFactory = createConsentFactory() else { return } let inputStep: NSDictionary = [ "identifier" : "consentReview", "type" : "consentReview", "requiresSignature" : true ] let step = consentFactory.createSurveyStepWithDictionary(inputStep) let (_, reviewStep, nameStep, signatureStep) = consentReviewSteps(step) XCTAssertNotNil(nameStep) XCTAssertNotNil(signatureStep) guard reviewStep != nil && nameStep != nil && signatureStep != nil else { return } XCTAssertNotNil(reviewStep!.reasonForConsent) XCTAssertNotNil(nameStep!.formItems) let expected: [String: String] = [ "given" : "ORKTextAnswerFormat", "family" : "ORKTextAnswerFormat"] for (identifier, expectedClassName) in expected { let formItem = nameStep!.formItem(for: identifier) XCTAssertNotNil(formItem) if let classForCoder = formItem?.answerFormat?.classForCoder { let className = NSStringFromClass(classForCoder) XCTAssertEqual(className, expectedClassName) } } } func testConsentReview_RequiresSignature_NO() { guard let consentFactory = createConsentFactory() else { return } let inputStep: NSDictionary = [ "identifier" : "consentReview", "type" : "consentReview", "requiresSignature" : false ] let step = consentFactory.createSurveyStepWithDictionary(inputStep) let (_, reviewStep, nameStep, signatureStep) = consentReviewSteps(step) XCTAssertNotNil(reviewStep?.reasonForConsent) XCTAssertNil(nameStep) XCTAssertNil(signatureStep) } func testConsentResult_RequiresSignatureAndConsented() { guard let consentFactory = createConsentFactory() else { return } let inputStep: NSDictionary = [ "identifier" : "consentReview", "type" : "consentReview", "items" : ["name", "birthdate"] ] let step = consentFactory.createSurveyStepWithDictionary(inputStep) let (_, reviewStep, _, _) = consentReviewSteps(step) guard reviewStep != nil else { return } let reviewResult = ORKConsentSignatureResult(identifier: "review.consent") reviewResult.consented = true reviewResult.signature = reviewStep!.signature let nameResult = ORKTextQuestionResult(identifier: "name.name") nameResult.textAnswer = "John Jones" let birthResult = ORKDateQuestionResult(identifier: "name.birthdate") let expectedBirthdate = Date(timeIntervalSince1970: 0) birthResult.dateAnswer = expectedBirthdate let signatureResult = ORKSignatureResult(identifier: "signature") signatureResult.signatureImage = UIImage() let inputResult = ORKStepResult(stepIdentifier: step!.identifier, results: [ ORKResult(identifier: "step.review"), reviewResult, ORKResult(identifier: "step.name"), nameResult, birthResult, ORKResult(identifier: "step.signature"), signatureResult]) let viewController = MockConsentReviewStepViewController(step: step!, result: inputResult) XCTAssertTrue(viewController.requiresSignature) XCTAssertTrue(viewController.consentAccepted ?? false) XCTAssertNotNil(viewController.signatureImage) XCTAssertEqual(viewController.fullName, "John Jones") XCTAssertEqual(viewController.birthdate, expectedBirthdate) // For the case where the user has consented, the user signature should be saved viewController.goForward() XCTAssertTrue(viewController.goNext_called) XCTAssertNil(viewController.handleConsentDeclined_error) XCTAssertEqual(viewController.sharedUser.name, "John Jones") XCTAssertEqual(viewController.sharedUser.birthdate, expectedBirthdate) guard let signature = viewController.sharedUser.consentSignature as? SBAConsentSignature else { XCTAssert(false, "Consent signature is nil") return } XCTAssertNotNil(signature.signatureImage) XCTAssertEqual(signature.signatureName, "John Jones") XCTAssertEqual(signature.signatureBirthdate, expectedBirthdate) } func testConsentResult_RequiresNoSignature() { guard let consentFactory = createConsentFactory() else { return } let inputStep: NSDictionary = [ "identifier" : "consentReview", "type" : "consentReview", "requiresSignature" : false ] let step = consentFactory.createSurveyStepWithDictionary(inputStep) let (_, reviewStep, _, _) = consentReviewSteps(step) guard reviewStep != nil else { return } let reviewResult = ORKConsentSignatureResult(identifier: "review.consent") reviewResult.consented = true reviewResult.signature = reviewStep!.signature let inputResult = ORKStepResult(stepIdentifier: step!.identifier, results: [ORKResult(identifier: "step.review"), reviewResult]) let viewController = MockConsentReviewStepViewController(step: step!, result: inputResult) XCTAssertFalse(viewController.requiresSignature) XCTAssertTrue(viewController.consentAccepted ?? false) XCTAssertNil(viewController.signatureImage) XCTAssertNil(viewController.fullName) XCTAssertNil(viewController.birthdate) // For the case where the user has consented, the user signature should be saved viewController.goForward() XCTAssertTrue(viewController.goNext_called) XCTAssertNil(viewController.handleConsentDeclined_error) XCTAssertNotNil(viewController.sharedUser.consentSignature) } func testConsentResult_RequiresNotConsented() { guard let consentFactory = createConsentFactory() else { return } let inputStep: NSDictionary = [ "identifier" : "consentReview", "type" : "consentReview", "requiresSignature" : true ] let step = consentFactory.createSurveyStepWithDictionary(inputStep) let (_, reviewStep, _, _) = consentReviewSteps(step) guard reviewStep != nil else { return } let reviewResult = ORKConsentSignatureResult(identifier: "review.consent") reviewResult.consented = false reviewResult.signature = reviewStep!.signature let inputResult = ORKStepResult(stepIdentifier: step!.identifier, results: [ORKResult(identifier: "step.review"), reviewResult]) let viewController = MockConsentReviewStepViewController(step: step!, result: inputResult) XCTAssertFalse(viewController.consentAccepted ?? true) // When the "goForward" method is called, this should call through to the error handler and *not* go to next step viewController.goForward() XCTAssertFalse(viewController.goNext_called) XCTAssertNotNil(viewController.handleConsentDeclined_error) } func testConsentReviewStepAfterStep_NotConsented() { guard let consentFactory = createConsentFactory() else { return } let inputStep: NSDictionary = [ "identifier" : "consentReview", "type" : "consentReview", "requiresSignature" : true ] let step = consentFactory.createSurveyStepWithDictionary(inputStep) let (pageStep, reviewStep, _, _) = consentReviewSteps(step) guard reviewStep != nil else { return } let taskResult = consentReviewTaskResult(step!.identifier, consented: false) let nextStep = pageStep?.stepAfterStep(withIdentifier: reviewStep?.identifier, with: taskResult) XCTAssertNil(nextStep) } func testConsentReviewStepAfterStep_Consented() { guard let consentFactory = createConsentFactory() else { return } let inputStep: NSDictionary = [ "identifier" : "consentReview", "type" : "consentReview", "requiresSignature" : true ] let step = consentFactory.createSurveyStepWithDictionary(inputStep) let (pageStep, reviewStep, _, _) = consentReviewSteps(step) guard reviewStep != nil else { return } let taskResult = consentReviewTaskResult(step!.identifier, consented: true) let nextStep = pageStep?.stepAfterStep(withIdentifier: reviewStep?.identifier, with: taskResult) XCTAssertNotNil(nextStep) } // MARK: helper methods func consentReviewTaskResult(_ identifier: String, consented: Bool) -> ORKTaskResult { let reviewResult = ORKConsentSignatureResult(identifier: "consent") reviewResult.consented = consented let stepResult = ORKStepResult(stepIdentifier: "review", results: [reviewResult]) let taskResult = ORKTaskResult(identifier: identifier) taskResult.results = [stepResult] return taskResult } func consentReviewSteps(_ step: ORKStep?) -> (pageStep:SBAConsentReviewStep?, reviewStep: ORKConsentReviewStep?, nameStep: ORKFormStep?, signatureStep: ORKSignatureStep?) { guard let pageStep = step as? SBAConsentReviewStep else { XCTAssert(false, "\(String(describing: step)) not of expected type") return (nil, nil, nil, nil) } guard let reviewStep = pageStep.step(withIdentifier: "review") as? ORKConsentReviewStep else { XCTAssert(false, "\(pageStep.steps) does not include a review step (required)") return (nil, nil, nil, nil) } if let signature = reviewStep.signature { // Review step should have either a nil signature or not require name/image XCTAssertFalse(signature.requiresName) XCTAssertFalse(signature.requiresSignatureImage) } let formStep = pageStep.step(withIdentifier: "name") as? ORKFormStep let signatureStep = pageStep.step(withIdentifier: "signature") as? ORKSignatureStep return (pageStep, reviewStep, formStep, signatureStep) } func createConsentFactory() -> SBASurveyFactory? { guard let input = jsonForResource("Consent") else { return nil } return SBASurveyFactory(dictionary: input) } } class MockConsentReviewStepViewController: SBAConsentReviewStepViewController { override init(step: ORKStep?) { super.init(step: step) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override init(step: ORKStep, result: ORKResult) { super.init(step: step, result: result) self.sharedAppDelegate = MockAppInfoDelegate() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func handleConsentDeclined(with error: Error) { handleConsentDeclined_error = error } var handleConsentDeclined_error: Error? override func goNext() { goNext_called = true } var goNext_called = false }
c99d5af5999ad2dc6092ece020d9a287
44.566596
176
0.630399
false
false
false
false
jwfriese/FrequentFlyer
refs/heads/master
FrequentFlyer/Authentication/ConcourseEntryViewController.swift
apache-2.0
1
import UIKit import RxSwift import RxCocoa class ConcourseEntryViewController: UIViewController { @IBOutlet weak var scrollView: UIScrollView? @IBOutlet weak var concourseURLEntryField: TitledTextField? @IBOutlet weak var submitButton: RoundedButton? var infoService = InfoService() var sslTrustService = SSLTrustService() var userTextInputPageOperator = UserTextInputPageOperator() class var storyboardIdentifier: String { get { return "ConcourseEntry" } } class var showVisibilitySelectionSegueId: String { get { return "ShowVisibilitySelection" } } var authMethod$: Observable<AuthMethod>? var disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() title = "" view?.backgroundColor = Style.Colors.backgroundColor scrollView?.backgroundColor = Style.Colors.backgroundColor navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) submitButton?.setUp(withTitleText: "Submit", titleFont: Style.Fonts.button, controlStateTitleColors: [.normal : #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)], controlStateButtonColors: [.normal : Style.Colors.buttonNormal] ) concourseURLEntryField?.titleLabel?.text = "Concourse Base URL" concourseURLEntryField?.textField?.autocorrectionType = .no concourseURLEntryField?.textField?.keyboardType = .URL concourseURLEntryField?.textField?.delegate = self submitButton?.isEnabled = false userTextInputPageOperator.delegate = self sslTrustService.clearAllTrust() } override func viewDidAppear(_ animated: Bool) { if let text = concourseURLEntryField?.textField?.text { submitButton?.isEnabled = !text.isEmpty } else { submitButton?.isEnabled = false } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == ConcourseEntryViewController.showVisibilitySelectionSegueId { guard let visibilitySelectionViewController = segue.destination as? VisibilitySelectionViewController else { return } guard let concourseURLString = concourseURLEntryField?.textField?.text else { return } visibilitySelectionViewController.concourseURLString = createValidConcourseURL(fromInput: concourseURLString) } } private func createValidConcourseURL(fromInput input: String) -> String { var concourseURLString = input let inputHasProtocol = input.hasPrefix("https://") if !inputHasProtocol { concourseURLString = "https://" + concourseURLString } return concourseURLString } @IBAction func submitButtonTapped() { guard var concourseURLString = concourseURLEntryField?.textField?.text else { return } let inputHasInvalidProtocol = concourseURLString.hasPrefix("http://") if inputHasInvalidProtocol { showInvalidProtocolAlert() return } if concourseURLString == "https://" { showConcourseInaccessibleError(atURL: concourseURLString) return } concourseURLString = createValidConcourseURL(fromInput: concourseURLString) submitButton?.isEnabled = false checkForConcourseExistence(atBaseURL: concourseURLString) } private func checkForConcourseExistence(atBaseURL baseURL: String) { infoService.getInfo(forConcourseWithURL: baseURL) .subscribe( onNext: { _ in DispatchQueue.main.async { self.performSegue(withIdentifier: ConcourseEntryViewController.showVisibilitySelectionSegueId, sender: nil) } }, onError: { error in guard let httpError = error as? HTTPError else { self.showConcourseInaccessibleError(atURL: baseURL) return } switch httpError { case .sslValidation: self.showSSLTrustChallenge(forBaseURL: baseURL) } }) .disposed(by: disposeBag) } private func showSSLTrustChallenge(forBaseURL baseURL: String) { let alert = UIAlertController( title: "Insecure Connection", message: "Could not establish a trusted connection with the Concourse instance. Would you like to connect anyway?", preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { _ in self.submitButton?.isEnabled = true })) alert.addAction(UIAlertAction(title: "Connect", style: .destructive, handler: { _ in self.submitButton?.isEnabled = true self.sslTrustService.registerTrust(forBaseURL: baseURL) self.checkForConcourseExistence(atBaseURL: baseURL) })) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } private func showConcourseInaccessibleError(atURL url: String) { let alert = UIAlertController( title: "Error", message: "Could not connect to a Concourse at '\(url)'.", preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) self.submitButton?.isEnabled = true } } private func showInvalidProtocolAlert() { let alert = UIAlertController( title: "Unsupported Protocol", message: "This app does not support connecting to Concourse instances through HTTP. You must use HTTPS.", preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) self.submitButton?.isEnabled = true } } } extension ConcourseEntryViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let isDeleting = string == "" let isCurrentStringLongerThanOne = textField.text != nil && textField.text!.count > 1 let willHaveText = !isDeleting || isCurrentStringLongerThanOne submitButton?.isEnabled = willHaveText return true } func textFieldShouldClear(_ textField: UITextField) -> Bool { submitButton?.isEnabled = false return true } } extension ConcourseEntryViewController: UserTextInputPageDelegate { var textFields: [UITextField] { get { return [concourseURLEntryField!.textField!] } } var pageView: UIView { get { return view } } var pageScrollView: UIScrollView { get { return scrollView! } } }
f91d7c637cddd03b1dd0d63ee6045539
38.458564
131
0.649258
false
false
false
false
TCA-Team/iOS
refs/heads/master
TUM Campus App/SearchResultsController.swift
gpl-3.0
1
// // SearchResultsController.swift // Campus // // This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS // Copyright (c) 2018 TCA // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import UIKit import Sweeft class SearchResultsController: UITableViewController { weak var delegate: DetailViewDelegate? weak var navCon: UINavigationController? var promise: Response<[SearchResults]>? var currentElement: DataElement? public var elements: [SearchResults] = [] { didSet { tableView.reloadData() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if !UIAccessibility.isReduceTransparencyEnabled { self.view.backgroundColor = .clear let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.extraLight) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = self.view.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.tableView.separatorEffect = UIVibrancyEffect(blurEffect: blurEffect) self.tableView.backgroundView = blurEffectView } else { self.view.backgroundColor = .black } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { guard !elements[section].results.isEmpty else { return nil } return elements[section].key.description } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { currentElement = elements[indexPath.section].results[indexPath.row] return indexPath } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch currentElement!.getCellIdentifier() { case "person": let storyboard = UIStoryboard(name: "PersonDetail", bundle: nil) if let personDetailTableViewController = storyboard.instantiateInitialViewController() as? PersonDetailTableViewController { personDetailTableViewController.user = currentElement personDetailTableViewController.delegate = self navCon?.pushViewController(personDetailTableViewController, animated: true) } case "lecture": let storyboard = UIStoryboard(name: "LectureDetail", bundle: nil) if let lectureDetailViewController = storyboard.instantiateInitialViewController() as? LectureDetailsTableViewController { lectureDetailViewController.lecture = currentElement lectureDetailViewController.delegate = self navCon?.pushViewController(lectureDetailViewController, animated: true) } case "room": let storyboard = UIStoryboard(name: "RoomFinder", bundle: nil) if let roomFinderView = storyboard.instantiateInitialViewController() as? RoomFinderViewController { roomFinderView.room = currentElement roomFinderView.delegate = self navCon?.pushViewController(roomFinderView, animated: true) } case "sexy": (currentElement as? SexyEntry)?.open(sender: navCon) default: break } tableView.deselectRow(at: indexPath, animated: true) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return elements[section].results.count } override func numberOfSections(in tableView: UITableView) -> Int { return elements.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let element = elements[indexPath.section].results[indexPath.row] let cell = tableView.dequeueReusableCell( withIdentifier: element.getCellIdentifier()) as? CardTableViewCell ?? CardTableViewCell() cell.setElement(element) cell.backgroundColor = .clear return cell } } extension SearchResultsController { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } } extension SearchResultsController: DetailViewDelegate { func dataManager() -> TumDataManager? { return delegate?.dataManager() } } extension SearchResultsController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { promise?.cancel() if let query = searchController.searchBar.text { promise = delegate?.dataManager()?.search(query: query).onSuccess(in: .main) { elements in self.elements = elements } } } }
385509e63e33b25ef864385817fe3eb5
35.444444
109
0.659433
false
false
false
false
dathtcheapgo/Jira-Demo
refs/heads/master
Driver/Extension/SegmentedControlExtension.swift
mit
1
// // SegmentedControlExtension.swift // Demo // // Created by Tien Dat on 10/24/16. // Copyright © 2016 Tien Dat. All rights reserved. // import Foundation import UIKit extension UISegmentedControl { func removeBorders() { // setBackgroundImage(self.imageWithColor(UIColor.clearColor()), forState: .Normal, barMetrics: .Default) setBackgroundImage(imageWithColor(tintColor!), for: .selected, barMetrics: .default) setDividerImage(imageWithColor(UIColor.clear), forLeftSegmentState: UIControlState(), rightSegmentState: UIControlState(), barMetrics: .default) for borderview in subviews { let upperBorder: CALayer = CALayer() upperBorder.backgroundColor = UIColor.init(red: 215/255.0, green: 0.0, blue: 30/255.0, alpha: 1.0).cgColor upperBorder.frame = CGRect(x: 0, y: borderview.frame.size.height-1, width: borderview.frame.size.width, height: 1.0) borderview.layer .addSublayer(upperBorder) borderview.layer.allowsEdgeAntialiasing = true borderview.layer.shadowOffset = CGSize.init(width: 10, height: 10) borderview.layer.cornerRadius = CGFloat(5) borderview.layer.masksToBounds = true // borderview.frame = CGRectMake(0, borderview.frame.size.height-1, borderview.frame.size.width, 1.0) } } // create a 1x1 image with this color fileprivate func imageWithColor(_ color: UIColor) -> UIImage { let rect = CGRect(x: 0.0, y: 0.0, width: 0.5, height: 0.5) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor); context?.fill(rect); let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image! } }
f53d79b980c30a249d5f609e9f5c41fd
35.2
148
0.688398
false
false
false
false
drewag/Swiftlier
refs/heads/master
Tests/SwiftlierTests/ObservableTests.swift
mit
1
// // ObservableTests.swift // Swiftlier // // Created by Andrew J Wagner on 7/27/14. // Copyright (c) 2014 Drewag LLC. All rights reserved. // import XCTest import Swiftlier final class ObservableTests: XCTestCase { func testSubscribing() { let observable = Observable<String>("Old Value") var called = false observable.addChangedValueObserver(self) { oldValue, newValue in XCTAssertEqual(oldValue, "Old Value") XCTAssertEqual(newValue, "New Value") called = true } observable.current = "New Value" XCTAssertTrue(called) } func testUnsubscribing() { let observable = Observable<String>("Old Value") var called = false observable.addNewValueObserver(self) { _ in called = true } observable.removeObserver(self) observable.current = "New Value" XCTAssertFalse(called) } func testTriggerImmediately() { let observable = Observable<String>("Current Value") var called = false observable.addChangeObserver(self, options: ObservationOptions.initial) { oldValue, newValue in XCTAssertNil(oldValue) XCTAssertEqual(newValue, "Current Value") called = true } XCTAssertTrue(called) } func testAutomaticUnsubscribing() { class SomeClass { } var observable = Observable<String>("Current Value") var called = false func scope() { let observer = SomeClass() observable.addNewValueObserver(observer) { _ in called = true } } scope() observable.current = "New Value" XCTAssertFalse(called) } func testCallOnceOption() { let observable = Observable<String>("Current Value") var called = false observable.addNewValueObserver(self, options: .onlyOnce) { newValue in XCTAssertEqual(newValue, "Second Value") called = true } XCTAssertFalse(called) observable.current = "Second Value" XCTAssertTrue(called) called = false observable.current = "Third Value" XCTAssertFalse(called) } func testCallOnceOptionWithInitial() { let observable = Observable<String>("Current Value") var called = false observable.addNewValueObserver(self, options: [.initial, .onlyOnce]) { _ in called = true } XCTAssertTrue(called) observable.current = "Second Value" XCTAssertTrue(called) called = false observable.current = "Third Value" XCTAssertFalse(called) } }
d8dde7ea1db346ff565e2caab23bc3d4
28.168421
103
0.592927
false
true
false
false
brentdax/swift
refs/heads/master
test/decl/protocol/req/unsatisfiable.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift -swift-version 4 protocol P { associatedtype A associatedtype B func f<T: P>(_: T) where T.A == Self.A, T.A == Self.B // expected-error{{instance method requirement 'f' cannot add constraint 'Self.A == Self.B' on 'Self'}} // expected-note@-1 {{protocol requires function 'f' with type '<T> (T) -> ()'; do you want to add a stub?}} } extension P { func f<T: P>(_: T) where T.A == Self.A, T.A == Self.B { } // expected-note@-1 {{candidate has non-matching type '<Self, T> (T) -> ()'}} } struct X : P { // expected-error {{type 'X' does not conform to protocol 'P'}} typealias A = X typealias B = Int } protocol P2 { associatedtype A func f<T: P2>(_: T) where T.A == Self.A, T.A: P2 // expected-error{{instance method requirement 'f' cannot add constraint 'Self.A: P2' on 'Self'}} } class C { } protocol P3 { associatedtype A func f<T: P3>(_: T) where T.A == Self.A, T.A: C // expected-error{{instance method requirement 'f' cannot add constraint 'Self.A: C' on 'Self'}} func g<T: P3>(_: T) where T.A: C, T.A == Self.A // expected-error{{instance method requirement 'g' cannot add constraint 'Self.A: C' on 'Self'}} } protocol Base { associatedtype Assoc } // FIXME: The first error is redundant and isn't correct in what it states. // FIXME: This used to /not/ error in Swift 3. It didn't impose any statically- // enforced requirements, but the compiler crashed if you used anything but the // same type. protocol Sub1: Base { associatedtype SubAssoc: Assoc // expected-error@-1 {{type 'Self.SubAssoc' constrained to non-protocol, non-class type 'Self.Assoc'}} // expected-error@-2 {{inheritance from non-protocol, non-class type 'Self.Assoc'}} } // FIXME: This error is incorrect in what it states. protocol Sub2: Base { associatedtype SubAssoc where SubAssoc: Assoc // expected-error {{type 'Self.SubAssoc' constrained to non-protocol, non-class type 'Self.Assoc'}} } struct S {} // FIX-ME: One of these errors is redundant. protocol P4 { associatedtype X : S // expected-error@-1 {{type 'Self.X' constrained to non-protocol, non-class type 'S'}} // expected-error@-2 {{inheritance from non-protocol, non-class type 'S'}} } protocol P5 { associatedtype Y where Y : S // expected-error {{type 'Self.Y' constrained to non-protocol, non-class type 'S'}} }
4c016f4bfa0fa17242b80fff4015c6ea
34.651515
159
0.671908
false
false
false
false
XWebView/Sample
refs/heads/master
Sample/Plugins/Echo.swift
apache-2.0
1
/* Copyright 2015 XWebView 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 XWebView class Echo: NSObject { dynamic var prefix: String = "" func echo(_ message: String, callback: XWVScriptObject) { callback.call(arguments: [prefix + message], completionHandler: nil) } } extension Echo : XWVScripting { convenience init(prefix: AnyObject?) { self.init() if prefix is String { self.prefix = prefix as! String } else if let num = prefix as? NSNumber { self.prefix = num.stringValue } } class func scriptName(for selector: Selector) -> String? { return selector == #selector(Echo.init(prefix:)) ? "" : nil } }
4696a8f76cdc5191969013708e5ed917
29.846154
76
0.686617
false
false
false
false
darrarski/SharedShopping-iOS
refs/heads/master
SharedShoppingApp/UI/CreateShopping/Presenters/CreatedShoppingPresenter.swift
mit
1
import UIKit class CreatedShoppingPresenter: CreatedShoppingPresenting { typealias ShoppingViewControllerFactory = (Shopping) -> UIViewController init(navigationController: UINavigationController, shoppingViewControllerFactory: @escaping ShoppingViewControllerFactory) { self.navigationController = navigationController self.shoppingViewControllerFactory = shoppingViewControllerFactory } // MARK: CreatedShoppingPresenting func presentCreatedShopping(_ shopping: Shopping) { let viewController = self.shoppingViewControllerFactory(shopping) var viewControllers = navigationController.viewControllers let index = viewControllers.index(where: { $0.isKind(of: CreateShoppingViewController.self) }) if let index = index { viewControllers.removeSubrange((index..<viewControllers.endIndex)) } viewControllers.append(viewController) navigationController.setViewControllers(viewControllers, animated: true) } // MARK: Private private let navigationController: UINavigationController private let shoppingViewControllerFactory: ShoppingViewControllerFactory }
e97da708a7153669e592e7c92477ec72
37.322581
102
0.760943
false
false
false
false
RushingTwist/SwiftExamples
refs/heads/master
DemoClass/RxSwiftProject/Pods/Moya/Sources/Moya/Plugins/AccessTokenPlugin.swift
apache-2.0
4
import Foundation import Result // MARK: - AccessTokenAuthorizable /// A protocol for controlling the behavior of `AccessTokenPlugin`. public protocol AccessTokenAuthorizable { /// Represents the authorization header to use for requests. var authorizationType: AuthorizationType { get } } // MARK: - AuthorizationType /// An enum representing the header to use with an `AccessTokenPlugin` public enum AuthorizationType: String { /// No header. case none /// The `"Basic"` header. case basic = "Basic" /// The `"Bearer"` header. case bearer = "Bearer" } // MARK: - AccessTokenPlugin /** A plugin for adding basic or bearer-type authorization headers to requests. Example: ``` Authorization: Bearer <token> Authorization: Basic <token> ``` */ public struct AccessTokenPlugin: PluginType { /// A closure returning the access token to be applied in the header. public let tokenClosure: () -> String /** Initialize a new `AccessTokenPlugin`. - parameters: - tokenClosure: A closure returning the token to be applied in the pattern `Authorization: <AuthorizationType> <token>` */ public init(tokenClosure: @escaping @autoclosure () -> String) { self.tokenClosure = tokenClosure } /** Prepare a request by adding an authorization header if necessary. - parameters: - request: The request to modify. - target: The target of the request. - returns: The modified `URLRequest`. */ public func prepare(_ request: URLRequest, target: TargetType) -> URLRequest { guard let authorizable = target as? AccessTokenAuthorizable else { return request } let authorizationType = authorizable.authorizationType var request = request switch authorizationType { case .basic, .bearer: let authValue = authorizationType.rawValue + " " + tokenClosure() request.addValue(authValue, forHTTPHeaderField: "Authorization") case .none: break } return request } }
3b21b845d6419e8bac82bd76903c6fe8
25.666667
126
0.669231
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
HabitRPG/UI/Inventory/AvatarOverviewViewController.swift
gpl-3.0
1
// // AvatarOverviewViewController.swift // Habitica // // Created by Phillip Thelen on 20.04.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models import ReactiveSwift class AvatarOverviewViewController: BaseUIViewController, UIScrollViewDelegate { private let userRepository = UserRepository() private let disposable = ScopedDisposable(CompositeDisposable()) private var selectedType: String? private var selectedGroup: String? @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var bodySizeLabel: UILabel! @IBOutlet weak var bodySizeControl: UISegmentedControl! @IBOutlet weak var containerview: UIView! @IBOutlet weak var shirtView: AvatarOverviewItemView! @IBOutlet weak var skinView: AvatarOverviewItemView! @IBOutlet weak var hairColorView: AvatarOverviewItemView! @IBOutlet weak var hairBangsView: AvatarOverviewItemView! @IBOutlet weak var hairBaseView: AvatarOverviewItemView! @IBOutlet weak var hairMustacheView: AvatarOverviewItemView! @IBOutlet weak var hairBeardView: AvatarOverviewItemView! @IBOutlet weak var hairFlowerView: AvatarOverviewItemView! @IBOutlet weak var eyewearView: AvatarOverviewItemView! @IBOutlet weak var wheelchairView: AvatarOverviewItemView! @IBOutlet weak var animalEarsView: AvatarOverviewItemView! @IBOutlet weak var backgroundView: AvatarOverviewItemView! override func viewDidLoad() { super.viewDidLoad() topHeaderCoordinator = TopHeaderCoordinator(topHeaderNavigationController: hrpgTopHeaderNavigationController(), scrollView: scrollView) topHeaderCoordinator?.followScrollView = false setupItemViews() disposable.inner.add(userRepository.getUser().on(value: {[weak self]user in self?.configure(user: user) }).start()) view.setNeedsLayout() } override func applyTheme(theme: Theme) { super.applyTheme(theme: theme) bodySizeLabel.textColor = theme.primaryTextColor } override func populateText() { navigationItem.title = L10n.Titles.avatar bodySizeLabel.text = L10n.bodySize bodySizeControl.setTitle(L10n.slim, forSegmentAt: 0) bodySizeControl.setTitle(L10n.broad, forSegmentAt: 1) } func scrollViewDidScroll(_ scrollView: UIScrollView) { topHeaderCoordinator?.scrollViewDidScroll() } private func setupItemViews() { shirtView.setup(title: L10n.Avatar.shirt) {[weak self] in self?.openDetailView(type: "shirt") } skinView.setup(title: L10n.Avatar.skin) {[weak self] in self?.openDetailView(type: "skin") } hairColorView.setup(title: L10n.Avatar.hairColor) {[weak self] in self?.openDetailView(type: "hair", group: "color") } hairBangsView.setup(title: L10n.Avatar.bangs) {[weak self] in self?.openDetailView(type: "hair", group: "bangs") } hairBaseView.setup(title: L10n.Avatar.hairStyle) {[weak self] in self?.openDetailView(type: "hair", group: "base") } hairMustacheView.setup(title: L10n.Avatar.mustache) {[weak self] in self?.openDetailView(type: "hair", group: "mustache") } hairBeardView.setup(title: L10n.Avatar.beard) {[weak self] in self?.openDetailView(type: "hair", group: "beard") } hairFlowerView.setup(title: L10n.Avatar.flower) {[weak self] in self?.openDetailView(type: "hair", group: "flower") } eyewearView.setup(title: L10n.Avatar.glasses) {[weak self] in self?.openDetailView(type: "eyewear") } wheelchairView.setup(title: L10n.Avatar.wheelchair) {[weak self] in self?.openDetailView(type: "chair") } animalEarsView.setup(title: L10n.Avatar.head) {[weak self] in self?.openDetailView(type: "headAccessory") } backgroundView.setup(title: L10n.Avatar.background) {[weak self] in self?.openDetailView(type: "background") } } private func configure(user: UserProtocol) { bodySizeControl.selectedSegmentIndex = user.preferences?.size == "slim" ? 0 : 1 if let shirt = user.preferences?.shirt { shirtView.configure("Icon_\(user.preferences?.size ?? "slim")_shirt_\(shirt)") } if let skin = user.preferences?.skin { skinView.configure("Icon_skin_\(skin)") } if let hairColor = user.preferences?.hair?.color { hairColorView.configure("Icon_hair_bangs_1_\(hairColor)") if let bangs = user.preferences?.hair?.bangs, bangs != 0 { hairBangsView.configure("Icon_hair_bangs_\(bangs)_\(hairColor)") } else { hairBangsView.configure(nil) } if let base = user.preferences?.hair?.base, base != 0 { hairBaseView.configure("Icon_hair_base_\(base)_\(hairColor)") } else { hairBaseView.configure(nil) } if let beard = user.preferences?.hair?.beard, beard != 0 { hairBeardView.configure("Icon_hair_beard_\(beard)_\(hairColor)") } else { hairBeardView.configure(nil) } if let mustache = user.preferences?.hair?.mustache, mustache != 0 { hairBeardView.configure("Icon_hair_mustache_\(mustache)_\(hairColor)") } else { hairBeardView.configure(nil) } } if let flower = user.preferences?.hair?.flower, flower != 0 { hairFlowerView.configure("Icon_hair_flower_\(flower)") } else { hairFlowerView.configure(nil) } if let chair = user.preferences?.chair, chair != "none" { wheelchairView.configure("Icon_chair_\(chair)") } else { wheelchairView.configure(nil) } if let outfit = user.preferences?.useCostume ?? false ? user.items?.gear?.costume : user.items?.gear?.equipped { if let eyewear = outfit.eyewear { eyewearView.configure("shop_\(eyewear)") } else { eyewearView.configure(nil) } if let headAccessory = outfit.headAccessory { animalEarsView.configure("shop_\(headAccessory)") } else { animalEarsView.configure(nil) } } if let background = user.preferences?.background { backgroundView.configure("icon_background_\(background)") } else { backgroundView.configure(nil) } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() layout() } private func layout() { let itemWidth = (view.bounds.size.width - (7 * 8)) / 4 let itemHeight = itemWidth + 38 containerview.pin.top(50).left(8).width(view.bounds.size.width-16).height(itemHeight * 3 + (3 * 8)) scrollView.contentSize = CGSize(width: view.bounds.size.width, height: containerview.bounds.origin.y + containerview.bounds.size.height + 64) scrollView.pin.all() bodySizeLabel.pin.top(0).left(8).above(of: containerview).sizeToFit(.height) bodySizeControl.pin.right(8).top(11) shirtView.pin.top(8).left(8).width(itemWidth).height(itemHeight) skinView.pin.top(8).right(of: shirtView).marginLeft(8).width(itemWidth).height(itemHeight) hairColorView.pin.top(8).right(of: skinView).marginLeft(8).width(itemWidth).height(itemHeight) hairBangsView.pin.top(8).right(of: hairColorView).marginLeft(8).width(itemWidth).height(itemHeight) hairBaseView.pin.below(of: shirtView).marginTop(8).left(8).width(itemWidth).height(itemHeight) hairMustacheView.pin.below(of: shirtView).marginTop(8).right(of: hairBaseView).marginLeft(8).width(itemWidth).height(itemHeight) hairBeardView.pin.below(of: shirtView).marginTop(8).right(of: hairMustacheView).marginLeft(8).width(itemWidth).height(itemHeight) hairFlowerView.pin.below(of: shirtView).marginTop(8).right(of: hairBeardView).marginLeft(8).width(itemWidth).height(itemHeight) eyewearView.pin.below(of: hairBaseView).marginTop(8).left(8).width(itemWidth).height(itemHeight) wheelchairView.pin.below(of: hairBaseView).marginTop(8).right(of: eyewearView).marginLeft(8).width(itemWidth).height(itemHeight) animalEarsView.pin.below(of: hairBaseView).marginTop(8).right(of: wheelchairView).marginLeft(8).width(itemWidth).height(itemHeight) backgroundView.pin.below(of: hairBaseView).marginTop(8).right(of: animalEarsView).marginLeft(8).width(itemWidth).height(itemHeight) } @IBAction func bodySizeChanged(_ sender: Any) { disposable.inner.add(userRepository.updateUser(key: "preferences.size", value: bodySizeControl.selectedSegmentIndex == 0 ? "slim" : "broad").observeCompleted {}) } private func openDetailView(type: String, group: String? = nil) { selectedType = type selectedGroup = group perform(segue: StoryboardSegue.Main.detailSegue) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == StoryboardSegue.Main.detailSegue.rawValue { let destination = segue.destination as? AvatarDetailViewController destination?.customizationType = selectedType destination?.customizationGroup = selectedGroup } } }
bab18b71b5b0b6a75199e77c33ee4cb7
42.799107
169
0.640302
false
true
false
false
rambler-digital-solutions/rambler-it-ios
refs/heads/develop
Carthage/Checkouts/rides-ios-sdk/source/UberRides/Model/RideMap.swift
mit
1
// // RideMap.swift // UberRides // // Copyright © 2016 Uber Technologies, Inc. All rights reserved. // // 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. // MARK: RideMap /** * Visual representation of a ride request, only available after a request is accepted. */ @objc(UBSDKRideMap) public class RideMap: NSObject, Codable { /// URL to a map representing the requested trip. @objc public private(set) var path: URL /// Unique identifier representing a ride request. @objc public private(set) var requestID: String enum CodingKeys: String, CodingKey { case path = "href" case requestID = "request_id" } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) path = try container.decode(URL.self, forKey: .path) requestID = try container.decode(String.self, forKey: .requestID) } }
0b0ed437542d501e4b1d16427d46f91b
40.208333
88
0.717391
false
false
false
false
Chriskuei/Bon-for-Mac
refs/heads/master
Bon/BonLoginView.swift
mit
1
// // BonLoginView.swift // Bon // // Created by Chris on 16/5/14. // Copyright © 2016年 Chris. All rights reserved. // import Cocoa enum LogMessage { case loading case usernameError case passwordError case inArrearsError case timeout case error case loginSuccess case logoutSuccess } class BonLoginView: NSView { @IBOutlet weak var usernameTextField: NSTextField! @IBOutlet weak var passwordTextField: NSSecureTextField! @IBOutlet weak var loadingIndicator: NSProgressIndicator! @IBOutlet weak var alertLabel: NSTextField! override func awakeFromNib() { super.awakeFromNib() loadingIndicator.isHidden = true alertLabel.isHidden = true wantsLayer = true layer?.backgroundColor = NSColor.white.cgColor } func show(_ logMessage: LogMessage) { switch logMessage { case .loading: isHidden = false loadingIndicator.isHidden = false loadingIndicator.startAnimation(nil) case .usernameError: isHidden = false loadingIndicator.isHidden = true loadingIndicator.stopAnimation(nil) alertLabel.isHidden = false alertLabel.stringValue = "User not found." delay(2) { self.alertLabel.isHidden = true; } case .passwordError: isHidden = false loadingIndicator.isHidden = true loadingIndicator.stopAnimation(nil) alertLabel.isHidden = false alertLabel.stringValue = "Password is incorrect." delay(2) { self.alertLabel.isHidden = true; } case .inArrearsError: isHidden = false loadingIndicator.isHidden = true loadingIndicator.stopAnimation(nil) alertLabel.isHidden = false alertLabel.stringValue = "You are in arrears." delay(2) { self.alertLabel.isHidden = true; } case .timeout: isHidden = false loadingIndicator.isHidden = true loadingIndicator.stopAnimation(nil) alertLabel.isHidden = false alertLabel.stringValue = "Time out." delay(2) { self.alertLabel.isHidden = true; } case .error: isHidden = false loadingIndicator.isHidden = true loadingIndicator.stopAnimation(nil) alertLabel.isHidden = false alertLabel.stringValue = "Login error." delay(2) { self.alertLabel.isHidden = true; } case .loginSuccess: isHidden = true loadingIndicator.isHidden = true loadingIndicator.stopAnimation(nil) case .logoutSuccess: isHidden = false loadingIndicator.isHidden = true loadingIndicator.stopAnimation(nil) alertLabel.isHidden = false alertLabel.stringValue = "Logout ok." delay(2) { self.alertLabel.isHidden = true; } } } func showLoginState(_ loginState: LoginState) { switch loginState { case .online: isHidden = false loadingIndicator.isHidden = true loadingIndicator.stopAnimation(nil) alertLabel.isHidden = false alertLabel.stringValue = "You are online now." delay(2) { self.alertLabel.isHidden = true; } case .offline: isHidden = false loadingIndicator.isHidden = true loadingIndicator.stopAnimation(nil) alertLabel.isHidden = false alertLabel.stringValue = "You are offline." delay(2) { self.alertLabel.isHidden = true; } } } }
c20dd2ec8c1eb0a841fb654ddecc32a2
27.93617
61
0.548039
false
false
false
false
zisko/swift
refs/heads/master
test/SILGen/enum_resilience.swift
apache-2.0
1
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift // RUN: %target-swift-frontend -I %t -enable-sil-ownership -emit-silgen -enable-resilience %s | %FileCheck %s import resilient_enum // Resilient enums are always address-only, and switches must include // a default case // CHECK-LABEL: sil hidden @$S15enum_resilience15resilientSwitchyy0c1_A06MediumOF : $@convention(thin) (@in Medium) -> () // CHECK: [[BOX:%.*]] = alloc_stack $Medium // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX]] // CHECK-NEXT: switch_enum_addr [[BOX]] : $*Medium, case #Medium.Paper!enumelt: bb1, case #Medium.Canvas!enumelt: bb2, case #Medium.Pamphlet!enumelt.1: bb3, case #Medium.Postcard!enumelt.1: bb4, default bb5 // CHECK: bb1: // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb3: // CHECK-NEXT: [[INDIRECT_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]] // CHECK-NEXT: [[INDIRECT:%.*]] = load [take] [[INDIRECT_ADDR]] // CHECK-NEXT: [[PAYLOAD:%.*]] = project_box [[INDIRECT]] // CHECK-NEXT: destroy_value [[INDIRECT]] // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb4: // CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]] // CHECK-NEXT: destroy_addr [[PAYLOAD_ADDR]] // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb5: // CHECK-NEXT: unreachable // CHECK: bb6: // CHECK-NEXT: destroy_addr %0 // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] func resilientSwitch(_ m: Medium) { switch m { case .Paper: () case .Canvas: () case .Pamphlet: () case .Postcard: () } } // Indirect enums are still address-only, because the discriminator is stored // as part of the value, so we cannot resiliently make assumptions about the // enum's size // CHECK-LABEL: sil hidden @$S15enum_resilience21indirectResilientEnumyy010resilient_A016IndirectApproachOF : $@convention(thin) (@in IndirectApproach) -> () func indirectResilientEnum(_ ia: IndirectApproach) {} public enum MyResilientEnum { case kevin case loki } // CHECK-LABEL: sil @$S15enum_resilience15resilientSwitchyyAA15MyResilientEnumOF : $@convention(thin) (@in MyResilientEnum) -> () // CHECK: switch_enum_addr %2 : $*MyResilientEnum, case #MyResilientEnum.kevin!enumelt: bb1, case #MyResilientEnum.loki!enumelt: bb2 // // CHECK: return public func resilientSwitch(_ e: MyResilientEnum) { switch e { case .kevin: () case .loki: () } } // Inlineable functions must lower the switch as if it came from outside the module // CHECK-LABEL: sil [serialized] @$S15enum_resilience16inlineableSwitchyyAA15MyResilientEnumOF : $@convention(thin) (@in MyResilientEnum) -> () // CHECK: switch_enum_addr %2 : $*MyResilientEnum, case #MyResilientEnum.kevin!enumelt: bb1, case #MyResilientEnum.loki!enumelt: bb2, default bb3 // CHECK: return @_inlineable public func inlineableSwitch(_ e: MyResilientEnum) { switch e { case .kevin: () case .loki: () } }
2dc9c468d1cb2809213d6f1405b5a624
41.851852
209
0.677615
false
false
false
false
overtake/TelegramSwift
refs/heads/master
packages/TGUIKit/Sources/SelectingControl.swift
gpl-2.0
1
// // SelectingControl.swift // TGUIKit // // Created by keepcoder on 27/10/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa public class SelectingControl: Control { private var selectedView:ImageView? private let unselectedView = ImageView() private var unselectedImage:CGImage private var selectedImage:CGImage public init(unselectedImage:CGImage, selectedImage:CGImage, selected: Bool = false) { self.unselectedImage = unselectedImage self.selectedImage = selectedImage self.unselectedView.image = unselectedImage self.unselectedView.sizeToFit() super.init(frame:NSMakeRect(0, 0, max(unselectedImage.backingSize.width ,selectedImage.backingSize.width ), max(unselectedImage.backingSize.height,selectedImage.backingSize.height ))) userInteractionEnabled = false addSubview(unselectedView) self.set(selected: selected, animated: false) } public override func layout() { super.layout() unselectedView.center() selectedView?.center() } public func set(selected:Bool, animated:Bool = false) { if selected != isSelected { self.isSelected = selected if selected { if selectedView == nil { selectedView = ImageView() addSubview(selectedView!) selectedView!.image = selectedImage selectedView!.sizeToFit() selectedView!.center() if animated { selectedView!.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) selectedView!.layer?.animateScaleSpring(from: 0.2, to: 1.0, duration: 0.3) } } } else { if let selectedView = self.selectedView { self.selectedView = nil if animated { selectedView.layer?.animateScaleSpring(from: 1, to: 0.2, duration: 0.3, removeOnCompletion: false) selectedView.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak selectedView] _ in selectedView?.removeFromSuperview() }) } else { selectedView.removeFromSuperview() } } } } } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required public init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } public override func draw(_ layer: CALayer, in ctx: CGContext) { } }
00bc986f7fa3016eeeaf9354202dc24c
33.719512
191
0.567264
false
false
false
false
GraphQLSwift/GraphQL
refs/heads/main
Sources/GraphQL/Subscription/EventStream.swift
mit
1
/// Abstract event stream class - Should be overridden for actual implementations open class EventStream<Element> { public init() {} /// Template method for mapping an event stream to a new generic type - MUST be overridden by implementing types. open func map<To>(_: @escaping (Element) throws -> To) -> EventStream<To> { fatalError("This function should be overridden by implementing classes") } } #if compiler(>=5.5) && canImport(_Concurrency) @available(macOS 12, iOS 15, watchOS 8, tvOS 15, *) /// Event stream that wraps an `AsyncThrowingStream` from Swift's standard concurrency system. public class ConcurrentEventStream<Element>: EventStream<Element> { public let stream: AsyncThrowingStream<Element, Error> public init(_ stream: AsyncThrowingStream<Element, Error>) { self.stream = stream } /// Performs the closure on each event in the current stream and returns a stream of the results. /// - Parameter closure: The closure to apply to each event in the stream /// - Returns: A stream of the results override open func map<To>(_ closure: @escaping (Element) throws -> To) -> ConcurrentEventStream<To> { let newStream = stream.mapStream(closure) return ConcurrentEventStream<To>.init(newStream) } } @available(macOS 12, iOS 15, watchOS 8, tvOS 15, *) extension AsyncThrowingStream { func mapStream<To>(_ closure: @escaping (Element) throws -> To) -> AsyncThrowingStream<To, Error> { return AsyncThrowingStream<To, Error> { continuation in let task = Task { do { for try await event in self { let newEvent = try closure(event) continuation.yield(newEvent) } continuation.finish() } catch { continuation.finish(throwing: error) } } continuation.onTermination = { @Sendable reason in task.cancel() } } } func filterStream(_ isIncluded: @escaping (Element) throws -> Bool) -> AsyncThrowingStream<Element, Error> { return AsyncThrowingStream<Element, Error> { continuation in let task = Task { do { for try await event in self { if try isIncluded(event) { continuation.yield(event) } } continuation.finish() } catch { continuation.finish(throwing: error) } } continuation.onTermination = { @Sendable _ in task.cancel() } } } } #endif
4b060c7be6430c6d8c032d5e9e94119e
37.3125
117
0.523002
false
false
false
false
Flinesoft/Imperio
refs/heads/stable
Demo/Modules/Tutorial/TutorialFlowController.swift
mit
1
// // TutorialFlowController.swift // Imperio // // Created by Cihat Gündüz on 01.11.17. // Copyright © 2017 Flinesoft. All rights reserved. // import Imperio import UIKit // NOTE: In this case we have multiple view controllers to be navigated between using the flow controller. Please note that we are using the built-in // back navigation functionality from the navigation controller and are not explicitly implementing this ourselves. Let's keep things simple. class TutorialFlowController: FlowController { var navigationCtrl: UINavigationController? override func start(from presentingViewController: UIViewController) { let page1ViewCtrl = Page1ViewController() navigationCtrl = UINavigationController(rootViewController: page1ViewCtrl) page1ViewCtrl.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(doneButtonPressed)) page1ViewCtrl.flowDelegate = self presentingViewController.present(navigationCtrl!, animated: true) } @objc func doneButtonPressed() { navigationCtrl?.dismiss(animated: true) } } extension TutorialFlowController: Page1FlowDelegate { func nextToPage2ButtonPressed() { let page2ViewCtrl = Page2ViewController() page2ViewCtrl.flowDelegate = self navigationCtrl?.pushViewController(page2ViewCtrl, animated: true) } } extension TutorialFlowController: Page2FlowDelegate { func nextToPage3ButtonPressed() { let page3ViewCtrl = Page3ViewController() page3ViewCtrl.flowDelegate = self navigationCtrl?.pushViewController(page3ViewCtrl, animated: true) } } extension TutorialFlowController: Page3FlowDelegate { func completeButtonPressed() { navigationCtrl?.dismiss(animated: true) { self.removeFromSuperFlowController() } } }
ec99de5a252a5640ee9ebe4f9229b0fe
31.672414
154
0.74248
false
false
false
false
kirmani/lockman
refs/heads/master
iOS/Lockman/Lockman/SecondViewController.swift
mit
1
// // SecondViewController.swift // fingerprintTest // // Created by Yuriy Minin on 11/7/15. // Copyright © 2015 Yuriy Minin. All rights reserved. // import UIKit import Alamofire var lockID = "" var faces = "" class SecondViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() Alamofire.request(.GET, baseURL + "/list").validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let id_list = JSON(value) for result in id_list["result"].arrayValue { let url = baseURL + "/id/" + result.stringValue Alamofire.request(.GET, url).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) self.peopleLabel.text = "You have " + json["result"]["faces"].stringValue + " friends in this photo." let image: UIImage = UIImage(data: NSData(base64EncodedString: json["result"]["image"].stringValue, options: NSDataBase64DecodingOptions())!)! self.img.image = image lockID = result.stringValue } case .Failure(let error): print(error) } } } } case .Failure(let error): print(error) } } // Do any additional setup after loading the view, typically from a nib. } @IBOutlet weak var img: UIImageView! @IBOutlet weak var peopleLabel: UILabel! @IBAction func approved(recognizer: UISwipeGestureRecognizer) { UIView.animateWithDuration(0.4, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.img.alpha = 0.0 }, completion: nil) Alamofire.request(.PUT, baseURL + "/id/" + lockID + "/approve") print(baseURL + "/id/" + lockID + "/approve") Alamofire.request(.GET, baseURL + "/list").validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let id_list = JSON(value) for result in id_list["result"].arrayValue { let url = baseURL + "/id/" + result.stringValue Alamofire.request(.GET, url).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) self.peopleLabel.text = "You have " + json["result"]["faces"].stringValue + " friends in this photo." let image: UIImage = UIImage(data: NSData(base64EncodedString: json["result"]["image"].stringValue, options: NSDataBase64DecodingOptions())!)! self.img.image = image } case .Failure(let error): print(error) } } } } case .Failure(let error): print(error) } } UIView.animateWithDuration(0.4, delay: 1.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.img.alpha = 100.0 }, completion: nil) } @IBAction func denied(recognizer: UISwipeGestureRecognizer) { UIView.animateWithDuration(0.4, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.img.alpha = 0.0 }, completion: nil) Alamofire.request(.PUT, baseURL + "/id/" + lockID + "/deny") print(baseURL + "/id/" + lockID + "/deny") Alamofire.request(.GET, baseURL + "/list").validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let id_list = JSON(value) for result in id_list["result"].arrayValue { let url = baseURL + "/id/" + result.stringValue Alamofire.request(.GET, url).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) self.peopleLabel.text = "You have " + json["result"]["faces"].stringValue + " friends in this photo." let image: UIImage = UIImage(data: NSData(base64EncodedString: json["result"]["image"].stringValue, options: NSDataBase64DecodingOptions())!)! self.img.image = image lockID = result.stringValue } case .Failure(let error): print(error) } } } } case .Failure(let error): print(error) } } UIView.animateWithDuration(0.4, delay: 1.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.img.alpha = 100.0 }, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
8a9347fa8482b18f74911b81d9163484
41.371622
178
0.469144
false
false
false
false
GrouponChina/groupon-up
refs/heads/master
Groupon UP/Groupon UP/StringMD5.swift
apache-2.0
1
// // StringMD5.swift // Groupon UP // // Created by Robert Xue on 11/22/15. // Copyright © 2015 Chang Liu. All rights reserved. // import UIKit extension String { func md5() -> String! { let str = self.cStringUsingEncoding(NSUTF8StringEncoding) let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) CC_MD5(str!, strLen, result) let hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.destroy() return String(format: hash as String) } }
beac12aae4c350e30cf14c85956f0ea0
25.137931
88
0.610304
false
false
false
false
koba-uy/chivia-app-ios
refs/heads/master
src/Pods/Pulley/PulleyLib/PulleyViewController.swift
lgpl-3.0
1
// // PulleyViewController.swift // Pulley // // Created by Brendan Lee on 7/6/16. // Copyright © 2016 52inc. All rights reserved. // import UIKit /** * The base delegate protocol for Pulley delegates. */ @objc public protocol PulleyDelegate: class { @objc optional func drawerPositionDidChange(drawer: PulleyViewController) @objc optional func makeUIAdjustmentsForFullscreen(progress: CGFloat) @objc optional func drawerChangedDistanceFromBottom(drawer: PulleyViewController, distance: CGFloat) } /** * View controllers in the drawer can implement this to receive changes in state or provide values for the different drawer positions. */ public protocol PulleyDrawerViewControllerDelegate: PulleyDelegate { func collapsedDrawerHeight() -> CGFloat func partialRevealDrawerHeight() -> CGFloat func supportedDrawerPositions() -> [PulleyPosition] } /** * View controllers that are the main content can implement this to receive changes in state. */ public protocol PulleyPrimaryContentControllerDelegate: PulleyDelegate { // Not currently used for anything, but it's here for parity with the hopes that it'll one day be used. } /** * A completion block used for animation callbacks. */ public typealias PulleyAnimationCompletionBlock = ((_ finished: Bool) -> Void) /** Represents a Pulley drawer position. - collapsed: When the drawer is in its smallest form, at the bottom of the screen. - partiallyRevealed: When the drawer is partially revealed. - open: When the drawer is fully open. - closed: When the drawer is off-screen at the bottom of the view. Note: Users cannot close or reopen the drawer on their own. You must set this programatically */ public enum PulleyPosition: Int { case collapsed = 0 case partiallyRevealed = 1 case open = 2 case closed = 3 public static let all: [PulleyPosition] = [ .collapsed, .partiallyRevealed, .open, .closed ] public static func positionFor(string: String?) -> PulleyPosition { guard let positionString = string?.lowercased() else { return .collapsed } switch positionString { case "collapsed": return .collapsed case "partiallyrevealed": return .partiallyRevealed case "open": return .open case "closed": return .closed default: print("PulleyViewController: Position for string '\(positionString)' not found. Available values are: collapsed, partiallyRevealed, open, and closed. Defaulting to collapsed.") return .collapsed } } } private let kPulleyDefaultCollapsedHeight: CGFloat = 68.0 private let kPulleyDefaultPartialRevealHeight: CGFloat = 264.0 open class PulleyViewController: UIViewController { // Interface Builder /// When using with Interface Builder only! Connect a containing view to this outlet. @IBOutlet public var primaryContentContainerView: UIView! /// When using with Interface Builder only! Connect a containing view to this outlet. @IBOutlet public var drawerContentContainerView: UIView! // Internal fileprivate let primaryContentContainer: UIView = UIView() fileprivate let drawerContentContainer: UIView = UIView() fileprivate let drawerShadowView: UIView = UIView() fileprivate let drawerScrollView: PulleyPassthroughScrollView = PulleyPassthroughScrollView() fileprivate let backgroundDimmingView: UIView = UIView() fileprivate var dimmingViewTapRecognizer: UITapGestureRecognizer? fileprivate var lastDragTargetContentOffset: CGPoint = CGPoint.zero /// The current content view controller (shown behind the drawer). public fileprivate(set) var primaryContentViewController: UIViewController! { willSet { guard let controller = primaryContentViewController else { return; } controller.view.removeFromSuperview() controller.willMove(toParentViewController: nil) controller.removeFromParentViewController() } didSet { guard let controller = primaryContentViewController else { return; } controller.view.translatesAutoresizingMaskIntoConstraints = true self.primaryContentContainer.addSubview(controller.view) self.addChildViewController(controller) controller.didMove(toParentViewController: self) if self.isViewLoaded { self.view.setNeedsLayout() self.setNeedsSupportedDrawerPositionsUpdate() } } } /// The current drawer view controller (shown in the drawer). public fileprivate(set) var drawerContentViewController: UIViewController! { willSet { guard let controller = drawerContentViewController else { return; } controller.view.removeFromSuperview() controller.willMove(toParentViewController: nil) controller.removeFromParentViewController() } didSet { guard let controller = drawerContentViewController else { return; } controller.view.translatesAutoresizingMaskIntoConstraints = true self.drawerContentContainer.addSubview(controller.view) self.addChildViewController(controller) controller.didMove(toParentViewController: self) if self.isViewLoaded { self.view.setNeedsLayout() self.setNeedsSupportedDrawerPositionsUpdate() } } } /// The content view controller and drawer controller can receive delegate events already. This lets another object observe the changes, if needed. public weak var delegate: PulleyDelegate? /// The current position of the drawer. public fileprivate(set) var drawerPosition: PulleyPosition = .collapsed { didSet { setNeedsStatusBarAppearanceUpdate() } } /// The background visual effect layer for the drawer. By default this is the extraLight effect. You can change this if you want, or assign nil to remove it. public var drawerBackgroundVisualEffectView: UIVisualEffectView? = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight)) { willSet { drawerBackgroundVisualEffectView?.removeFromSuperview() } didSet { if let drawerBackgroundVisualEffectView = drawerBackgroundVisualEffectView, self.isViewLoaded { drawerScrollView.insertSubview(drawerBackgroundVisualEffectView, aboveSubview: drawerShadowView) drawerBackgroundVisualEffectView.clipsToBounds = true drawerBackgroundVisualEffectView.layer.cornerRadius = drawerCornerRadius } } } /// The inset from the top of the view controller when fully open. @IBInspectable public var topInset: CGFloat = 50.0 { didSet { if self.isViewLoaded { self.view.setNeedsLayout() } } } /// The corner radius for the drawer. @IBInspectable public var drawerCornerRadius: CGFloat = 13.0 { didSet { if self.isViewLoaded { self.view.setNeedsLayout() drawerBackgroundVisualEffectView?.layer.cornerRadius = drawerCornerRadius } } } /// The opacity of the drawer shadow. @IBInspectable public var shadowOpacity: Float = 0.1 { didSet { if self.isViewLoaded { self.view.setNeedsLayout() } } } /// The radius of the drawer shadow. @IBInspectable public var shadowRadius: CGFloat = 3.0 { didSet { if self.isViewLoaded { self.view.setNeedsLayout() } } } /// The opaque color of the background dimming view. @IBInspectable public var backgroundDimmingColor: UIColor = UIColor.black { didSet { if self.isViewLoaded { backgroundDimmingView.backgroundColor = backgroundDimmingColor } } } /// The maximum amount of opacity when dimming. @IBInspectable public var backgroundDimmingOpacity: CGFloat = 0.5 { didSet { if self.isViewLoaded { self.scrollViewDidScroll(drawerScrollView) } } } /// The starting position for the drawer when it first loads public var initialDrawerPosition: PulleyPosition = .collapsed /// This is here exclusively to support IBInspectable in Interface Builder because Interface Builder can't deal with enums. If you're doing this in code use the -initialDrawerPosition property instead. Available strings are: open, closed, partiallyRevealed, collapsed @IBInspectable public var initialDrawerPositionFromIB: String? { didSet { initialDrawerPosition = PulleyPosition.positionFor(string: initialDrawerPositionFromIB) } } /// The drawer positions supported by the drawer fileprivate var supportedDrawerPositions: [PulleyPosition] = PulleyPosition.all { didSet { guard self.isViewLoaded else { return } guard supportedDrawerPositions.count > 0 else { supportedDrawerPositions = PulleyPosition.all return } self.view.setNeedsLayout() if supportedDrawerPositions.contains(drawerPosition) { setDrawerPosition(position: drawerPosition) } else { let lowestDrawerState: PulleyPosition = supportedDrawerPositions.min { (pos1, pos2) -> Bool in return pos1.rawValue < pos2.rawValue } ?? .collapsed setDrawerPosition(position: lowestDrawerState, animated: false) } drawerScrollView.isScrollEnabled = supportedDrawerPositions.count > 1 } } /** Initialize the drawer controller programmtically. - parameter contentViewController: The content view controller. This view controller is shown behind the drawer. - parameter drawerViewController: The view controller to display inside the drawer. - note: The drawer VC is 20pts too tall in order to have some extra space for the bounce animation. Make sure your constraints / content layout take this into account. - returns: A newly created Pulley drawer. */ required public init(contentViewController: UIViewController, drawerViewController: UIViewController) { super.init(nibName: nil, bundle: nil) ({ self.primaryContentViewController = contentViewController self.drawerContentViewController = drawerViewController })() } /** Initialize the drawer controller from Interface Builder. - note: Usage notes: Make 2 container views in Interface Builder and connect their outlets to -primaryContentContainerView and -drawerContentContainerView. Then use embed segues to place your content/drawer view controllers into the appropriate container. - parameter aDecoder: The NSCoder to decode from. - returns: A newly created Pulley drawer. */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func loadView() { super.loadView() // IB Support if primaryContentContainerView != nil { primaryContentContainerView.removeFromSuperview() } if drawerContentContainerView != nil { drawerContentContainerView.removeFromSuperview() } // Setup primaryContentContainer.backgroundColor = UIColor.white definesPresentationContext = true drawerScrollView.bounces = false drawerScrollView.delegate = self drawerScrollView.clipsToBounds = false drawerScrollView.showsVerticalScrollIndicator = false drawerScrollView.showsHorizontalScrollIndicator = false drawerScrollView.delaysContentTouches = true drawerScrollView.canCancelContentTouches = true drawerScrollView.backgroundColor = UIColor.clear drawerScrollView.decelerationRate = UIScrollViewDecelerationRateFast drawerScrollView.scrollsToTop = false drawerScrollView.touchDelegate = self drawerShadowView.layer.shadowOpacity = shadowOpacity drawerShadowView.layer.shadowRadius = shadowRadius drawerShadowView.backgroundColor = UIColor.clear drawerContentContainer.backgroundColor = UIColor.clear backgroundDimmingView.backgroundColor = backgroundDimmingColor backgroundDimmingView.isUserInteractionEnabled = false backgroundDimmingView.alpha = 0.0 drawerBackgroundVisualEffectView?.clipsToBounds = true dimmingViewTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(PulleyViewController.dimmingViewTapRecognizerAction(gestureRecognizer:))) backgroundDimmingView.addGestureRecognizer(dimmingViewTapRecognizer!) drawerScrollView.addSubview(drawerShadowView) if let drawerBackgroundVisualEffectView = drawerBackgroundVisualEffectView { drawerScrollView.addSubview(drawerBackgroundVisualEffectView) drawerBackgroundVisualEffectView.layer.cornerRadius = drawerCornerRadius } drawerScrollView.addSubview(drawerContentContainer) primaryContentContainer.backgroundColor = UIColor.white self.view.backgroundColor = UIColor.white self.view.addSubview(primaryContentContainer) self.view.addSubview(backgroundDimmingView) self.view.addSubview(drawerScrollView) } override open func viewDidLoad() { super.viewDidLoad() // IB Support if primaryContentViewController == nil || drawerContentViewController == nil { assert(primaryContentContainerView != nil && drawerContentContainerView != nil, "When instantiating from Interface Builder you must provide container views with an embedded view controller.") // Locate main content VC for child in self.childViewControllers { if child.view == primaryContentContainerView.subviews.first { primaryContentViewController = child } if child.view == drawerContentContainerView.subviews.first { drawerContentViewController = child } } assert(primaryContentViewController != nil && drawerContentViewController != nil, "Container views must contain an embedded view controller.") } setDrawerPosition(position: initialDrawerPosition, animated: false) scrollViewDidScroll(drawerScrollView) } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setNeedsSupportedDrawerPositionsUpdate() } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // Layout main content primaryContentContainer.frame = self.view.bounds backgroundDimmingView.frame = self.view.bounds // Layout container var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { collapsedHeight = drawerVCCompliant.collapsedDrawerHeight() partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight() } let lowestStop = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight].min() ?? 0 let bounceOverflowMargin: CGFloat = 20.0 if supportedDrawerPositions.contains(.open) { // Layout scrollview drawerScrollView.frame = CGRect(x: 0, y: topInset, width: self.view.bounds.width, height: self.view.bounds.height - topInset) } else { // Layout scrollview let adjustedTopInset: CGFloat = supportedDrawerPositions.contains(.partiallyRevealed) ? partialRevealHeight : collapsedHeight drawerScrollView.frame = CGRect(x: 0, y: self.view.bounds.height - adjustedTopInset, width: self.view.bounds.width, height: adjustedTopInset) } drawerContentContainer.frame = CGRect(x: 0, y: drawerScrollView.bounds.height - lowestStop, width: drawerScrollView.bounds.width, height: drawerScrollView.bounds.height + bounceOverflowMargin) drawerBackgroundVisualEffectView?.frame = drawerContentContainer.frame drawerShadowView.frame = drawerContentContainer.frame drawerScrollView.contentSize = CGSize(width: drawerScrollView.bounds.width, height: (drawerScrollView.bounds.height - lowestStop) + drawerScrollView.bounds.height) // Update rounding mask and shadows let borderPath = UIBezierPath(roundedRect: drawerContentContainer.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: drawerCornerRadius, height: drawerCornerRadius)).cgPath let cardMaskLayer = CAShapeLayer() cardMaskLayer.path = borderPath cardMaskLayer.frame = drawerContentContainer.bounds cardMaskLayer.fillColor = UIColor.white.cgColor cardMaskLayer.backgroundColor = UIColor.clear.cgColor drawerContentContainer.layer.mask = cardMaskLayer drawerShadowView.layer.shadowPath = borderPath // Make VC views match frames primaryContentViewController?.view.frame = primaryContentContainer.bounds drawerContentViewController?.view.frame = CGRect(x: drawerContentContainer.bounds.minX, y: drawerContentContainer.bounds.minY, width: drawerContentContainer.bounds.width, height: drawerContentContainer.bounds.height) setDrawerPosition(position: drawerPosition, animated: false) } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Configuration Updates /** Set the drawer position, with an option to animate. - parameter position: The position to set the drawer to. - parameter animated: Whether or not to animate the change. (Default: true) - parameter completion: A block object to be executed when the animation sequence ends. The Bool indicates whether or not the animations actually finished before the completion handler was called. (Default: nil) */ public func setDrawerPosition(position: PulleyPosition, animated: Bool, completion: PulleyAnimationCompletionBlock? = nil) { guard supportedDrawerPositions.contains(position) else { print("PulleyViewController: You can't set the drawer position to something not supported by the current view controller contained in the drawer. If you haven't already, you may need to implement the PulleyDrawerViewControllerDelegate.") return } drawerPosition = position var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { collapsedHeight = drawerVCCompliant.collapsedDrawerHeight() partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight() } let stopToMoveTo: CGFloat switch drawerPosition { case .collapsed: stopToMoveTo = collapsedHeight case .partiallyRevealed: stopToMoveTo = partialRevealHeight case .open: stopToMoveTo = (self.view.bounds.size.height - topInset) case .closed: stopToMoveTo = 0 } let drawerStops = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight] let lowestStop = drawerStops.min() ?? 0 if animated { UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.0, options: .curveEaseInOut, animations: { [weak self] () -> Void in self?.drawerScrollView.setContentOffset(CGPoint(x: 0, y: stopToMoveTo - lowestStop), animated: false) if let drawer = self { drawer.delegate?.drawerPositionDidChange?(drawer: drawer) (drawer.drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerPositionDidChange?(drawer: drawer) (drawer.primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerPositionDidChange?(drawer: drawer) drawer.view.layoutIfNeeded() } }, completion: { (completed) in completion?(completed) }) } else { drawerScrollView.setContentOffset(CGPoint(x: 0, y: stopToMoveTo - lowestStop), animated: false) delegate?.drawerPositionDidChange?(drawer: self) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerPositionDidChange?(drawer: self) (primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerPositionDidChange?(drawer: self) completion?(true) } } /** Set the drawer position, the change will be animated. - parameter position: The position to set the drawer to. */ public func setDrawerPosition(position: PulleyPosition) { setDrawerPosition(position: position, animated: true) } /** Change the current primary content view controller (The one behind the drawer) - parameter controller: The controller to replace it with - parameter animated: Whether or not to animate the change. Defaults to true. - parameter completion: A block object to be executed when the animation sequence ends. The Bool indicates whether or not the animations actually finished before the completion handler was called. */ public func setPrimaryContentViewController(controller: UIViewController, animated: Bool = true, completion: PulleyAnimationCompletionBlock?) { if animated { UIView.transition(with: primaryContentContainer, duration: 0.5, options: .transitionCrossDissolve, animations: { [weak self] () -> Void in self?.primaryContentViewController = controller }, completion: { (completed) in completion?(completed) }) } else { primaryContentViewController = controller completion?(true) } } /** Change the current primary content view controller (The one behind the drawer). This method exists for backwards compatibility. - parameter controller: The controller to replace it with - parameter animated: Whether or not to animate the change. Defaults to true. */ public func setPrimaryContentViewController(controller: UIViewController, animated: Bool = true) { setPrimaryContentViewController(controller: controller, animated: animated, completion: nil) } /** Change the current drawer content view controller (The one inside the drawer) - parameter controller: The controller to replace it with - parameter animated: Whether or not to animate the change. - parameter completion: A block object to be executed when the animation sequence ends. The Bool indicates whether or not the animations actually finished before the completion handler was called. */ public func setDrawerContentViewController(controller: UIViewController, animated: Bool = true, completion: PulleyAnimationCompletionBlock?) { if animated { UIView.transition(with: drawerContentContainer, duration: 0.5, options: .transitionCrossDissolve, animations: { [weak self] () -> Void in self?.drawerContentViewController = controller self?.setDrawerPosition(position: self?.drawerPosition ?? .collapsed, animated: false) }, completion: { (completed) in completion?(completed) }) } else { drawerContentViewController = controller setDrawerPosition(position: drawerPosition, animated: false) completion?(true) } } /** Change the current drawer content view controller (The one inside the drawer). This method exists for backwards compatibility. - parameter controller: The controller to replace it with - parameter animated: Whether or not to animate the change. */ public func setDrawerContentViewController(controller: UIViewController, animated: Bool = true) { setDrawerContentViewController(controller: controller, animated: animated, completion: nil) } /** Update the supported drawer positions allows by the Pulley Drawer */ public func setNeedsSupportedDrawerPositionsUpdate() { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { supportedDrawerPositions = drawerVCCompliant.supportedDrawerPositions() } else { supportedDrawerPositions = PulleyPosition.all } } // MARK: Actions func dimmingViewTapRecognizerAction(gestureRecognizer: UITapGestureRecognizer) { if gestureRecognizer == dimmingViewTapRecognizer { if gestureRecognizer.state == .ended { self.setDrawerPosition(position: .collapsed, animated: true) } } } // MARK: Propogate child view controller style / status bar presentation based on drawer state override open var childViewControllerForStatusBarStyle: UIViewController? { get { if drawerPosition == .open { return drawerContentViewController } return primaryContentViewController } } override open var childViewControllerForStatusBarHidden: UIViewController? { get { if drawerPosition == .open { return drawerContentViewController } return primaryContentViewController } } } extension PulleyViewController: PulleyPassthroughScrollViewDelegate { func shouldTouchPassthroughScrollView(scrollView: PulleyPassthroughScrollView, point: CGPoint) -> Bool { let contentDrawerLocation = drawerContentContainer.frame.origin.y if point.y < contentDrawerLocation { return true } return false } func viewToReceiveTouch(scrollView: PulleyPassthroughScrollView) -> UIView { if drawerPosition == .open { return backgroundDimmingView } return primaryContentContainer } } extension PulleyViewController: UIScrollViewDelegate { public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if scrollView == drawerScrollView { // Find the closest anchor point and snap there. var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { collapsedHeight = drawerVCCompliant.collapsedDrawerHeight() partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight() } var drawerStops: [CGFloat] = [CGFloat]() if supportedDrawerPositions.contains(.open) { drawerStops.append((self.view.bounds.size.height - topInset)) } if supportedDrawerPositions.contains(.partiallyRevealed) { drawerStops.append(partialRevealHeight) } if supportedDrawerPositions.contains(.collapsed) { drawerStops.append(collapsedHeight) } let lowestStop = drawerStops.min() ?? 0 let distanceFromBottomOfView = lowestStop + lastDragTargetContentOffset.y var currentClosestStop = lowestStop for currentStop in drawerStops { if abs(currentStop - distanceFromBottomOfView) < abs(currentClosestStop - distanceFromBottomOfView) { currentClosestStop = currentStop } } if abs(Float(currentClosestStop - (self.view.bounds.size.height - topInset))) <= Float.ulpOfOne && supportedDrawerPositions.contains(.open) { setDrawerPosition(position: .open, animated: true) } else if abs(Float(currentClosestStop - collapsedHeight)) <= Float.ulpOfOne && supportedDrawerPositions.contains(.collapsed) { setDrawerPosition(position: .collapsed, animated: true) } else if supportedDrawerPositions.contains(.partiallyRevealed){ setDrawerPosition(position: .partiallyRevealed, animated: true) } } } public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if scrollView == drawerScrollView { lastDragTargetContentOffset = targetContentOffset.pointee // Halt intertia targetContentOffset.pointee = scrollView.contentOffset } } public func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == drawerScrollView { var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { collapsedHeight = drawerVCCompliant.collapsedDrawerHeight() partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight() } var drawerStops: [CGFloat] = [CGFloat]() if supportedDrawerPositions.contains(.open) { drawerStops.append((self.view.bounds.size.height - topInset)) } if supportedDrawerPositions.contains(.partiallyRevealed) { drawerStops.append(partialRevealHeight) } if supportedDrawerPositions.contains(.collapsed) { drawerStops.append(collapsedHeight) } let lowestStop = drawerStops.min() ?? 0 if scrollView.contentOffset.y > partialRevealHeight - lowestStop { // Calculate percentage between partial and full reveal let fullRevealHeight = (self.view.bounds.size.height - topInset) let progress = (scrollView.contentOffset.y - (partialRevealHeight - lowestStop)) / (fullRevealHeight - (partialRevealHeight)) delegate?.makeUIAdjustmentsForFullscreen?(progress: progress) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: progress) (primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: progress) backgroundDimmingView.alpha = progress * backgroundDimmingOpacity backgroundDimmingView.isUserInteractionEnabled = true } else { if backgroundDimmingView.alpha >= 0.001 { backgroundDimmingView.alpha = 0.0 delegate?.makeUIAdjustmentsForFullscreen?(progress: 0.0) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: 0.0) (primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: 0.0) backgroundDimmingView.isUserInteractionEnabled = false } } delegate?.drawerChangedDistanceFromBottom?(drawer: self, distance: scrollView.contentOffset.y + lowestStop) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerChangedDistanceFromBottom?(drawer: self, distance: scrollView.contentOffset.y + lowestStop) (primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerChangedDistanceFromBottom?(drawer: self, distance: scrollView.contentOffset.y + lowestStop) } } }
b9c37e9d8f74224efc3e857fa9e7cd7b
38.539933
271
0.637222
false
false
false
false
darkerk/v2ex
refs/heads/master
V2EX/ViewControllers/ProfileViewController.swift
mit
1
// // ProfileViewController.swift // V2EX // // Created by darker on 2017/3/14. // Copyright © 2017年 darker. All rights reserved. // import UIKit import RxSwift import RxCocoa import Moya import PKHUD class ProfileViewController: UITableViewController { @IBOutlet weak var headerView: ProfileHeaderView! lazy var menuItems = [(#imageLiteral(resourceName: "slide_menu_topic"), "个人"), (#imageLiteral(resourceName: "slide_menu_message"), "消息"), (#imageLiteral(resourceName: "slide_menu_favorite"), "收藏"), (#imageLiteral(resourceName: "slide_menu_setting"), "设置")] private let disposeBag = DisposeBag() var navController: UINavigationController? { return drawerViewController?.centerViewController as? UINavigationController } override func viewDidLoad() { super.viewDidLoad() AppStyle.shared.themeUpdateVariable.asObservable().subscribe(onNext: { update in self.updateTheme() if update { self.headerView.updateTheme() self.tableView.reloadData() } }).disposed(by: disposeBag) tableView.delegate = nil tableView.dataSource = nil Account.shared.user.asObservable().bind(to: headerView.rx.user).disposed(by: disposeBag) Account.shared.isLoggedIn.asObservable().subscribe(onNext: {isLoggedIn in if !isLoggedIn { self.headerView.logout() } }).disposed(by: disposeBag) Observable.just(menuItems).bind(to: tableView.rx.items) { (tableView, row, item) in let cell: ProfileMenuViewCell = tableView.dequeueReusableCell() cell.updateTheme() cell.configure(image: item.0, text: item.1) return cell }.disposed(by: disposeBag) tableView.rx.itemSelected.subscribe(onNext: {[weak self] indexPath in guard let `self` = self else { return } self.tableView.deselectRow(at: indexPath, animated: true) guard let nav = self.navController else { return } guard Account.shared.isLoggedIn.value else { self.showLoginView() return } switch indexPath.row { case 0: self.drawerViewController?.isOpenDrawer = false TimelineViewController.show(from: nav, user: Account.shared.user.value) case 1: if Account.shared.unreadCount.value > 0 { Account.shared.unreadCount.value = 0 } self.drawerViewController?.isOpenDrawer = false nav.performSegue(withIdentifier: MessageViewController.segueId, sender: nil) case 2: self.drawerViewController?.isOpenDrawer = false nav.performSegue(withIdentifier: FavoriteViewController.segueId, sender: nil) case 3: self.drawerViewController?.isOpenDrawer = false nav.performSegue(withIdentifier: SettingViewController.segueId, sender: nil) default: break } }).disposed(by: disposeBag) if let cell = tableView.cellForRow(at: IndexPath(item: 1, section: 0)) as? ProfileMenuViewCell { Account.shared.unreadCount.asObservable().bind(to: cell.rx.unread).disposed(by: disposeBag) } Account.shared.isDailyRewards.asObservable().flatMapLatest { canRedeem -> Observable<Bool> in if canRedeem { return Account.shared.redeemDailyRewards() } return Observable.just(false) }.share(replay: 1).delay(1, scheduler: MainScheduler.instance).subscribe(onNext: { success in if success { HUD.showText("已领取每日登录奖励!") Account.shared.isDailyRewards.value = false } }, onError: { error in print(error.message) }).disposed(by: disposeBag) } @IBAction func loginButtonAction(_ sender: Any) { if let nav = navController, Account.shared.isLoggedIn.value { drawerViewController?.isOpenDrawer = false TimelineViewController.show(from: nav, user: Account.shared.user.value) }else { showLoginView() } } func showLoginView() { drawerViewController?.performSegue(withIdentifier: LoginViewController.segueId, sender: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
e41a6542bb6e984fa1a60af34b0f35ca
36.496063
105
0.597648
false
false
false
false
fancymax/12306ForMac
refs/heads/master
12306ForMac/UserControls/NSTableView+ContextMenu.swift
mit
1
// // NSTableView+ContextMenu.swift // 12306ForMac // // Created by fancymax on 2016/12/6. // Copyright © 2016年 fancy. All rights reserved. // import Foundation import Cocoa //user define Context Menu protocol ContextMenuDelegate: NSObjectProtocol { func tableView(aTableView:NSTableView, menuForRows rows:IndexSet) -> NSMenu? } extension NSTableView { open override func menu(for event: NSEvent) -> NSMenu? { let location = self.convert(event.locationInWindow, from: nil) let row = self.row(at: location) if ((row < 0) || (event.type != NSRightMouseDown)) { return super.menu(for: event) } var selected = self.selectedRowIndexes if !selected.contains(row) { selected = IndexSet(integer:row) self.selectRowIndexes(selected, byExtendingSelection: false) } if let contextMenuDelegate = self.delegate { if contextMenuDelegate.responds(to: Selector(("tableView:menuForRows:"))){ return (contextMenuDelegate as! ContextMenuDelegate).tableView(aTableView: self,menuForRows:selected) } } return super.menu(for: event) } }
59c257fad0863c1e0eac8b44ead286ec
28.238095
117
0.635993
false
false
false
false
lioonline/Swift
refs/heads/master
CoreLocation/CoreLocation/ViewController.swift
gpl-3.0
1
// // ViewController.swift // CoreLocation // // Created by Carlos Butron on 19/12/14. // Copyright (c) 2015 Carlos Butron. All rights reserved. // // This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later // version. // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License along with this program. If not, see // http:/www.gnu.org/licenses/. // import UIKit import CoreLocation import MapKit class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate { @IBOutlet weak var myMap: MKMapView! let locationManager: CLLocationManager = CLLocationManager() var myLatitude: CLLocationDegrees! var myLongitude: CLLocationDegrees! var finalLatitude: CLLocationDegrees! var finalLongitude: CLLocationDegrees! var distance: CLLocationDistance! override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() let tap = UITapGestureRecognizer(target: self, action: "action:") myMap.addGestureRecognizer(tap) } func action(gestureRecognizer:UIGestureRecognizer) { var touchPoint = gestureRecognizer.locationInView(self.myMap) var newCoord:CLLocationCoordinate2D = myMap.convertPoint(touchPoint, toCoordinateFromView: self.myMap) var getLat: CLLocationDegrees = newCoord.latitude var getLon: CLLocationDegrees = newCoord.longitude //Convert to points to CLLocation. In this way we can measure distanceFromLocation var newCoord2: CLLocation = CLLocation(latitude: getLat, longitude: getLon) var newCoord3: CLLocation = CLLocation(latitude: myLatitude, longitude: myLongitude) finalLatitude = newCoord2.coordinate.latitude finalLongitude = newCoord2.coordinate.longitude println("Original Latitude: \(myLatitude)") println("Original Longitude: \(myLongitude)") println("Final Latitude: \(finalLatitude)") println("Final Longitude: \(finalLongitude)") //distance between our position and the new point created let distance = newCoord2.distanceFromLocation(newCoord3) println("Distancia entre puntos: \(distance)") var newAnnotation = MKPointAnnotation() newAnnotation.coordinate = newCoord newAnnotation.title = "My target" newAnnotation.subtitle = "" myMap.addAnnotation(newAnnotation) } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in if (error != nil) { println("Reverse geocoder failed with error" + error.localizedDescription) return } if placemarks.count > 0 { let pm = placemarks[0] as CLPlacemark self.displayLocationInfo(pm) } else { println("Problem with the data received from geocoder") } }) } func displayLocationInfo(placemark: CLPlacemark?) { if let containsPlacemark = placemark { //stop updating location to save battery life locationManager.stopUpdatingLocation() //get data from placemark let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : "" let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : "" let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : "" let country = (containsPlacemark.country != nil) ? containsPlacemark.country : "" myLongitude = (containsPlacemark.location.coordinate.longitude) myLatitude = (containsPlacemark.location.coordinate.latitude) // testing show data println("Locality: \(locality)") println("PostalCode: \(postalCode)") println("Area: \(administrativeArea)") println("Country: \(country)") println(myLatitude) println(myLongitude) //update map with my location let theSpan:MKCoordinateSpan = MKCoordinateSpanMake(0.1 , 0.1) let location:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: myLatitude, longitude: myLongitude) let theRegion:MKCoordinateRegion = MKCoordinateRegionMake(location, theSpan) myMap.setRegion(theRegion, animated: true) } } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { println("Error while updating location " + error.localizedDescription) } //distance between two points func degreesToRadians(degrees: Double) -> Double { return degrees * M_PI / 180.0 } func radiansToDegrees(radians: Double) -> Double { return radians * 180.0 / M_PI } func getBearingBetweenTwoPoints1(point1 : CLLocation, point2 : CLLocation) -> Double { let lat1 = degreesToRadians(point1.coordinate.latitude) let lon1 = degreesToRadians(point1.coordinate.longitude) let lat2 = degreesToRadians(point2.coordinate.latitude); let lon2 = degreesToRadians(point2.coordinate.longitude); println("Latitud inicial: \(point1.coordinate.latitude)") println("Longitud inicial: \(point1.coordinate.longitude)") println("Latitud final: \(point2.coordinate.latitude)") println("Longitud final: \(point2.coordinate.longitude)") let dLon = lon2 - lon1; let y = sin(dLon) * cos(lat2); let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon); let radiansBearing = atan2(y, x); return radiansToDegrees(radiansBearing) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
e29d61cc217d503745c5d9cd51ea7cce
38.193182
126
0.649754
false
false
false
false
davidbjames/Unilib
refs/heads/master
Unilib/Sources/WeakArray.swift
mit
1
// // WeakArray.swift // C3 // // Created by David James on 2021-11-26. // Copyright © 2021 David B James. All rights reserved. // import Foundation /// Generic array wrapper that can hold its /// reference-based items either weakly or strongly. protocol CaptureArray : Collection, Elidable { associatedtype T:AnyObject associatedtype Wrapper var contents:[Wrapper] { get } var validItems:[T] { get } init(_ contents:[T]?) subscript(safe index:Array<Wrapper>.Index) -> T? { get } var strongify:StrongArray<T> { get } var weakify:WeakArray<T> { get } } extension CaptureArray { /// Ensure this capture array is a strong array. var strongify:StrongArray<T> { cast(StrongArray<T>.self) } /// Ensure this capture array is a weak array. var weakify:WeakArray<T> { cast(WeakArray<T>.self) } private func cast<C:CaptureArray>(_:C.Type) -> C where C.T == T { C(validItems) } /// Support `for..in` statements, iterating only /// those items which are still allocated. func makeIterator() -> Array<T>.Iterator { validItems.makeIterator() } // Indices remain according to original item order, // which is what you would expect at the call-site. // It's up to the developer to consider how that // might affect index-based access. var startIndex:Array<Wrapper>.Index { contents.startIndex } var endIndex:Array<Wrapper>.Index { contents.endIndex } func index(after i:Array<Wrapper>.Index) -> Array<Wrapper>.Index { contents.index(after:i) } } // DEV NOTE: This uses structs for WeakBox/WeakArray. // There is no advantage to using classes and would // only complicate the call-site. Since WeakBox holds // the references weakly (no retain count increment) // making copies of these structs wouldn't change this fact. /// Box to hold a reference type weakly so /// that storage doesn't prevent the item /// from deallocating properly. struct WeakBox<T:AnyObject> { weak var value:T? init(_ value:T) { self.value = value } } /// Array of weakly boxed reference-type items /// to be used when passing arrays into long-lived /// closures so that those items are not strongly /// held and may deallocate properly. struct WeakArray<T:AnyObject> : CaptureArray { var contents:[WeakBox<T>] init(_ contents:[T]?) { if let contents = contents { self.contents = contents.map { WeakBox($0) } } else { self.contents = [] } } /// Get the valid, still allocated, items. var validItems:[T] { contents.compactMap { $0.value } } /// Cleanup empty boxes where the stored item has been deallocated mutating func flush() { contents = contents.filter { $0.value.exists } } /// Get element at index if it exists and is /// still allocated, else nil. subscript(safe index:Array<WeakBox<T>>.Index) -> T? { indices.contains(index) ? contents[index].value : nil } /// Get element at index. /// /// In addition to standard crash if index /// is not valid, this will also crash if the /// boxed item has been deallocated. /// /// See also `subscript(safe:)`. subscript(position:Array<WeakBox<T>>.Index) -> T { contents[position].value! } func `as`<I:AnyObject>(_:I.Type) -> WeakArray<I> { WeakArray<I>(validItems.compactMap { $0 as? I }) } } /// Array of reference-type items held strongly. /// This is meant to be used generically or /// in-concert with WeakArray. /// On its own it adds nothing to an Array. struct StrongArray<T:AnyObject> : CaptureArray { var contents:[T] var validItems:[T] { contents } init(_ contents:[T]?) { self.contents = contents ?? [] } /// Get element at index if it exists and is /// still allocated, else nil. subscript(safe index:Array<T>.Index) -> T? { indices.contains(index) ? contents[index] : nil } /// Get element at index. /// /// See also `subscript(safe:)`. subscript(position:Array<T>.Index) -> T { contents[position] } func `as`<I:AnyObject>(_:I.Type) -> StrongArray<I> { StrongArray<I>(validItems.compactMap { $0 as? I }) } }
312857ebd02a079cd915a99e4f4a4b75
29.549296
70
0.629322
false
false
false
false
CaiMiao/CGSSGuide
refs/heads/master
DereGuide/Toolbox/Gacha/Detail/View/GachaSimulatorView.swift
mit
1
// // GachaSimulatorView.swift // DereGuide // // Created by zzk on 2016/9/15. // Copyright © 2016年 zzk. All rights reserved. // import UIKit protocol GachaSimulatorViewDelegate: class { func singleGacha(gachaSimulatorView: GachaSimulatorView) func tenGacha(gachaSimulatorView: GachaSimulatorView) func gachaSimulateView(_ gachaSimulatorView: GachaSimulatorView, didClick cardIcon:CGSSCardIconView) func resetResult(gachaSimulatorView: GachaSimulatorView) } class GachaSimulatorView: UIView { let space: CGFloat = 10 let btnW = min(96, (Screen.shortSide - 60) / 5) var leftLabel: UILabel! let singleButton = WideButton() let tenButton = WideButton() var resultView: UIView! var resultGrid: GridLabel! let resetButton = WideButton() weak var delegate: GachaSimulatorViewDelegate? override init(frame: CGRect) { super.init(frame: frame) leftLabel = UILabel() leftLabel.font = UIFont.systemFont(ofSize: 16) leftLabel.text = NSLocalizedString("模拟抽卡", comment: "") addSubview(leftLabel) leftLabel.snp.makeConstraints { (make) in make.left.equalTo(10) make.top.equalTo(10) } singleButton.setTitle(NSLocalizedString("单抽", comment: "模拟抽卡页面"), for: .normal) singleButton.backgroundColor = Color.passion singleButton.addTarget(self, action: #selector(clickSingle), for: .touchUpInside) addSubview(singleButton) singleButton.snp.makeConstraints { (make) in make.left.equalTo(10) make.width.equalToSuperview().dividedBy(2).offset(-15) make.top.equalTo(leftLabel.snp.bottom).offset(2 * btnW + 30) } tenButton.setTitle(NSLocalizedString("十连", comment: "模拟抽卡页面"), for: .normal) tenButton.backgroundColor = Color.cute tenButton.addTarget(self, action: #selector(clickTen), for: .touchUpInside) addSubview(tenButton) tenButton.snp.makeConstraints { (make) in make.right.equalTo(-10) make.width.equalToSuperview().dividedBy(2).offset(-15) make.top.equalTo(singleButton) } resultView = UIView() addSubview(resultView) resultView.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.top.equalTo(leftLabel.snp.bottom).offset(10) make.width.equalTo(btnW * 5 + 40) make.height.equalTo(2 * btnW + 10) } resultGrid = GridLabel(rows: 4, columns: 4) addSubview(resultGrid) resultGrid.snp.makeConstraints { (make) in make.top.equalTo(tenButton.snp.bottom).offset(10) make.left.equalTo(10) make.right.equalTo(-10) } resetButton.setTitle(NSLocalizedString("重置", comment: "模拟抽卡页面"), for: .normal) resetButton.backgroundColor = .cool resetButton.addTarget(self, action: #selector(clickReset), for: .touchUpInside) addSubview(resetButton) resetButton.snp.makeConstraints { (make) in make.left.equalTo(10) make.right.equalTo(-10) make.top.equalTo(resultGrid.snp.bottom).offset(10) make.bottom.equalTo(-10) } resultGrid.setContents([[NSLocalizedString("抽卡次数", comment: ""), "SSR", "SR", "R"], ["", "", "", ""], [NSLocalizedString("星星数", comment: ""), "SSR \(NSLocalizedString("占比", comment: ""))", "SR \(NSLocalizedString("占比", comment: ""))", "R \(NSLocalizedString("占比", comment: ""))"], ["", "", "", ""]]) backgroundColor = Color.cool.mixed(withColor: .white, weight: 0.9) } @objc private func clickTen() { delegate?.tenGacha(gachaSimulatorView: self) } @objc private func clickSingle() { delegate?.singleGacha(gachaSimulatorView: self) } @objc private func clickReset() { delegate?.resetResult(gachaSimulatorView: self) } func wipeResultView() { for subview in resultView.subviews { subview.removeFromSuperview() } } func wipeResultGrid() { resultGrid[1, 0].text = "" resultGrid[1, 1].text = "" resultGrid[1, 2].text = "" resultGrid[1, 3].text = "" resultGrid[3, 0].text = "" resultGrid[3, 1].text = "" resultGrid[3, 2].text = "" resultGrid[3, 3].text = "" } func setup(cardIDs: [Int], result: GachaSimulationResult) { wipeResultView() guard result.times > 0 else { return } for i in 0..<cardIDs.count { let x = CGFloat(i % 5) * (space + btnW) let y = CGFloat(i / 5) * (btnW + space) let btn = CGSSCardIconView.init(frame: CGRect.init(x: x, y: y, width: btnW, height: btnW)) btn.setWithCardId(cardIDs[i], target: self, action: #selector(iconClick(iv:))) if let card = CGSSDAO.shared.findCardById(cardIDs[i]), card.rarityType == .ssr { let view = UIView.init(frame: btn.frame) view.isUserInteractionEnabled = false view.addGlowAnimateAlongBorder(clockwise: true, imageName: "star", count: 3, cornerRadius: btn.fheight / 8) resultView.addSubview(view) view.tintColor = card.attColor } resultView.addSubview(btn) resultView.sendSubview(toBack: btn) } resultGrid[1, 0].text = "\(result.times)" resultGrid[1, 1].text = "\(result.ssrCount)" resultGrid[1, 2].text = "\(result.srCount)" resultGrid[1, 3].text = "\(result.rCount)" resultGrid[3, 0].text = "\(result.jewel)" resultGrid[3, 1].text = String.init(format: "%.2f%%", result.ssrRate * 100) resultGrid[3, 2].text = String.init(format: "%.2f%%", result.srRate * 100) resultGrid[3, 3].text = String.init(format: "%.2f%%", result.rRate * 100) } @objc func iconClick(iv: CGSSCardIconView) { delegate?.gachaSimulateView(self, didClick: iv) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
6fdb19b24a20ef0afa1581b913cdde20
37.301205
210
0.591381
false
false
false
false
JGiola/swift
refs/heads/main
test/Concurrency/Runtime/actor_keypaths.swift
apache-2.0
8
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking) // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime actor Page { let initialNumWords : Int private let numWordsMem: UnsafeMutablePointer<Int> nonisolated var numWords : Int { get { numWordsMem.pointee } set { numWordsMem.pointee = newValue } } private init(withWords words : Int) { initialNumWords = words numWordsMem = .allocate(capacity: 1) numWordsMem.initialize(to: words) } convenience init(_ words: Int) { self.init(withWords: words) numWords = words } deinit { numWordsMem.deallocate() } } actor Book { let pages : [Page] init(_ numPages : Int) { var stack : [Page] = [] for i in 0 ..< numPages { stack.append(Page(i)) } pages = stack } nonisolated subscript(_ page : Int) -> Page { return pages[page] } } func bookHasChanged(_ b : Book, currentGetter : KeyPath<Page, Int>, initialGetter : (Page) -> Int) -> Bool { let numPages = b[keyPath: \.pages.count] for i in 0 ..< numPages { let pageGetter = \Book.[i] let currentWords = pageGetter.appending(path: currentGetter) if (b[keyPath: currentWords] != initialGetter(b[keyPath: pageGetter])) { return true } } return false } func enumeratePageKeys(from : Int, to : Int) -> [KeyPath<Book, Page>] { var keys : [KeyPath<Book, Page>] = [] for i in from ..< to { keys.append(\Book.[i]) } return keys } func erasePages(_ book : Book, badPages: [KeyPath<Book, Page>]) { for page in badPages { book[keyPath: page].numWords = 0 } } let book = Book(100) if bookHasChanged(book, currentGetter: \Page.numWords, initialGetter: \Page.initialNumWords) { fatalError("book should not be changed") } erasePages(book, badPages: enumeratePageKeys(from: 0, to: 100)) guard bookHasChanged(book, currentGetter: \Page.numWords, initialGetter: \Page.initialNumWords) else { fatalError("book should be wiped!") }
933640a52b23ed4ad9179bd87ea72722
23.096774
102
0.610442
false
false
false
false
davejlin/treehouse
refs/heads/master
swift/swift2/voice-memo-saving-data-to-cloud/VoiceMemo/AppDelegate.swift
unlicense
1
// // AppDelegate.swift // VoiceMemo // // Created by Pasan Premaratne on 8/23/16. // Copyright © 2016 Treehouse Island, Inc. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.mainScreen().bounds) guard let window = window else { return false } window.backgroundColor = .whiteColor() let controller = ViewController() let navigationController = UINavigationController(rootViewController: controller) window.rootViewController = navigationController window.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
c6c1cc8471035ab775462ea62ab28489
43.101695
285
0.731745
false
false
false
false
GPWiOS/DouYuLive
refs/heads/master
DouYuTV/DouYuTV/Classes/Main/View/PageContentView.swift
mit
1
// // PageContentView.swift // DouYuTV // // Created by GaiPengwei on 2017/5/10. // Copyright © 2017年 GaiPengwei. All rights reserved. // import UIKit protocol PageContentViewDelegate : class { func pageContentView(_ pageContentView : PageContentView, progress : CGFloat, startIndex : Int, endIndex : Int) } fileprivate let CollectionCellID = "CollectionCellID" class PageContentView: UIView { // MARK - 定义属性 fileprivate var childVCs : [UIViewController] fileprivate weak var parentVC : UIViewController? fileprivate var startOffsetX : CGFloat = 0 fileprivate var isForbidScrollDelegate = false weak var delegate : PageContentViewDelegate? // MARK - 懒加载 fileprivate lazy var collectionView : UICollectionView = { [weak self] in // 1.创建layout let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = UICollectionViewScrollDirection.horizontal // 2.创建collectionView let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.showsVerticalScrollIndicator = false collectionView.bounces = false collectionView.isPagingEnabled = true collectionView.scrollsToTop = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: CollectionCellID) return collectionView }() // MARK - 自定义构造函数 init(frame: CGRect, childVCs: [UIViewController], parentVC: UIViewController?) { self.childVCs = childVCs self.parentVC = parentVC super.init(frame: frame) // 设置contentView setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK - 设置contentView的UI extension PageContentView { fileprivate func setupUI(){ // 1.将所有的子控制器添加父控制器中 for childVC in childVCs{ parentVC?.addChildViewController(childVC) } // 2.添加UICollectionView,用于cell存放控制器的view addSubview(collectionView) collectionView.frame = bounds } } // MARK - 遵守UICollectionViewDataSource extension PageContentView : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.childVCs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.创建cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionCellID, for: indexPath) // 2.设置cell内容 for view in cell.contentView.subviews{ view.removeFromSuperview() } let childVC = childVCs[indexPath.item] childVC.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVC.view) return cell } } // MARK - 遵守UICollectionViewDelegate extension PageContentView : UICollectionViewDelegate{ func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { // 0.判断是否是点击事件 if isForbidScrollDelegate { return } // 1.定义变量 var progress : CGFloat = 0 var startIndex : Int = 0 var endIndex :Int = 0 // 2.判断是左滑还是右滑 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX{ // 左滑 // 2.1 计算progress progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) startIndex = Int(currentOffsetX / scrollViewW) endIndex = startIndex + 1 if endIndex >= childVCs.count { endIndex = childVCs.count - 1 } // 2.2.如果完全划过去 if currentOffsetX - startOffsetX == scrollViewW { progress = 1 endIndex = startIndex } } else { // 右滑 // 2.1 计算右滑 progress progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) endIndex = Int(currentOffsetX / scrollViewW) startIndex = endIndex + 1 if startIndex >= childVCs.count { startIndex = childVCs.count - 1 } } // print("progress:\(progress) startIndex:\(startIndex) endIndex:\(endIndex)") delegate?.pageContentView(self, progress: progress, startIndex: startIndex, endIndex: endIndex) } } // MARK - 供给外部使用的方法 extension PageContentView{ func setupCurrentViewWithIndex(currentIndex : Int){ // 1.记录需要进制执行代理方法 isForbidScrollDelegate = true // 2.滚动正确的位置 let offX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x: offX, y: 0), animated: false) } }
781066c9860f1da47104db339e78bf6d
31.560976
121
0.639888
false
false
false
false
brentsimmons/Frontier
refs/heads/master
BeforeTheRename/FrontierData/FrontierData/List.swift
gpl-2.0
1
// // List.swift // FrontierData // // Created by Brent Simmons on 4/22/17. // Copyright © 2017 Ranchero Software. All rights reserved. // import Foundation // This is an immutable struct for now, and I hope it can stay that way, but we’ll see. // For example: you can build up a ListArray and then create a List struct when completed. public typealias ListArray = [Value] public struct List { let listArray: ListArray let count: Int subscript(n: Int) -> Value { get { return listArray[n] } } public init(_ listArray: ListArray) { self.listArray = listArray self.count = listArray.count } public init(value: Value) { var tempArray = ListArray() tempArray.append(value) self.init(tempArray) } func listByAdding(value: Value) -> List { var tempArray = listArray tempArray.append(value) return List(tempArray) } func listByRemovingValue(at ix: Int) -> List { assert(ix < count, "Can’t remove list value \(ix) when count is \(count)") if ix < count { return self } var tempArray = listArray tempArray.remove(at: ix) return List(tempArray) } func listByInserting(value: Value, at ix: Int) -> List { assert(ix <= count, "Can’t add list value at \(ix) when count is \(count)") if ix <= count { return self } if ix == count { return listByAdding(value: value) } var tempArray = listArray tempArray.insert(value, at: ix) return List(tempArray) } func isEqualTo(_ otherList: List) -> Bool { // Arrays aren’t Equatable, but we might need this. if count != otherList.count { return false } var ix = 0 for oneValue in listArray { do { if try !oneValue.equals(otherList[ix]) { return false } } catch { return false } ix = ix + 1 } return true } }
5a421cad70874b86b39b717273acff0e
18.031579
90
0.64823
false
false
false
false
ruslanskorb/CoreStore
refs/heads/master
Sources/ObjectRepresentation.swift
mit
1
// // ObjectRepresentation.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 CoreData // MARK - ObjectRepresentation /** An object that acts as interfaces for `CoreStoreObject`s or `NSManagedObject`s */ public protocol ObjectRepresentation { /** The object type represented by this protocol */ associatedtype ObjectType: DynamicObject /** The internal ID for the object. */ func objectID() -> ObjectType.ObjectID /** An instance that may be observed for object changes. */ func asPublisher(in dataStack: DataStack) -> ObjectPublisher<ObjectType> /** A read-only instance in the `DataStack`. */ func asReadOnly(in dataStack: DataStack) -> ObjectType? /** An instance that may be mutated within a `BaseDataTransaction`. */ func asEditable(in transaction: BaseDataTransaction) -> ObjectType? /** A thread-safe `struct` that is a full-copy of the object's properties */ func asSnapshot(in dataStack: DataStack) -> ObjectSnapshot<ObjectType>? /** A thread-safe `struct` that is a full-copy of the object's properties */ func asSnapshot(in transaction: BaseDataTransaction) -> ObjectSnapshot<ObjectType>? } extension NSManagedObject: ObjectRepresentation {} extension CoreStoreObject: ObjectRepresentation {} extension DynamicObject where Self: ObjectRepresentation { // MARK: ObjectRepresentation public func objectID() -> Self.ObjectID { return self.cs_id() } public func asPublisher(in dataStack: DataStack) -> ObjectPublisher<Self> { let context = dataStack.unsafeContext() return ObjectPublisher<Self>(objectID: self.cs_id(), context: context) } public func asReadOnly(in dataStack: DataStack) -> Self? { let context = dataStack.unsafeContext() if self.cs_toRaw().managedObjectContext == context { return self } return context.fetchExisting(self.cs_id()) } public func asEditable(in transaction: BaseDataTransaction) -> Self? { let context = transaction.unsafeContext() if self.cs_toRaw().managedObjectContext == context { return self } return context.fetchExisting(self.cs_id()) } public func asSnapshot(in dataStack: DataStack) -> ObjectSnapshot<Self>? { let context = dataStack.unsafeContext() return ObjectSnapshot<Self>(objectID: self.cs_id(), context: context) } public func asSnapshot(in transaction: BaseDataTransaction) -> ObjectSnapshot<Self>? { let context = transaction.unsafeContext() return ObjectSnapshot<Self>(objectID: self.cs_id(), context: context) } }
9318971d6ffb40f8da10427ebaedb929
30.672131
90
0.690994
false
false
false
false
yinyifu/cse442_watch
refs/heads/master
applewatch_mapping/SocialController.swift
mit
1
// // ViewController.swift // applewatch_mapping // // Created by yifu on 9/6/17. // Copyright © 2017 CSE442_UB. All rights reserved. // import UIKit import MapKit import CoreLocation import GoogleMaps import GooglePlaces //@interface MyLocationViewController : UIViewController <CLLocationManagerDelegate> class SocialController: UIViewController { let _sc : SessionController = SessionController(); private var mapController : MapController?; let range = 10 @IBAction func autocompleteClicked(_ sender: UIButton) { let autocompleteController = GMSAutocompleteViewController() autocompleteController.delegate = self present(autocompleteController, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad(); } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination as? MapController, segue.identifier == "socialSegue" { self.mapController = vc }else{ NSLog("Motherfucker didnt prepare"); } } func alerting(title: String, message: String){ let alert = UIAlertController(title: title, message: message, preferredStyle : UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } //trying to make uiimage @objc func getLoc(sender: UIButton, event: UIEvent){ //_sc.send_image() } } extension SocialController : GMSAutocompleteViewControllerDelegate { // Handle the user's selection. func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) { // runner.setCenter(place.coordinate) //let sboar : UIStoryboard = UIStoryboard(name:"Main", bundle:nil); if let map = self.mapController{ map.setCenter(place.coordinate) }else{ NSLog("Motherfucker didnt coord"); } NSLog("coor is \(place.coordinate.latitude) + \(place.coordinate.longitude)"); NSLog("runner is nil"); dismiss(animated: true, completion: nil) } func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) { // TODO: handle the error. print("Error: ", error.localizedDescription) } // User canceled the operation. func wasCancelled(_ viewController: GMSAutocompleteViewController) { dismiss(animated: true, completion: nil) } // Turn the network activity indicator on and off again. func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = true } func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = false } }
4f4164ee5ffc4494f3d5c65ee3975dc1
32.813187
117
0.683133
false
false
false
false
ello/ello-ios
refs/heads/master
Sources/Utilities/InterfaceImage.swift
mit
1
//// /// InterfaceImage.swift // import SVGKit enum InterfaceImage: String { enum Style { case normal case white case selected case disabled case red case green // used by the "watching" lightning bolt case orange // used by the "selected" star case dynamic case inverted } case elloLogo = "ello_logo" case elloType = "ello_type" case elloLogoGrey = "ello_logo_grey" case elloGrayLineLogo = "ello_gray_line_logo" // Post Action Icons case eye = "eye" case heart = "hearts" case heartOutline = "hearts_outline" case giantHeart = "hearts_giant" case repost = "repost" case share = "share" case xBox = "xbox" case pencil = "pencil" case reply = "reply" case flag = "flag" case featurePost = "feature_post" // Social logos case logoMedium = "logo_medium" // Badges case badgeFeatured = "badge_featured" // Location Marker Icon case marker = "marker" // Notification Icons case comments = "bubble" case commentsOutline = "bubble_outline" case invite = "relationships" case watch = "watch" // TabBar Icons case home = "home" case discover = "discover" case bolt = "bolt" case omni = "omni" case person = "person" case narrationPointer = "narration_pointer" // Validation States case validationLoading = "circ" case validationError = "x_red" case validationOK = "check_green" case smallCheck = "small_check_green" // NavBar Icons case search = "search" case searchField = "search_small" case burger = "burger" case gridView = "grid_view" case listView = "list_view" // Omnibar case reorder = "reorder" case photoPicker = "photo_picker" case textPicker = "text_picker" case camera = "camera" case library = "library" case check = "check" case link = "link" case breakLink = "breaklink" // Commenting case replyAll = "replyall" case bubbleBody = "bubble_body" case bubbleTail = "bubble_tail" // Hire me mail button case mail = "mail" // Profile case roleAdmin = "role_admin" // Alert case question = "question" // BuyButton case buyButton = "$" case addBuyButton = "$_add" case setBuyButton = "$_set" // OnePassword case onePassword = "1password" // Artist Invites case circleCheck = "circle_check" case circleCheckLarge = "circle_check_large" case star = "star" // "New Posts" arrow case arrowRight = "arrow_right" case arrowUp = "arrow_up" // Generic case x = "x" case dots = "dots" case dotsLight = "dots_light" case plusSmall = "plussmall" case checkSmall = "checksmall" case forwardChevron = "abracket" case backChevron = "chevron" // Embeds case audioPlay = "embetter_audio_play" case videoPlay = "embetter_video_play" func image(_ style: Style) -> UIImage? { switch style { case .normal: return normalImage case .white: return whiteImage case .selected: return selectedImage case .disabled: return disabledImage case .red: return redImage case .green: return greenImage case .orange: return orangeImage case .dynamic: if #available(iOS 13, *) { if UITraitCollection.current.userInterfaceStyle == .dark { return whiteImage } else { return normalImage } } else { return normalImage } case .inverted: if #available(iOS 13, *) { if UITraitCollection.current.userInterfaceStyle == .dark { return normalImage } else { return whiteImage } } else { return whiteImage } } } private static func svgkImage(_ name: String) -> SVGKImage? { return SVGKImage(named: "\(name).svg") } static func toUIImage(_ svgkImage: SVGKImage) -> UIImage { return svgkImage.uiImage.withRenderingMode(.alwaysOriginal) } var normalSVGK: SVGKImage? { switch self { case .audioPlay, .bubbleTail, .buyButton, .elloLogo, .elloLogoGrey, .elloGrayLineLogo, .giantHeart, .logoMedium, .marker, .narrationPointer, .validationError, .validationOK, .smallCheck, .videoPlay: return InterfaceImage.svgkImage(self.rawValue) default: return InterfaceImage.svgkImage("\(self.rawValue)_normal") } } var normalImage: UIImage! { return InterfaceImage.toUIImage(normalSVGK!) } var selectedSVGK: SVGKImage? { return InterfaceImage.svgkImage("\(self.rawValue)_selected") } var selectedImage: UIImage! { return InterfaceImage.toUIImage(selectedSVGK!) } var whiteSVGK: SVGKImage? { switch self { case .arrowRight, .addBuyButton, .arrowUp, .backChevron, .bolt, .breakLink, .bubbleBody, .camera, .check, .checkSmall, .circleCheck, .circleCheckLarge, .comments, .commentsOutline, .discover, .elloType, .eye, .forwardChevron, .heart, .heartOutline, .home, .invite, .library, .link, .mail, .omni, .onePassword, .pencil, .person, .photoPicker, .plusSmall, .reorder, .repost, .roleAdmin, .setBuyButton, .share, .textPicker, .xBox, .x: return InterfaceImage.svgkImage("\(self.rawValue)_white") default: return nil } } var whiteImage: UIImage? { return whiteSVGK.map { InterfaceImage.toUIImage($0) } } var disabledSVGK: SVGKImage? { switch self { case .forwardChevron, .addBuyButton, .backChevron, .repost: return InterfaceImage.svgkImage("\(self.rawValue)_disabled") default: return nil } } var disabledImage: UIImage? { return disabledSVGK.map { InterfaceImage.toUIImage($0) } } var redSVGK: SVGKImage? { switch self { case .x: return InterfaceImage.svgkImage("\(self.rawValue)_red") default: return nil } } var redImage: UIImage? { return redSVGK.map { InterfaceImage.toUIImage($0) } } var greenSVGK: SVGKImage? { switch self { case .watch, .circleCheck, .circleCheckLarge: return InterfaceImage.svgkImage("\(self.rawValue)_green") default: return nil } } var greenImage: UIImage? { return greenSVGK.map { InterfaceImage.toUIImage($0) } } var orangeSVGK: SVGKImage? { switch self { case .star: return InterfaceImage.svgkImage("\(self.rawValue)_orange") default: return nil } } var orangeImage: UIImage? { return orangeSVGK.map { InterfaceImage.toUIImage($0) } } }
8ef3da0f91f05482b765d8ab139dff1d
24.190789
74
0.543745
false
false
false
false
NijiDigital/NetworkStack
refs/heads/master
Carthage/Checkouts/RxSwift/RxCocoa/Traits/SharedSequence/SharedSequence.swift
apache-2.0
8
// // SharedSequence.swift // RxCocoa // // Created by Krunoslav Zaher on 8/27/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !RX_NO_MODULE import RxSwift #endif /** Trait that represents observable sequence that shares computation resources with following properties: - it never fails - it delivers events on `SharingStrategy.scheduler` - sharing strategy is customizable using `SharingStrategy.share` behavior `SharedSequence<Element>` can be considered a builder pattern for observable sequences that share computation resources. To find out more about units and how to use them, please visit `Documentation/Traits.md`. */ public struct SharedSequence<S: SharingStrategyProtocol, Element> : SharedSequenceConvertibleType { public typealias E = Element public typealias SharingStrategy = S let _source: Observable<E> init(_ source: Observable<E>) { self._source = S.share(source) } init(raw: Observable<E>) { self._source = raw } #if EXPANDABLE_SHARED_SEQUENCE /** This method is extension hook in case this unit needs to extended from outside the library. By defining `EXPANDABLE_SHARED_SEQUENCE` one agrees that it's up to him to ensure shared sequence properties are preserved after extension. */ public static func createUnsafe<O: ObservableType>(source: O) -> SharedSequence<S, O.E> { return SharedSequence<S, O.E>(raw: source.asObservable()) } #endif /** - returns: Built observable sequence. */ public func asObservable() -> Observable<E> { return _source } /** - returns: `self` */ public func asSharedSequence() -> SharedSequence<SharingStrategy, E> { return self } } /** Different `SharedSequence` sharing strategies must conform to this protocol. */ public protocol SharingStrategyProtocol { /** Scheduled on which all sequence events will be delivered. */ static var scheduler: SchedulerType { get } /** Computation resources sharing strategy for multiple sequence observers. E.g. One can choose `share(replay:scope:)` as sequence event sharing strategies, but also do something more exotic, like implementing promises or lazy loading chains. */ static func share<E>(_ source: Observable<E>) -> Observable<E> } /** A type that can be converted to `SharedSequence`. */ public protocol SharedSequenceConvertibleType : ObservableConvertibleType { associatedtype SharingStrategy: SharingStrategyProtocol /** Converts self to `SharedSequence`. */ func asSharedSequence() -> SharedSequence<SharingStrategy, E> } extension SharedSequenceConvertibleType { public func asObservable() -> Observable<E> { return asSharedSequence().asObservable() } } extension SharedSequence { /** Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. - returns: An observable sequence with no elements. */ public static func empty() -> SharedSequence<S, E> { return SharedSequence(raw: Observable.empty().subscribeOn(S.scheduler)) } /** Returns a non-terminating observable sequence, which can be used to denote an infinite duration. - returns: An observable sequence whose observers will never get called. */ public static func never() -> SharedSequence<S, E> { return SharedSequence(raw: Observable.never()) } /** Returns an observable sequence that contains a single element. - parameter element: Single element in the resulting observable sequence. - returns: An observable sequence containing the single specified element. */ public static func just(_ element: E) -> SharedSequence<S, E> { return SharedSequence(raw: Observable.just(element).subscribeOn(S.scheduler)) } /** Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. */ public static func deferred(_ observableFactory: @escaping () -> SharedSequence<S, E>) -> SharedSequence<S, E> { return SharedSequence(Observable.deferred { observableFactory().asObservable() }) } /** This method creates a new Observable instance with a variable number of elements. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - parameter elements: Elements to generate. - returns: The observable sequence whose elements are pulled from the given arguments. */ public static func of(_ elements: E ...) -> SharedSequence<S, E> { let source = Observable.from(elements, scheduler: S.scheduler) return SharedSequence(raw: source) } } extension SharedSequence { /** This method converts an array to an observable sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - returns: The observable sequence whose elements are pulled from the given enumerable sequence. */ public static func from(_ array: [E]) -> SharedSequence<S, E> { let source = Observable.from(array, scheduler: S.scheduler) return SharedSequence(raw: source) } /** This method converts a sequence to an observable sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - returns: The observable sequence whose elements are pulled from the given enumerable sequence. */ public static func from<S: Sequence>(_ sequence: S) -> SharedSequence<SharingStrategy, E> where S.Iterator.Element == E { let source = Observable.from(sequence, scheduler: SharingStrategy.scheduler) return SharedSequence(raw: source) } /** This method converts a optional to an observable sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - parameter optional: Optional element in the resulting observable sequence. - returns: An observable sequence containing the wrapped value or not from given optional. */ public static func from(optional: E?) -> SharedSequence<S, E> { let source = Observable.from(optional: optional, scheduler: S.scheduler) return SharedSequence(raw: source) } } extension SharedSequence where Element : RxAbstractInteger { /** Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html) - parameter period: Period for producing the values in the resulting sequence. - returns: An observable sequence that produces a value after each period. */ public static func interval(_ period: RxTimeInterval) -> SharedSequence<S, E> { return SharedSequence(Observable.interval(period, scheduler: S.scheduler)) } } // MARK: timer extension SharedSequence where Element: RxAbstractInteger { /** Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) - parameter dueTime: Relative time at which to produce the first value. - parameter period: Period to produce subsequent values. - returns: An observable sequence that produces a value after due time has elapsed and then each period. */ public static func timer(_ dueTime: RxTimeInterval, period: RxTimeInterval) -> SharedSequence<S, E> { return SharedSequence(Observable.timer(dueTime, period: period, scheduler: S.scheduler)) } }
b5500fc2ce4812a385f08c97b39367d9
34.861472
174
0.703042
false
false
false
false
Fenrikur/ef-app_ios
refs/heads/master
Domain Model/EurofurenceModelTests/Upgrade Path/UserDefaultsForceRefreshRequired.swift
mit
1
import EurofurenceModel import EurofurenceModelTestDoubles import XCTest class UserDefaultsForceRefreshRequiredTests: XCTestCase { var versionProviding: StubAppVersionProviding! var userDefaults: UserDefaults! var forceRefreshRequired: UserDefaultsForceRefreshRequired! override func setUp() { super.setUp() versionProviding = StubAppVersionProviding(version: .random) userDefaults = unwrap(UserDefaults(suiteName: .random)) forceRefreshRequired = UserDefaultsForceRefreshRequired(userDefaults: userDefaults, versionProviding: versionProviding) } func testNoSavedAppVersionRequiresForceRefresh() { XCTAssertTrue(forceRefreshRequired.isForceRefreshRequired) } func testLaunchingSameAppVersionDoesNotRequireForceRefresh() { XCTAssertTrue(forceRefreshRequired.isForceRefreshRequired) forceRefreshRequired = UserDefaultsForceRefreshRequired(userDefaults: userDefaults, versionProviding: versionProviding) XCTAssertFalse(forceRefreshRequired.isForceRefreshRequired) } func testLaunchingDifferentAppVersionsRequiresForceRefresh() { XCTAssertTrue(forceRefreshRequired.isForceRefreshRequired) versionProviding.version = .random forceRefreshRequired = UserDefaultsForceRefreshRequired(userDefaults: userDefaults, versionProviding: versionProviding) XCTAssertTrue(forceRefreshRequired.isForceRefreshRequired) } }
929440f90f0669326520c8cc8a2e2824
39.305556
127
0.796003
false
true
false
false
hsusmita/survey-builder
refs/heads/master
SurveyBuilder/SurveyBuilder/AppDelegate.swift
mit
1
// // AppDelegate.swift // SurveyBuilder // // Created by Susmita Horrow on 03/11/15. // Copyright © 2015 hsusmita.com. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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 throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "hsusmita.com.SurveyBuilder" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("SurveyBuilder", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
6db09c66974bc711ff463221f0c6d4ed
51.621622
288
0.753638
false
false
false
false
mindforce/Projector
refs/heads/master
Projector/MembershipsTableViewController.swift
gpl-2.0
1
// // MembershipsTableViewController.swift // Projector // // Created by Volodymyr Tymofiychuk on 17.01.15. // Copyright (c) 2015 Volodymyr Tymofiychuk. All rights reserved. // import UIKit import Alamofire class MembershipsTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tblMemberships: UITableView! var tableData: NSArray = NSArray() var projectData = ProjectData.sharedInstance func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("MembershipsCell") as MembershipsTableViewCell var rowData: NSDictionary = self.tableData[indexPath.row] as NSDictionary var rowData2: NSDictionary = rowData["user"] as NSDictionary cell.lblTitle?.text = rowData2["name"] as? String return cell } override func viewDidLoad() { super.viewDidLoad() var dataDefault:NSUserDefaults = NSUserDefaults.standardUserDefaults() var base_url: String = dataDefault.valueForKey("BASE_URL")! as String var api_key: AnyObject = dataDefault.valueForKey("API_KEY")! var projects: AnyObject? = dataDefault.valueForKey("PROJECTS") var url = base_url + "/projects/\(projectData.progectId)/memberships.json" Alamofire.request(.GET, url, parameters: ["key": api_key]) .validate(statusCode: 200..<300) .validate(contentType: ["application/json"]) .responseJSON { (request, response, json, error) in if error == nil { var json = JSON(json!) if var results: AnyObject? = json["memberships"].arrayObject { var res_array: NSArray = results as NSArray dispatch_async(dispatch_get_main_queue(), { self.tableData = res_array self.tblMemberships.reloadData() }) } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
d0e400e7b783594a4b2e6f3d6afeeea9
34.08642
109
0.622801
false
false
false
false
IdeasOnCanvas/Callisto
refs/heads/enhancement/yml
Callisto/String+Sugar.swift
mit
1
// // String+Sugar.swift // Callisto // // Created by Patrick Kladek on 14.08.19. // Copyright © 2019 IdeasOnCanvas. All rights reserved. // import Foundation extension String { func trim() -> String { return self.trimmingCharacters(in: CharacterSet.whitespaces) } /// An `NSRange` that represents the full range of the string. var nsrange: NSRange { return NSRange(location: 0, length: utf16.count) } /// Returns a substring with the given `NSRange`, /// or `nil` if the range can't be converted. func substring(with nsrange: NSRange) -> String? { guard let range = Range(nsrange, in: self) else { return nil } return String(self[range]) } func trim(from beginning: String, to endding: String) -> String { let string = self as NSString let begin = string.range(of: beginning) let end = string.range(of: endding) guard begin.location != NSNotFound, end.location != NSNotFound else { return self } let range = begin.extend(to: end) return string.replacingCharacters(in: range, with: "") } func condenseWhitespace() -> String { let components = self.components(separatedBy: .whitespacesAndNewlines) return components.filter { !$0.isEmpty }.joined(separator: " ") } } extension NSRange { init(begin: Int, end: Int) { self = .init(location: begin, length: end - begin) } func extend(to range: NSRange) -> NSRange { guard self.endPosition < range.endPosition else { return self } return NSRange(begin: self.location, end: range.endPosition) } var endPosition: NSInteger { return self.location + self.length } }
919342587dbe9f0da213441f1039e7fe
26.046875
91
0.637204
false
false
false
false
Acidburn0zzz/firefox-ios
refs/heads/main
Client/Frontend/Browser/LocalRequestHelper.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit import Shared class LocalRequestHelper: TabContentScript { func scriptMessageHandlerName() -> String? { return "localRequestHelper" } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { guard let requestUrl = message.frameInfo.request.url, let internalUrl = InternalURL(requestUrl) else { return } let params = message.body as! [String: String] guard let token = params["appIdToken"], token == UserScriptManager.appIdToken else { print("Missing required appid token.") return } if params["type"] == "reload" { // If this is triggered by session restore pages, the url to reload is a nested url argument. if let _url = internalUrl.extractedUrlParam, let nested = InternalURL(_url), let url = nested.extractedUrlParam { message.webView?.replaceLocation(with: url) } else { _ = message.webView?.reload() } } else { assertionFailure("Invalid message: \(message.body)") } } class func name() -> String { return "LocalRequestHelper" } }
a6453ba8607808f77b930c00fe51aea9
36.435897
132
0.647945
false
false
false
false
AttilaTheFun/SwaggerParser
refs/heads/master
Sources/Operation.swift
mit
1
public struct Operation { /// A list of tags for API documentation control. /// Tags can be used for logical grouping of operations by resources or any other qualifier. public let tags: [String] /// A short summary of what the operation does. This field SHOULD be less than 120 characters. public let summary: String? /// A verbose explanation of the operation behavior. /// Github-Flavored Markdown syntax can be used for rich text representation. public let description: String? /// Additional external documentation for this operation. public let externalDocumentation: ExternalDocumentation? /// A list of parameters that are applicable for this operation. /// If a parameter is already defined at the Path Item, the new definition will override it, /// but can never remove it. The list MUST NOT include duplicated parameters. /// There can be one "body" parameter at most. public let parameters: [Either<Parameter, Structure<Parameter>>] /// The list of possible responses as they are returned from executing this operation. public let responses: [Int : Either<Response, Structure<Response>>] /// The documentation of responses other than the ones declared for specific HTTP response codes. /// It can be used to cover undeclared responses. public let defaultResponse: Either<Response, Structure<Response>>? /// Declares this operation to be deprecated. Usage of the declared operation should be refrained. /// Default value is false. public let deprecated: Bool /// A unique string used to identify the operation public let identifier: String? /// A list of which security schemes are applied to this operation. /// The list of values describes alternative security schemes that can be used /// (that is, there is a logical OR between the security requirements). /// This definition overrides any declared top-level security. /// To remove a top-level security declaration, an empty array is used. public let security: [SecurityRequirement]? } struct OperationBuilder: Codable { let summary: String? let description: String? let deprecated: Bool let identifier: String? let tags: [String] let security: [SecurityRequirement]? let externalDocumentationBuilder: ExternalDocumentationBuilder? let parameters: [Reference<ParameterBuilder>] let responses: [Int : Reference<ResponseBuilder>] let defaultResponse: Reference<ResponseBuilder>? enum CodingKeys: String, CodingKey { case summary case description case deprecated case identifier = "operationId" case tags case security case externalDocumentation = "externalDocs" case parameters case responses case defaultResponse = "default" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.summary = try values.decodeIfPresent(String.self, forKey: .summary) self.description = try values.decodeIfPresent(String.self, forKey: .description) self.deprecated = try values.decodeIfPresent(Bool.self, forKey: .deprecated) ?? false self.identifier = try values.decodeIfPresent(String.self, forKey: .identifier) self.tags = try values.decodeIfPresent([String].self, forKey: .tags) ?? [] self.security = try values.decodeIfPresent([SecurityRequirement].self, forKey: .security) self.externalDocumentationBuilder = try values.decodeIfPresent(ExternalDocumentationBuilder.self, forKey: .externalDocumentation) self.parameters = try values.decodeIfPresent([Reference<ParameterBuilder>].self, forKey: .parameters) ?? [] let allResponses = try values.decode([String: Reference<ResponseBuilder>].self, forKey: .responses) let intTuples = allResponses.compactMap { key, value in return Int(key).flatMap { ($0, value) } } self.responses = Dictionary(uniqueKeysWithValues: intTuples) self.defaultResponse = allResponses["default"] } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.summary, forKey: .summary) try container.encode(self.description, forKey: .description) try container.encode(self.deprecated, forKey: .deprecated) try container.encode(self.identifier, forKey: .identifier) try container.encode(self.tags, forKey: .tags) try container.encode(self.security, forKey: .security) try container.encode(self.externalDocumentationBuilder, forKey: .externalDocumentation) try container.encode(self.parameters, forKey: .parameters) var allResponses = [String: Reference<ResponseBuilder>]() allResponses["default"] = self.defaultResponse self.responses.forEach { allResponses[String($0)] = $1 } try container.encode(allResponses, forKey: .responses) } } extension OperationBuilder: Builder { typealias Building = Operation func build(_ swagger: SwaggerBuilder) throws -> Operation { let externalDocumentation = try self.externalDocumentationBuilder?.build(swagger) let parameters = try self.parameters.map { try ParameterBuilder.resolve(swagger, reference: $0) } let responses = try self.responses.mapValues { response in try ResponseBuilder.resolve(swagger, reference: response) } let defaultResponse = try self.defaultResponse.map { response in try ResponseBuilder.resolve(swagger, reference: response) } return Operation( tags: self.tags, summary: self.summary, description: self.description, externalDocumentation: externalDocumentation, parameters: parameters, responses: responses, defaultResponse: defaultResponse, deprecated: self.deprecated, identifier: self.identifier, security: self.security) } }
9bc067801a26a23956c167910b8a88f5
44.720588
107
0.688324
false
false
false
false
wireapp/wire-ios-data-model
refs/heads/develop
Tests/Source/Model/Utils/ProtobufUtilitiesTests.swift
gpl-3.0
1
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import XCTest import WireTesting @testable import WireDataModel class ProtobufUtilitiesTests: BaseZMClientMessageTests { func testThatItSetsAndReadsTheLoudness() { // given let loudness: [Float] = [0.8, 0.3, 1.0, 0.0, 0.001] let sut = WireProtos.Asset.Original(withSize: 200, mimeType: "audio/m4a", name: "foo.m4a", audioDurationInMillis: 1000, normalizedLoudness: loudness) // when let extractedLoudness = sut.audio.normalizedLoudness // then XCTAssertTrue(sut.audio.hasNormalizedLoudness) XCTAssertEqual(extractedLoudness.count, loudness.count) XCTAssertEqual(loudness.map { Float(UInt8(roundf($0*255)))/255.0 }, sut.normalizedLoudnessLevels) } func testThatItDoesNotReturnTheLoudnessIfEmpty() { // given let sut = WireProtos.Asset.Original(withSize: 234, mimeType: "foo/bar", name: "boo.bar") // then XCTAssertEqual(sut.normalizedLoudnessLevels, []) } func testThatItUpdatesTheLinkPreviewWithOTRKeyAndSha() { // given var preview = createLinkPreview() XCTAssertFalse(preview.article.image.hasUploaded) XCTAssertFalse(preview.image.hasUploaded) // when let (otrKey, sha256) = (Data.randomEncryptionKey(), Data.zmRandomSHA256Key()) let metadata = WireProtos.Asset.ImageMetaData(width: 42, height: 12) let original = WireProtos.Asset.Original(withSize: 256, mimeType: "image/jpeg", name: nil, imageMetaData: metadata) preview.update(withOtrKey: otrKey, sha256: sha256, original: original) // then XCTAssertTrue(preview.image.hasUploaded) XCTAssertEqual(preview.image.uploaded.otrKey, otrKey) XCTAssertEqual(preview.image.uploaded.sha256, sha256) XCTAssertEqual(preview.image.original.size, 256) XCTAssertEqual(preview.image.original.mimeType, "image/jpeg") XCTAssertEqual(preview.image.original.image.height, 12) XCTAssertEqual(preview.image.original.image.width, 42) XCTAssertFalse(preview.image.original.hasName) } func testThatItUpdatesTheLinkPreviewWithAssetIDAndTokenAndDomain() { // given var preview = createLinkPreview() preview.update(withOtrKey: .randomEncryptionKey(), sha256: .zmRandomSHA256Key(), original: nil) XCTAssertTrue(preview.image.hasUploaded) XCTAssertFalse(preview.image.uploaded.hasAssetID) // when let (assetKey, token, domain) = ("key", "token", "domain") preview.update(withAssetKey: assetKey, assetToken: token, assetDomain: domain) // then XCTAssertTrue(preview.image.uploaded.hasAssetID) XCTAssertEqual(preview.image.uploaded.assetID, assetKey) XCTAssertEqual(preview.image.uploaded.assetToken, token) XCTAssertEqual(preview.image.uploaded.assetDomain, domain) } func testThatItUpdatesRemoteAssetDataWIthAssetIdAndAssetTokenAndDomain() { // given let (otrKey, sha) = (Data.randomEncryptionKey(), Data.zmRandomSHA256Key()) let (assetId, token, domain) = ("id", "token", "domain") var sut = WireProtos.Asset.RemoteData(withOTRKey: otrKey, sha256: sha) // when sut.update(assetId: assetId, token: token, domain: domain) // then XCTAssertEqual(sut.assetID, assetId) XCTAssertEqual(sut.assetToken, token) XCTAssertEqual(sut.assetDomain, domain) XCTAssertEqual(sut.otrKey, otrKey) XCTAssertEqual(sut.sha256, sha) } func testThatItUpdatesAGenericMessageWithAssetUploadedWithAssetIdAndTokenAndDomain() { // given let (otrKey, sha) = (Data.randomEncryptionKey(), Data.zmRandomSHA256Key()) let (assetId, token, domain) = ("id", "token", "domain") let asset = WireProtos.Asset(withUploadedOTRKey: otrKey, sha256: sha) var sut = GenericMessage(content: asset, nonce: UUID.create()) // when sut.updateUploaded(assetId: assetId, token: token, domain: domain) // then if case .ephemeral? = sut.content { return XCTFail() } XCTAssert(sut.hasAsset) XCTAssertEqual(sut.asset.uploaded.assetID, assetId) XCTAssertEqual(sut.asset.uploaded.assetToken, token) XCTAssertEqual(sut.asset.uploaded.assetDomain, domain) XCTAssertEqual(sut.asset.uploaded.otrKey, otrKey) XCTAssertEqual(sut.asset.uploaded.sha256, sha) } func testThatItUpdatesAGenericMessageWithAssetUploadedWithAssetIdAndTokenAndDomain_Ephemeral() { // given let (otrKey, sha) = (Data.randomEncryptionKey(), Data.zmRandomSHA256Key()) let (assetId, token, domain) = ("id", "token", "domain") let asset = WireProtos.Asset(withUploadedOTRKey: otrKey, sha256: sha) var sut = GenericMessage(content: asset, nonce: UUID.create(), expiresAfter: .tenSeconds) // when sut.updateUploaded(assetId: assetId, token: token, domain: domain) // then guard case .ephemeral? = sut.content else { return XCTFail() } XCTAssertTrue(sut.ephemeral.hasAsset) XCTAssertEqual(sut.ephemeral.asset.uploaded.assetID, assetId) XCTAssertEqual(sut.ephemeral.asset.uploaded.assetToken, token) XCTAssertEqual(sut.ephemeral.asset.uploaded.assetDomain, domain) XCTAssertEqual(sut.ephemeral.asset.uploaded.otrKey, otrKey) XCTAssertEqual(sut.ephemeral.asset.uploaded.sha256, sha) } func testThatItUpdatesAGenericMessageWithAssetPreviewWithAssetIdAndTokenAndDomain() { // given let (otr, sha) = (Data.randomEncryptionKey(), Data.zmRandomSHA256Key()) let (assetId, token, domain) = ("id", "token", "domain") let previewAsset = WireProtos.Asset.Preview( size: 128, mimeType: "image/jpg", remoteData: WireProtos.Asset.RemoteData(withOTRKey: otr, sha256: sha, assetId: nil, assetToken: nil), imageMetadata: WireProtos.Asset.ImageMetaData(width: 123, height: 420)) var sut = GenericMessage( content: WireProtos.Asset(original: nil, preview: previewAsset), nonce: UUID.create() ) // when sut.updatePreview(assetId: assetId, token: token, domain: domain) // then if case .ephemeral? = sut.content { return XCTFail() } XCTAssert(sut.hasAsset) XCTAssertEqual(sut.asset.preview.remote.assetID, assetId) XCTAssertEqual(sut.asset.preview.remote.assetToken, token) XCTAssertEqual(sut.asset.preview.remote.assetDomain, domain) XCTAssertEqual(sut.asset.preview.remote.otrKey, otr) XCTAssertEqual(sut.asset.preview.remote.sha256, sha) } func testThatItUpdatesAGenericMessageWithAssetPreviewWithAssetIdAndTokenAndDomain_Ephemeral() { // given let (otr, sha) = (Data.randomEncryptionKey(), Data.zmRandomSHA256Key()) let (assetId, token, domain) = ("id", "token", "domain") let previewAsset = WireProtos.Asset.Preview( size: 128, mimeType: "image/jpg", remoteData: WireProtos.Asset.RemoteData(withOTRKey: otr, sha256: sha, assetId: nil, assetToken: nil), imageMetadata: WireProtos.Asset.ImageMetaData(width: 123, height: 420)) var sut = GenericMessage( content: WireProtos.Asset(original: nil, preview: previewAsset), nonce: UUID.create(), expiresAfter: .tenSeconds ) // when sut.updatePreview(assetId: assetId, token: token, domain: domain) // then guard case .ephemeral? = sut.content else { return XCTFail() } XCTAssert(sut.ephemeral.hasAsset) XCTAssertEqual(sut.ephemeral.asset.preview.remote.assetID, assetId) XCTAssertEqual(sut.ephemeral.asset.preview.remote.assetToken, token) XCTAssertEqual(sut.ephemeral.asset.preview.remote.assetDomain, domain) XCTAssertEqual(sut.ephemeral.asset.preview.remote.otrKey, otr) XCTAssertEqual(sut.ephemeral.asset.preview.remote.sha256, sha) } // MARK: - Helper func createLinkPreview() -> LinkPreview { return LinkPreview.with { $0.url = "www.example.com/original" $0.permanentURL = "www.example.com/permanent" $0.urlOffset = 42 $0.title = "Title" $0.summary = name } } } // MARK: - Using Swift protobuf API, Update assets extension ProtobufUtilitiesTests { func testThatItUpdatesAGenericMessageWithAssetUploadedWithAssetIdAndTokenAndDomain_SwiftProtobufAPI() { // given let (assetId, token, domain) = ("id", "token", "domain") let asset = WireProtos.Asset(imageSize: CGSize(width: 42, height: 12), mimeType: "image/jpeg", size: 123) var sut = GenericMessage(content: asset, nonce: UUID.create()) // when XCTAssertNotEqual(sut.asset.uploaded.assetID, assetId) XCTAssertNotEqual(sut.asset.uploaded.assetToken, token) sut.updateUploaded(assetId: assetId, token: token, domain: domain) // then XCTAssertEqual(sut.asset.uploaded.assetID, assetId) XCTAssertEqual(sut.asset.uploaded.assetToken, token) XCTAssertEqual(sut.asset.uploaded.assetDomain, domain) } func testThatItUpdatesAGenericMessageWithAssetUploadedWithAssetIdAndTokenAndDomain_Ephemeral_SwiftProtobufAP() { // given let (assetId, token, domain) = ("id", "token", "domain") let asset = WireProtos.Asset(imageSize: CGSize(width: 42, height: 12), mimeType: "image/jpeg", size: 123) var sut = GenericMessage(content: asset, nonce: UUID.create(), expiresAfter: .tenSeconds) // when XCTAssertNotEqual(sut.ephemeral.asset.uploaded.assetID, assetId) XCTAssertNotEqual(sut.ephemeral.asset.uploaded.assetToken, token) sut.updateUploaded(assetId: assetId, token: token, domain: domain) // then XCTAssertEqual(sut.ephemeral.asset.uploaded.assetID, assetId) XCTAssertEqual(sut.ephemeral.asset.uploaded.assetToken, token) XCTAssertEqual(sut.ephemeral.asset.uploaded.assetDomain, domain) } func testThatItUpdatesAGenericMessageWithAssetPreviewWithAssetIdAndTokenAndDomain_SwiftProtobufAP() { // given let (otr, sha) = (Data.randomEncryptionKey(), Data.zmRandomSHA256Key()) let remoteData = WireProtos.Asset.RemoteData.with { $0.otrKey = otr $0.sha256 = sha } let imageMetadata = WireProtos.Asset.ImageMetaData.with { $0.width = 123 $0.height = 420 } let previewAsset = WireProtos.Asset.Preview(size: 128, mimeType: "image/jpg", remoteData: remoteData, imageMetadata: imageMetadata) let asset = WireProtos.Asset.with { $0.preview = previewAsset } let (assetId, token, domain) = ("id", "token", "domain") var sut = GenericMessage(content: asset, nonce: UUID.create()) // when XCTAssertNotEqual(sut.asset.preview.remote.assetID, assetId) XCTAssertNotEqual(sut.asset.preview.remote.assetToken, token) sut.updatePreview(assetId: assetId, token: token, domain: domain) // then XCTAssertEqual(sut.asset.preview.remote.assetID, assetId) XCTAssertEqual(sut.asset.preview.remote.assetToken, token) XCTAssertEqual(sut.asset.preview.remote.assetDomain, domain) XCTAssertEqual(sut.asset.preview.remote.otrKey, otr) XCTAssertEqual(sut.asset.preview.remote.sha256, sha) } func testThatItUpdatesAGenericMessageWithAssetPreviewWithAssetIdAndToken_Ephemeral_SwiftProtobufAP() { // given let (otr, sha) = (Data.randomEncryptionKey(), Data.zmRandomSHA256Key()) let remoteData = WireProtos.Asset.RemoteData.with { $0.otrKey = otr $0.sha256 = sha } let imageMetadata = WireProtos.Asset.ImageMetaData.with { $0.width = 123 $0.height = 420 } let previewAsset = WireProtos.Asset.Preview(size: 128, mimeType: "image/jpg", remoteData: remoteData, imageMetadata: imageMetadata) let asset = WireProtos.Asset.with { $0.preview = previewAsset } let (assetId, token, domain) = ("id", "token", "domain") var sut = GenericMessage(content: asset, nonce: UUID.create(), expiresAfter: .tenSeconds) // when XCTAssertNotEqual(sut.ephemeral.asset.preview.remote.assetID, assetId) XCTAssertNotEqual(sut.ephemeral.asset.preview.remote.assetToken, token) XCTAssertNotEqual(sut.ephemeral.asset.preview.remote.assetDomain, domain) sut.updatePreview(assetId: assetId, token: token, domain: domain) // then XCTAssertEqual(sut.ephemeral.asset.preview.remote.assetID, assetId) XCTAssertEqual(sut.ephemeral.asset.preview.remote.assetToken, token) XCTAssertEqual(sut.ephemeral.asset.preview.remote.assetDomain, domain) XCTAssertEqual(sut.ephemeral.asset.preview.remote.otrKey, otr) XCTAssertEqual(sut.ephemeral.asset.preview.remote.sha256, sha) } }
2cca2fe115e8252c11ae4224c89126db
41.428571
157
0.672971
false
true
false
false
steve228uk/FBImagePicker
refs/heads/master
FBImagePicker/FBPhotoCollectionViewCell.swift
mit
1
// // FBPhotoCollectionViewCell.swift // FBImagePicker // // Created by Stephen Radford on 01/02/2017. // Copyright © 2017 Cocoon Development Ltd. All rights reserved. // import UIKit class FBPhotoCollectionViewCell: UICollectionViewCell { @IBOutlet weak var photo: UIImageView! var image: FBImage? { didSet { guard let image = image else { return } guard let cached = image.image else { image.getImage { [unowned self] image in UIView.transition(with: self.photo, duration: FBImagePicker.Settings.imageTransitionDuration, options: .transitionCrossDissolve, animations: { [unowned self] in self.photo.image = image }, completion: nil) } return } photo.image = cached } } override func prepareForReuse() { photo.image = nil } }
8b97307eaaf51884430b0251b73d321b
26.416667
180
0.561297
false
false
false
false
slightair/akane
refs/heads/master
akane/ViewController/InitialViewController.swift
mit
1
import UIKit import SafariServices import RxSwift import RxCocoa class InitialViewController: UIViewController { @IBOutlet weak var loginButton: UIButton! let disposeBag = DisposeBag() var currentWebViewController: SFSafariViewController? override func viewDidLoad() { super.viewDidLoad() let fetchUserTrigger = PublishSubject<Void>() let viewModel = InitialViewModel( input: ( loginTaps: loginButton.rx.tap.asObservable(), fetchUserTrigger: fetchUserTrigger ), dependency: ( redditService: RedditDefaultService.shared, redditAuthorization: RedditDefaultAuthorization.shared ) ) rx.sentMessage(#selector(viewWillAppear)) .take(1) .subscribe(onNext: { _ in fetchUserTrigger.onNext(()) }) .disposed(by: disposeBag) viewModel.needsLogin .map { !$0 } .bind(to: loginButton.rx.isHidden) .disposed(by: disposeBag) viewModel.needsAuthorize .subscribe(onNext: { url in self.presentRedditAuthorization(url: url) }) .disposed(by: disposeBag) viewModel.retrievedCredential .subscribe(onNext: { _ in fetchUserTrigger.onNext(()) self.currentWebViewController?.dismiss(animated: true, completion: nil) }) .disposed(by: disposeBag) viewModel.loggedIn .filter { $0 } .subscribe(onNext: { _ in self.presentHomeView() }) .disposed(by: disposeBag) } func presentRedditAuthorization(url: URL) { let viewController = SFSafariViewController(url: url) viewController.modalTransitionStyle = .crossDissolve self.currentWebViewController = viewController self.present(viewController, animated: true, completion: nil) } func presentHomeView() { let storyboard = UIStoryboard(name: "Main", bundle: nil) let viewController = storyboard.instantiateViewController(withIdentifier: "Home") viewController.modalTransitionStyle = .crossDissolve self.present(viewController, animated: true, completion: nil) } }
bf1e774ba0c8bcb7b76d38e5c1e40f44
30.837838
89
0.605263
false
false
false
false
gaowanli/PinGo
refs/heads/master
PinGo/PinGo/Discover/Topic/TopicHeaderView.swift
mit
1
// // TopicHeaderView.swift // PinGo // // Created by GaoWanli on 16/2/2. // Copyright © 2016年 GWL. All rights reserved. // import UIKit protocol TopicHeaderViewDelegate: NSObjectProtocol { /** 点击了某个按钮 - parameter headerView: view - parameter button: 按钮 */ func topicHeaderView(_ headerView: TopicHeaderView, didClickButton button: UIButton) } class TopicHeaderView: UIView { @IBOutlet fileprivate weak var topView: UIView! override func awakeFromNib() { super.awakeFromNib() topView.addSubview(imageCarouselView) } override func layoutSubviews() { super.layoutSubviews() imageCarouselView.frame = topView.bounds } var bannerList: [Banner]? { didSet { imageCarouselView.bannerList = bannerList } } func scrollImage() { imageCarouselView.startTimer() } func stopScrollImage() { imageCarouselView.stopTimer() } @IBAction func buttonClick(_ sender: UITapGestureRecognizer) { if let view = sender.view { print(view.tag) } } class func loadFromNib() -> TopicHeaderView { return Bundle.main.loadNibNamed("TopicHeader", owner: self, options: nil)!.last as! TopicHeaderView } // MARK: lazy loading fileprivate lazy var imageCarouselView: ImageCarouselView = { let i = ImageCarouselView.loadFromNib() return i }() }
0ceb31e10c07350b6326287d1671d3b5
21.656716
107
0.612648
false
false
false
false
RaviDesai/RSDRestServices
refs/heads/master
Example/Tests/MockedRESTCalls.swift
mit
1
// // MockedRESTCalls.swift // CEVFoundation // // Created by Ravi Desai on 4/29/15. // Copyright (c) 2015 CEV. All rights reserved. // import Foundation import OHHTTPStubs import RSDRESTServices import RSDSerialization class MockedRESTCalls { static var id0 = NSUUID() static var id1 = NSUUID() static var id2 = NSUUID() static var id3 = NSUUID() static var id4 = NSUUID() static func sampleITunesResultData() -> NSData { let bundle : NSBundle = NSBundle(forClass: self) let path = bundle.pathForResource("iTunesResults", ofType: "json")! let content = NSData(contentsOfFile: path) return content!; } static func sampleUsers() -> [User] { return [User(id: id0, prefix: "Sir", first: "David", middle: "Jon", last: "Gilmour", suffix: "CBE", friends: nil), User(id: id1, prefix: nil, first: "Roger", middle: nil, last: "Waters", suffix: nil, friends: nil), User(id: id2, prefix: "Sir", first: "Bob", middle: nil, last: "Geldof", suffix: "KBE", friends: nil), User(id: id3, prefix: "Mr", first: "Nick", middle: "Berkeley", last: "Mason", suffix: nil, friends: nil), User(id: id4, prefix: "", first: "Richard", middle: "William", last: "Wright", suffix: "", friends: nil)] } static func sampleUsersData() -> NSData { let jsonArray = MockedRESTCalls.sampleUsers().convertToJSONArray() return try! NSJSONSerialization.dataWithJSONObject(jsonArray, options: NSJSONWritingOptions.PrettyPrinted) } class func hijackITunesSearch() { OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in if (request.URL?.host != "itunes.apple.com") { return false; } if (request.URL?.path != "/search") { return false; } return true; }, withStubResponse: { (request) -> OHHTTPStubsResponse in let data = self.sampleITunesResultData() return OHHTTPStubsResponse(data: data, statusCode: 200, headers: ["Content-Type": "application/json"]) }) } class func hijackUserGetAll() { OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in if (request.URL?.host != .Some("com.desai")) { return false } if (request.URL?.path != .Some("/api/Users")) { return false } if (request.HTTPMethod != "GET") { return false } if (request.URL?.query != nil) { return false } return true }) { (request) -> OHHTTPStubsResponse in let data = sampleUsersData() return OHHTTPStubsResponse(data: data, statusCode: 200, headers: ["Content-Type": "application/json"]) } } class func hijackUserGetMatching() { OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in if (request.URL?.host != .Some("com.desai")) { return false } if (request.URL?.path != .Some("/api/Users")) { return false } if (request.HTTPMethod != "GET") { return false } if (request.URL?.query == nil) { return false } return true }) { (request) -> OHHTTPStubsResponse in var query = request.URL!.absoluteString query = query.stringByRemovingPercentEncoding! let comp = NSURLComponents(string: query) let items = comp!.queryItems! var users = sampleUsers() for item in items { users = users.filter { switch(item.name.lowercaseString) { case "prefix": return $0.prefix == item.value case "first": return $0.first == item.value case "middle": return $0.middle == item.value case "last": return $0.last == item.value case "suffix": return $0.prefix == item.value default: return false } } } let jsonArray = users.convertToJSONArray() if let data = try? NSJSONSerialization.dataWithJSONObject(jsonArray, options: NSJSONWritingOptions.PrettyPrinted) { return OHHTTPStubsResponse(data: data, statusCode: 200, headers: ["Content-Type": "application/json"]) } return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 500, headers: nil) } } class func hijackUserPost() { OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in if (request.URL?.host != .Some("com.desai")) { return false } if (request.URL?.path != .Some("/api/Users")) { return false } if (request.HTTPMethod != "POST") { return false } if (request.URL?.query != nil) { return false } return true }) { (request) -> OHHTTPStubsResponse in if let data = NSURLProtocol.propertyForKey("PostedData", inRequest: request) as? NSData { if let json: JSON = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) { if let newUser = User.createFromJSON(json) { let found = sampleUsers().filter { $0 == newUser }.first if found == nil { var returnUser = newUser returnUser.id = NSUUID() if let resultData = try? NSJSONSerialization.dataWithJSONObject(returnUser.convertToJSON(), options: NSJSONWritingOptions.PrettyPrinted) { return OHHTTPStubsResponse(data: resultData, statusCode: 200, headers: ["Content-Type": "application/json"]) } else { return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 500, headers: nil) } } else { return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 409, headers: nil) } } } } return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 422, headers: nil) } } class func hijackUserPut() { OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in if (request.URL?.host != .Some("com.desai")) { return false } if (request.URL?.path != .Some("/api/Users")) { return false } if (request.HTTPMethod != "PUT") { return false } if (request.URL?.query != nil) { return false } return true }) { (request) -> OHHTTPStubsResponse in if let data = NSURLProtocol.propertyForKey("PostedData", inRequest: request) as? NSData { if let json: JSON = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) { if let newUser = User.createFromJSON(json) { if (newUser.id == nil) { return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 404, headers: nil) } let found = sampleUsers().filter { $0 == newUser }.first if found != nil { if let resultData = try? NSJSONSerialization.dataWithJSONObject(newUser.convertToJSON(), options: NSJSONWritingOptions.PrettyPrinted) { return OHHTTPStubsResponse(data: resultData, statusCode: 200, headers: ["Content-Type": "application/json"]) } else { return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 500, headers: nil) } } else { return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 404, headers: nil) } } } } return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 422, headers: nil) } } class func hijackUserDelete() { OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in if (request.URL?.host != .Some("com.desai")) { return false } if (request.URL?.path != .Some("/api/Users")) { return false } if (request.HTTPMethod != "DELETE") { return false } if (request.URL?.query != nil) { return false } return true }) { (request) -> OHHTTPStubsResponse in if let data = NSURLProtocol.propertyForKey("PostedData", inRequest: request) as? NSData { if let json: JSON = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) { if let newUser = User.createFromJSON(json) { if (newUser.id == nil) { return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 404, headers: nil) } let found = sampleUsers().filter { $0 == newUser }.first if found != nil { if let resultData = try? NSJSONSerialization.dataWithJSONObject(newUser.convertToJSON(), options: NSJSONWritingOptions.PrettyPrinted) { return OHHTTPStubsResponse(data: resultData, statusCode: 200, headers: ["Content-Type": "application/json"]) } else { return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 500, headers: nil) } } else { return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 404, headers: nil) } } } } return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 422, headers: nil) } } }
a5239de486cef3a662f64786744ae764
51.209184
167
0.544468
false
false
false
false
cuzv/ExtensionKit
refs/heads/master
Sources/Extension/Timer+Extension.swift
mit
1
// // Timer+Extension.swift // ExtensionKit // // Created by Haioo Inc on 4/7/17. // Copyright © 2017 Moch. All rights reserved. // import Foundation public extension Timer { public func resume(after duration: TimeInterval = 0) { fireDate = Date(timeIntervalSinceNow: duration) } public func pause(after duration: TimeInterval = 0) { if 0 <= duration { fireDate = Date.distantFuture } else { DispatchQueue.main.asyncAfter(deadline: .now() + duration) { self.fireDate = Date.distantFuture } } } } public extension CADisplayLink { public func resume(after duration: TimeInterval = 0) { if 0 <= duration { isPaused = false } else { DispatchQueue.main.asyncAfter(deadline: .now() + duration) { self.isPaused = false } } } public func pause(after duration: TimeInterval = 0) { if 0 <= duration { isPaused = true } else { DispatchQueue.main.asyncAfter(deadline: .now() + duration) { self.isPaused = true } } } }
e2474089a14bb8d5e0f37d492967fe59
24.340426
72
0.548279
false
false
false
false
JaSpa/swift
refs/heads/master
test/attr/open.swift
apache-2.0
13
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-build-swift -emit-module -c %S/Inputs/OpenHelpers.swift -o %t/OpenHelpers.swiftmodule // RUN: %target-typecheck-verify-swift -I %t import OpenHelpers /**** General structural limitations on open. ****/ open private class OpenIsNotCompatibleWithPrivate {} // expected-error {{duplicate modifier}} expected-note{{modifier already specified here}} open fileprivate class OpenIsNotCompatibleWithFilePrivate {} // expected-error {{duplicate modifier}} expected-note{{modifier already specified here}} open internal class OpenIsNotCompatibleWithInternal {} // expected-error {{duplicate modifier}} expected-note{{modifier already specified here}} open public class OpenIsNotCompatibleWithPublic {} // expected-error {{duplicate modifier}} expected-note{{modifier already specified here}} open open class OpenIsNotCompatibleWithOpen {} // expected-error {{duplicate modifier}} expected-note{{modifier already specified here}} open typealias OpenIsNotAllowedOnTypeAliases = Int // expected-error {{only classes and overridable class members can be declared 'open'; use 'public'}} open struct OpenIsNotAllowedOnStructs {} // expected-error {{only classes and overridable class members can be declared 'open'; use 'public'}} open enum OpenIsNotAllowedOnEnums_AtLeastNotYet {} // expected-error {{only classes and overridable class members can be declared 'open'; use 'public'}} /**** Open entities are at least public. ****/ func foo(object: ExternalOpenClass) { object.openMethod() object.openProperty += 5 object[MarkerForOpenSubscripts()] += 5 } /**** Open classes. ****/ open class ClassesMayBeDeclaredOpen {} class ExternalSuperClassesMustBeOpen : ExternalNonOpenClass {} // expected-error {{cannot inherit from non-open class 'ExternalNonOpenClass' outside of its defining module}} class ExternalSuperClassesMayBeOpen : ExternalOpenClass {} class NestedClassesOfPublicTypesAreOpen : ExternalStruct.OpenClass {} // This one is hard to diagnose. class NestedClassesOfInternalTypesAreNotOpen : ExternalInternalStruct.OpenClass {} // expected-error {{use of undeclared type 'ExternalInternalStruct'}} class NestedPublicClassesOfOpenClassesAreNotOpen : ExternalOpenClass.PublicClass {} // expected-error {{cannot inherit from non-open class 'ExternalOpenClass.PublicClass' outside of its defining module}} open final class ClassesMayNotBeBothOpenAndFinal {} // expected-error {{class cannot be declared both 'final' and 'open'}} public class NonOpenSuperClass {} // expected-note {{superclass is declared here}} open class OpenClassesMustHaveOpenSuperClasses : NonOpenSuperClass {} // expected-error {{superclass 'NonOpenSuperClass' of open class must be open}} /**** Open methods. ****/ open class AnOpenClass { open func openMethod() {} open var openVar: Int = 0 open let openLet: Int = 1 // Should this be allowed? open typealias MyInt = Int // expected-error {{only classes and overridable class members can be declared 'open'; use 'public'}} open subscript(_: MarkerForOpenSubscripts) -> Int { return 0 } } internal class NonOpenClassesCanHaveOpenMembers { open var openVar: Int = 0; open func openMethod() {} } class SubClass : ExternalOpenClass { override func openMethod() {} override var openProperty: Int { get{return 0} set{} } override subscript(index: MarkerForOpenSubscripts) -> Int { get { return 0 } set {} } override func nonOpenMethod() {} // expected-error {{overriding non-open instance method outside of its defining module}} override var nonOpenProperty: Int { get{return 0} set{} } // expected-error {{overriding non-open var outside of its defining module}} override subscript(index: MarkerForNonOpenSubscripts) -> Int { // expected-error {{overriding non-open subscript outside of its defining module}} get { return 0 } set {} } } open class InvalidOpenSubClass : ExternalOpenClass { public override func openMethod() {} // expected-error {{overriding instance method must be as accessible as the declaration it overrides}} {{3-9=open}} public override var openProperty: Int { get{return 0} set{} } // expected-error {{overriding var must be as accessible as the declaration it overrides}} {{3-9=open}} public override subscript(index: MarkerForOpenSubscripts) -> Int { // expected-error {{overriding subscript must be as accessible as the declaration it overrides}} {{3-9=open}} get { return 0 } set {} } } open class InvalidOpenSubClass2 : ExternalOpenClass { internal override func openMethod() {} // expected-error {{overriding instance method must be as accessible as the declaration it overrides}} {{3-11=open}} internal override var openProperty: Int { get{return 0} set{} } // expected-error {{overriding var must be as accessible as the declaration it overrides}} {{3-11=open}} internal override subscript(index: MarkerForOpenSubscripts) -> Int { // expected-error {{overriding subscript must be as accessible as the declaration it overrides}} {{3-11=open}} get { return 0 } set {} } } open class OpenSubClassFinalMembers : ExternalOpenClass { final public override func openMethod() {} final public override var openProperty: Int { get{return 0} set{} } final public override subscript(index: MarkerForOpenSubscripts) -> Int { get { return 0 } set {} } } open class InvalidOpenSubClassFinalMembers : ExternalOpenClass { final internal override func openMethod() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{9-17=public}} final internal override var openProperty: Int { get{return 0} set{} } // expected-error {{overriding var must be as accessible as its enclosing type}} {{9-17=public}} final internal override subscript(index: MarkerForOpenSubscripts) -> Int { // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{9-17=public}} get { return 0 } set {} } } public class PublicSubClass : ExternalOpenClass { public override func openMethod() {} public override var openProperty: Int { get{return 0} set{} } public override subscript(index: MarkerForOpenSubscripts) -> Int { get { return 0 } set {} } } // The proposal originally made these invalid, but we changed our minds. open class OpenSuperClass { public func publicMethod() {} public var publicProperty: Int { return 0 } public subscript(index: MarkerForNonOpenSubscripts) -> Int { return 0 } } open class OpenSubClass : OpenSuperClass { open override func publicMethod() {} open override var publicProperty: Int { return 0 } open override subscript(index: MarkerForNonOpenSubscripts) -> Int { return 0 } }
00b6354fd860fdf6f84a7b9b4b02dcdd
47.970803
203
0.745864
false
false
false
false
google/JacquardSDKiOS
refs/heads/main
JacquardSDK/Classes/Logger.swift
apache-2.0
1
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /// Sets the global `Logger` instance used by all code in Jacquard SDK. /// /// You do not need to set this - the default logger prints log messages to the console using `print()`, ignoring `LogLevel.debug` /// messages and does not print source details (ie. file, line, function). You can set a new instance of `PrintLogger` with the /// levels you desire, or you may implement your own custom `Logger` type. /// /// - Important: This var is accessed from multiple threads and is not protected with a lock. You can alter this *only* prior /// to accessing any Jacquard SDK APIs for the first time in your code. /// /// - Parameter logger: new `Logger` instance. public func setGlobalJacquardSDKLogger(_ logger: Logger) { jqLogger = logger } func createDefaultLogger() -> Logger { PrintLogger( logLevels: [.info, .warning, .error, .assertion, .preconditionFailure], includeSourceDetails: false ) } var jqLogger: Logger = createDefaultLogger() /// Describes different types of log messages which can be used to filter which messages are collected. public enum LogLevel: String { /// Filter debug log messages. case debug = "DEBUG" /// Filter info log messages. case info = "INFO" /// Filter warning log messages. case warning = "WARNING" /// Filter error log messages. case error = "ERROR" /// Filter assertion log messages. case assertion = "ASSERTION" /// Filter precondition failure log messages. case preconditionFailure = "PRECONDITIONFAILURE" } /// Describes the type you must implement if you wish to provide your own logging implementation. /// /// The only required function to implement is `Logger.log(level:message:)` as the rest have default implementations. /// /// - SeeAlso: `jqLogger` public protocol Logger { /// Logs a message. /// /// Implementations must be thread-safe. /// /// - Parameters: /// - level: Describes the level/type of the message. /// - file: The file where the log message comes from. /// - line: The line where the log message comes from. /// - function: The function where the log message comes from. /// - message: A closure which returns the message to display. func log( level: LogLevel, file: String, line: Int, function: String, message: () -> String ) /// Logs a message with level `LogLevel.debug`. /// /// Implementations must be thread-safe. /// /// - Parameters: /// - file: The file where the log message comes from. /// - line: The line where the log message comes from. /// - function: The function where the log message comes from. /// - message: the message to display. It is an autoclosure so that if that log level is filtered the code will not be evaluated. func debug(file: String, function: String, line: Int, _ message: @autoclosure () -> String) /// Logs a message with level `LogLevel.info`. /// /// Implementations must be thread-safe. /// /// - Parameters: /// - file: The file where the log message comes from. /// - line: The line where the log message comes from. /// - function: The function where the log message comes from. /// - message: the message to display. It is an autoclosure so that if that log level is filtered the code will not be evaluated. func info(file: String, function: String, line: Int, _ message: @autoclosure () -> String) /// Logs a message with level `LogLevel.warning`. /// /// Implementations must be thread-safe. /// /// - Parameters: /// - file: The file where the log message comes from. /// - line: The line where the log message comes from. /// - function: The function where the log message comes from. /// - message: the message to display. It is an autoclosure so that if that log level is filtered the code will not be evaluated. func warning(file: String, function: String, line: Int, _ message: @autoclosure () -> String) /// Logs a message with level `LogLevel.error`. /// /// Implementations must be thread-safe. /// /// - Parameters: /// - file: The file where the log message comes from. /// - line: The line where the log message comes from. /// - function: The function where the log message comes from. /// - message: the message to display. It is an autoclosure so that if that log level is filtered the code will not be evaluated. func error(file: String, function: String, line: Int, _ message: @autoclosure () -> String) /// Raise an assertion with a message. /// /// Implementations must be thread-safe. /// /// - Parameters: /// - file: The file where the log message comes from. /// - line: The line where the log message comes from. /// - function: The function where the log message comes from. /// - message: the message to display. It is an autoclosure so that if that log level is filtered the code will not be evaluated. func assert(file: String, function: String, line: Int, _ message: @autoclosure () -> String) /// Precondition failure with a message. /// /// Implementations must be thread-safe. /// /// - Parameters: /// - file: The file where the log message comes from. /// - line: The line where the log message comes from. /// - function: The function where the log message comes from. /// - message: the message to display. It is an autoclosure so that if that log level is filtered the code will not be evaluated. func preconditionAssertFailure( file: String, function: String, line: Int, _ message: @autoclosure () -> String ) } /// Default `Logger` implementation that prints messages to the console. public class PrintLogger: Logger { /// Which log levels should be displayed. let logLevels: [LogLevel] /// Whether source file, line and function information should be logged. let includeSourceDetails: Bool /// Creates a `PrintLogger` instance. /// /// Whether assertions are raised or not depends on the usual compiler flags. If compiler flags prevent assertions being raised, the /// assertion message will still be printed to the console based on the usual `logLevels` check. /// /// - Parameter logLevels: Which log levels should be displayed. public init(logLevels: [LogLevel], includeSourceDetails: Bool) { self.logLevels = logLevels self.includeSourceDetails = includeSourceDetails } /// Logs a message /// /// - SeeAlso: `Logger.log(level:message:)` public func log( level: LogLevel, file: String, line: Int, function: String, message: () -> String ) { guard logLevels.contains(level) || level == .assertion || level == .preconditionFailure else { // Return early to avoid overhead of evaluating message. return } var sourceDetails = "" if includeSourceDetails { let filename = URL(fileURLWithPath: file).lastPathComponent sourceDetails = " [\(filename)@\(line);\(function)]" } let fullMessage = "[\(level.rawValue)]\(sourceDetails) \(message())" if level == .assertion { assertionFailure(fullMessage) } if level == .preconditionFailure { preconditionFailure(fullMessage) } if logLevels.contains(level) { print(fullMessage) } } } extension Logger { /// Logs a message with level `LogLevel.debug`. public func debug( file: String = #file, function: String = #function, line: Int = #line, _ message: @autoclosure () -> String ) { log(level: .debug, file: file, line: line, function: function, message: message) } /// Logs a message with level `LogLevel.info()`. public func info( file: String = #file, function: String = #function, line: Int = #line, _ message: @autoclosure () -> String ) { log(level: .info, file: file, line: line, function: function, message: message) } /// Logs a message with level `LogLevel.warning`. public func warning( file: String = #file, function: String = #function, line: Int = #line, _ message: @autoclosure () -> String ) { log(level: .warning, file: file, line: line, function: function, message: message) } /// Logs a message with level `LogLevel.error`. public func error( file: String = #file, function: String = #function, line: Int = #line, _ message: @autoclosure () -> String ) { log(level: .error, file: file, line: line, function: function, message: message) } /// Raise an assertion. public func assert( file: String = #file, function: String = #function, line: Int = #line, _ message: @autoclosure () -> String ) { log(level: .assertion, file: file, line: line, function: function, message: message) } public func preconditionAssertFailure( file: String = #file, function: String = #function, line: Int = #line, _ message: @autoclosure () -> String ) { log(level: .preconditionFailure, file: file, line: line, function: function, message: message) } }
1844e8ce855c7049ab1080ee3e76b248
35.965116
134
0.675055
false
false
false
false
Takanu/Pelican
refs/heads/master
Sources/Pelican/API/Types/Markup/Inline/InlineKeyboard.swift
mit
1
// // Inline.swift // Pelican // // Created by Takanu Kyriako on 31/08/2017. // import Foundation /** Represents a series of inline buttons that will be displayed underneath the message when included with it. Each inline button can do one of the following: _ _ _ _ _ **Callback Data** This sends a small String back to the bot as a `CallbackQuery`, which is automatically filtered back to the session and to a `callbackState` if one exists. Alternatively if the keyboard the button belongs to is part of a `Prompt`, it will automatically be received by it in the respective ChatSession, and the prompt will respond based on how you have set it up. **URL** The button when pressed will re-direct users to a webpage. **Inine Query Switch** This can only be used when the bot supports Inline Queries. This prompts the user to select one of their chats to open it, and when open the client will insert the bot‘s username and a specified query in the input field. **Inline Query Current Chat** This can only be used when the bot supports Inline Queries. Pressing the button will insert the bot‘s username and an optional specific inline query in the current chat's input field. */ final public class MarkupInline: MarkupType, Codable, Equatable { public var keyboard: [[MarkupInlineKey]] = [] /// Coding keys to map values when Encoding and Decoding. enum CodingKeys: String, CodingKey { case keyboard = "inline_keyboard" } // Blank! public init() { return } /** Creates an Inline Keyboard using a series of specified `MarkupInlineKey` types, where all buttons will be arranged on a single row. - parameter buttonsIn: The buttons to be included in the keyboard. */ public init(withButtons buttonsIn: MarkupInlineKey...) { var array: [MarkupInlineKey] = [] for button in buttonsIn { array.append(button) } keyboard.append(array) } /** Creates an Inline Keyboard using a series of specified button label and URL string pairs, where all buttons will be arranged on a single row. - parameter pair: A sequence of label/url String tuples that will define each key on the keyboard. */ public init(withURL sequence: (url: String, text: String)...) { var array: [MarkupInlineKey] = [] for tuple in sequence { let button = MarkupInlineKey(fromURL: tuple.url, text: tuple.text) array.append(button) } keyboard.append(array) } /** Creates an Inline Keyboard using a series of specified button label and callback String pairs, where all buttons will be arranged on a single row. - parameter pair: A sequence of label/callback String tuples that will define each key on the keyboard. */ public init?(withCallback sequence: (query: String, text: String?)...) { var array: [MarkupInlineKey] = [] for tuple in sequence { // Try to process them, but propogate the error if it fails. guard let button = MarkupInlineKey(fromCallbackData: tuple.query, text: tuple.text) else { return nil } array.append(button) } keyboard.append(array) } /** Creates an Inline Keyboard using sets of arrays containing label and callback tuples, where each tuple array is a single row. - parameter array: A an array of label/callback String tuple arrays that will define each row on the keyboard. */ public init?(withCallback array: [[(query: String, text: String)]]) { for row in array { var array: [MarkupInlineKey] = [] for tuple in row { // Try to process them, but propogate the error if it fails. guard let button = MarkupInlineKey(fromCallbackData: tuple.query, text: tuple.text) else { return nil } array.append(button) } keyboard.append(array) } } /** Creates an Inline Keyboard using a series of specified button label and "Inline Query Current Chat" String pairs, where all buttons will be arranged on a single row. - parameter pair: A sequence of label/"Inline Query Current Chat" String tuples that will define each key on the keyboard. */ public init(withInlineQueryCurrent sequence: (query: String, text: String)...) { var array: [MarkupInlineKey] = [] for tuple in sequence { let button = MarkupInlineKey(fromInlineQueryCurrent: tuple.query, text: tuple.text) array.append(button) } keyboard.append(array) } /** Creates an Inline Keyboard using a series of specified button label and "Inline Query New Chat" String pairs, where all buttons will be arranged on a single row. - parameter pair: A sequence of label/"Inline Query New Chat" String tuples that will define each key on the keyboard. */ public init(withInlineQueryNewChat sequence: (query: String, text: String)...) { var array: [MarkupInlineKey] = [] for tuple in sequence { let button = MarkupInlineKey(fromInlineQueryNewChat: tuple.query, text: tuple.text) array.append(button) } keyboard.append(array) } /** Creates an Inline Keyboard using a series of labels. The initializer will then generate an associated ID value for each label and assign it to the button as Callback data, starting with "1" and incrementing upwards. All buttons wil be arranged on a single row. - parameter labels: A sequence of String labels that will define each key on the keyboard. */ public init?(withGenCallback sequence: String...) { var array: [MarkupInlineKey] = [] var id = 1 for label in sequence { guard let button = MarkupInlineKey(fromCallbackData: String(id), text: label) else { return nil } array.append(button) id += 1 } keyboard.append(array) } /** Creates an Inline Keyboard using a set of nested String Arrays, where the array structure defines the specific arrangement of the keyboard. The initializer will generate an associated ID value for eachlabel and assign it to the button as Callback data, starting with "1" and incrementing upwards. - parameter rows: A nested set of String Arrays, where each String array will form a single row on the inline keyboard. */ public init?(withGenCallback rows: [[String]]) { var id = 1 for row in rows { var array: [MarkupInlineKey] = [] for label in row { guard let button = MarkupInlineKey(fromCallbackData: String(id), text: label) else { return nil } array.append(button) id += 1 } keyboard.append(array) } } /** Adds an extra row to the keyboard using the sequence of buttons provided. */ public func addRow(sequence: MarkupInlineKey...) { var array: [MarkupInlineKey] = [] for button in sequence { array.append(button) } keyboard.append(array) } /** Adds extra rows to the keyboard based on the array of buttons you provide. */ public func addRow(array: [MarkupInlineKey]...) { for item in array { keyboard.append(item) } } /** Returns all available callback data from any button held inside this markup */ public func getCallbackData() -> [String]? { var data: [String] = [] for row in keyboard { for key in row { if key.type == .callbackData { data.append(key.data) } } } return data } /** Returns all labels associated with the inline keyboard. */ public func getLabels() -> [String] { var labels: [String] = [] for row in keyboard { for key in row { labels.append(key.text) } } return labels } /** Returns the label thats associated with the provided data, if it exists. */ public func getLabel(withData data: String) -> String? { for row in keyboard { for key in row { if key.data == data { return key.text } } } return nil } /** Returns the key thats associated with the provided data, if it exists. */ public func getKey(withData data: String) -> MarkupInlineKey? { for row in keyboard { for key in row { if key.data == data { return key } } } return nil } /** Replaces a key with another provided one, by trying to match the given data with a key */ public func replaceKey(usingType type: InlineKeyType, data: String, newKey: MarkupInlineKey) -> Bool { for (rowIndex, row) in keyboard.enumerated() { var newRow = row var replaced = false // Iterate through each key in each row for a match for (i, key) in newRow.enumerated() { if replaced == true { continue } if key.type == type { if key.data == data { newRow.remove(at: i) newRow.insert(newKey, at: i) replaced = true } } } // If we made a match, switch out the rows and exit if replaced == true { keyboard.remove(at: rowIndex) keyboard.insert(newRow, at: rowIndex) return true } } return false } /** Replaces a key with another provided one, by trying to match the keys it has with one that's provided. */ public func replaceKey(oldKey: MarkupInlineKey, newKey: MarkupInlineKey) -> Bool { for (rowIndex, row) in keyboard.enumerated() { var newRow = row var replaced = false // Iterate through each key in each row for a match for (i, key) in newRow.enumerated() { if replaced == true { continue } if key == oldKey { newRow.remove(at: i) newRow.insert(newKey, at: i) replaced = true } } // If we made a match, switch out the rows and exit if replaced == true { keyboard.remove(at: rowIndex) keyboard.insert(newRow, at: rowIndex) return true } } return false } /** Tries to find and delete a key, based on a match with one provided. */ public func deleteKey(key: MarkupInlineKey) -> Bool { for (rowIndex, row) in keyboard.enumerated() { var newRow = row var removed = false // Iterate through each key in each row for a match for (i, newKey) in newRow.enumerated() { if removed == true { continue } if key == newKey { newRow.remove(at: i) removed = true } } // If we made a match, switch out the rows and exit if removed == true { keyboard.remove(at: rowIndex) keyboard.insert(newRow, at: rowIndex) return true } } return false } static public func ==(lhs: MarkupInline, rhs: MarkupInline) -> Bool { if lhs.keyboard.count != rhs.keyboard.count { return false } for (i, lhsRow) in lhs.keyboard.enumerated() { let rhsRow = rhs.keyboard[i] if lhsRow.count != rhsRow.count { return false } for (iKey, lhsKey) in lhsRow.enumerated() { let rhsKey = rhsRow[iKey] if lhsKey != rhsKey { return false } } } return true } }
490c3ac09d7fcbaf8ee41133487a1697
24.840686
137
0.680072
false
false
false
false
nbhasin2/Sudoku
refs/heads/master
Sudoku/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // Sudoku // // Created by Nishant on 2016-04-03. // Copyright © 2016 Epicara. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var navController: UINavigationController? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. setupNavController() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // Nav Controller Setup private func setupNavController() { let gridViewController = SudokuViewController(nibName: "SudokuViewController", bundle: nil) self.navController = UINavigationController(rootViewController: gridViewController) self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.rootViewController = navController self.window!.backgroundColor = UIColor.blueColor() self.window!.makeKeyAndVisible() } }
13376fcef32182b6782a8c2498850be3
41.136364
285
0.726357
false
false
false
false
adamnemecek/AudioKit
refs/heads/main
Sources/AudioKit/MIDI/Listeners/MIDITempoListener.swift
mit
1
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ // MIDI Spec // 24 clocks/quarternote // 96 clocks/4_beat_measure // // Ideas // - Provide the standard deviation of differences in clock times to observe stability // // Looked at // https://stackoverflow.com/questions/9641399/ios-how-to-receive-midi-tempo-bpm-from-host-using-coremidi // https://stackoverflow.com/questions/13562714/calculate-accurate-bpm-from-midi-clock-in-objc-with-coremidi // https://github.com/yderidde/PGMidi/blob/master/Sources/PGMidi/PGMidiSession.mm#L186 #if !os(tvOS) import Foundation import CoreMIDI /// Type to store tempo in BeatsPerMinute public typealias BPMType = TimeInterval /// A AudioKit midi listener that looks at midi clock messages and calculates a BPM /// /// Usage: /// /// let tempoListener = MIDITempoListener() /// MIDI().addListener(tempoListener) /// /// Make your class a MIDITempoObserver and you will recieve callbacks when the BPM /// changes. /// /// class YOURCLASS: MIDITempoObserver { /// func receivedTempoUpdate(bpm: BPMType, label: String) { ... } /// func midiClockFollowerMode() { ... } /// func midiClockLeaderEnabled() { ... } /// /// midiClockFollowerMode() informs client that midi clock messages have been received /// and the client may not become the clock leader. The client must stop all /// transmission of MIDI clock. /// /// midiClockLeaderEnabled() informs client that midi clock messages have not been seen /// in 1.6 seconds and the client is allowed to become the clock leader. /// public class MIDITempoListener: NSObject { /// Clock listener public var clockListener: MIDIClockListener? /// System Real-time Listener public var srtListener = MIDISystemRealTimeListener() var tempoObservers: [MIDITempoObserver] = [] /// Tempo string public var tempoString: String = "" /// Tempo in "BPM Type" public var tempo: BPMType = 0 var clockEvents: [UInt64] = [] let clockEventLimit = 2 var bpmStats = BPMHistoryStatistics() var bpmAveraging: BPMHistoryAveraging var timebaseInfo = mach_timebase_info() var tickSmoothing: ValueSmoothing var bpmSmoothing: ValueSmoothing var clockTimeout: MIDITimeout? /// Is the Incoming Clock active? public var isIncomingClockActive = false let BEAT_TICKS = 24 let oneThousand = UInt64(1_000) /// Create a BPM Listener /// /// This object creates a clockListener: MIDIClockListener /// The MIDIClockListener is informed every time there is a clock and it in turn informs its /// MIDIBeatObserver's whenever beat events happen. /// /// - Parameters: /// - smoothing: [0 - 1] this value controls the tick smoothing and bpm smoothing (currently both are disabled) /// - bpmHistoryLimit: When a bpm is calculated it's stored in a array which is sized by this number. /// The values in this array are averaged and that is the BPM result that is returned. /// If you make this number larger, then BPM will change very slowly. /// If you make this number small, then BPM will change very quickly. public init(smoothing: Float64 = 0.8, bpmHistoryLimit: Int = 3) { assert(bpmHistoryLimit > 0, "You must specify a positive number for bpmHistoryLimit") tickSmoothing = ValueSmoothing(factor: smoothing) bpmSmoothing = ValueSmoothing(factor: smoothing) bpmAveraging = BPMHistoryAveraging(countLimit: bpmHistoryLimit) super.init() clockListener = MIDIClockListener(srtListener: srtListener, tempoListener: self) if timebaseInfo.denom == 0 { _ = mach_timebase_info(&timebaseInfo) } clockTimeout = MIDITimeout(timeoutInterval: 1.6, onMainThread: true, success: {}, timeout: { if self.isIncomingClockActive == true { self.midiClockActivityStopped() } self.isIncomingClockActive = false }) midiClockActivityStopped() } deinit { clockTimeout = nil clockListener = nil } } // MARK: - BPM Analysis public extension MIDITempoListener { /// Analyze tempo func analyze() { guard clockEvents.count > 1 else { return } guard clockEventLimit > 1 else { return } guard clockEvents.count >= clockEventLimit else { return } let previousClockTime = clockEvents[ clockEvents.count - 2 ] let currentClockTime = clockEvents[ clockEvents.count - 1 ] guard previousClockTime > 0 && currentClockTime > previousClockTime else { return } let clockDelta = currentClockTime - previousClockTime if timebaseInfo.denom == 0 { _ = mach_timebase_info(&timebaseInfo) } let numerator = Float64(clockDelta * UInt64(timebaseInfo.numer)) let denominator = Float64(UInt64(oneThousand) * UInt64(timebaseInfo.denom)) let intervalNanos = numerator / denominator //NSEC_PER_SEC let oneMillion = Float64(USEC_PER_SEC) let bpmCalc = ((oneMillion / intervalNanos / Float64(BEAT_TICKS)) * Float64(60.0)) + 0.055 resetClockEventsLeavingOne() bpmStats.record(bpm: bpmCalc, time: currentClockTime) // bpmSmoothing.smoothed( let results = bpmStats.bpmFromRegressionAtTime(bpmStats.timeAt(ratio: 0.8)) // currentClockTime - 500000 // Only report results when there is enough history to guess at the BPM let bpmToRecord: BPMType if results > 0 { bpmToRecord = BPMType(results) } else { bpmToRecord = BPMType(bpmCalc) } bpmAveraging.record(bpmToRecord) tempo = bpmAveraging.results.avg let newTempoString = String(format: "%3.2f", tempo) if newTempoString != tempoString { tempoString = newTempoString receivedTempo(bpm: bpmAveraging.results.avg, label: tempoString) } } /// Reset all clock events except the last one func resetClockEventsLeavingOne() { guard clockEvents.count > 1 else { return } clockEvents = clockEvents.dropFirst(clockEvents.count - 1).map { $0 } } /// Reset all clock events leaving half remaining func resetClockEventsLeavingHalf() { guard clockEvents.count > 1 else { return } clockEvents = clockEvents.dropFirst(clockEvents.count / 2).map { $0 } } /// Reset all clock events leaving none func resetClockEventsLeavingNone() { guard clockEvents.count > 1 else { return } clockEvents = [] } } // MARK: - MIDITempoListener should be used as an MIDIListener extension MIDITempoListener: MIDIListener { /// Receive a MIDI system command (such as clock, SysEx, etc) /// /// - data: Array of integers /// - portID: MIDI Unique Port ID /// - offset: MIDI Event TimeStamp /// public func receivedMIDISystemCommand(_ data: [MIDIByte], portID: MIDIUniqueID? = nil, timeStamp: MIDITimeStamp? = nil) { if data[0] == MIDISystemCommand.clock.rawValue { clockTimeout?.succeed() clockTimeout?.perform { if self.isIncomingClockActive == false { midiClockActivityStarted() self.isIncomingClockActive = true } let timeStamp = timeStamp ?? 0 clockEvents.append(timeStamp) analyze() clockListener?.midiClockBeat(timeStamp: timeStamp) } } if data[0] == MIDISystemCommand.stop.rawValue { resetClockEventsLeavingNone() } if data[0] == MIDISystemCommand.start.rawValue { resetClockEventsLeavingOne() } srtListener.receivedMIDISystemCommand(data, portID: portID, timeStamp: timeStamp) } /// Receive the MIDI note on event /// /// - Parameters: /// - noteNumber: MIDI Note number of activated note /// - velocity: MIDI Velocity (0-127) /// - channel: MIDI Channel (1-16) /// - portID: MIDI Unique Port ID /// - timeStamp: MIDI Event TimeStamp /// public func receivedMIDINoteOn(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel, portID: MIDIUniqueID? = nil, timeStamp: MIDITimeStamp? = nil) { // Do nothing } /// Receive the MIDI note off event /// /// - Parameters: /// - noteNumber: MIDI Note number of released note /// - velocity: MIDI Velocity (0-127) usually speed of release, often 0. /// - channel: MIDI Channel (1-16) /// - portID: MIDI Unique Port ID /// - timeStamp: MIDI Event TimeStamp /// public func receivedMIDINoteOff(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel, portID: MIDIUniqueID? = nil, timeStamp: MIDITimeStamp? = nil) { // Do nothing } /// Receive a generic controller value /// /// - Parameters: /// - controller: MIDI Controller Number /// - value: Value of this controller /// - channel: MIDI Channel (1-16) /// - portID: MIDI Unique Port ID /// - timeStamp: MIDI Event TimeStamp /// public func receivedMIDIController(_ controller: MIDIByte, value: MIDIByte, channel: MIDIChannel, portID: MIDIUniqueID? = nil, timeStamp: MIDITimeStamp? = nil) { // Do nothing } /// Receive single note based aftertouch event /// /// - Parameters: /// - noteNumber: Note number of touched note /// - pressure: Pressure applied to the note (0-127) /// - channel: MIDI Channel (1-16) /// - portID: MIDI Unique Port ID /// - timeStamp: MIDI Event TimeStamp /// public func receivedMIDIAftertouch(noteNumber: MIDINoteNumber, pressure: MIDIByte, channel: MIDIChannel, portID: MIDIUniqueID? = nil, timeStamp: MIDITimeStamp? = nil) { // Do nothing } /// Receive global aftertouch /// /// - Parameters: /// - pressure: Pressure applied (0-127) /// - channel: MIDI Channel (1-16) /// - portID: MIDI Unique Port ID /// - timeStamp:MIDI Event TimeStamp /// public func receivedMIDIAftertouch(_ pressure: MIDIByte, channel: MIDIChannel, portID: MIDIUniqueID? = nil, timeStamp: MIDITimeStamp? = nil) { // Do nothing } /// Receive pitch wheel value /// /// - Parameters: /// - pitchWheelValue: MIDI Pitch Wheel Value (0-16383) /// - channel: MIDI Channel (1-16) /// - portID: MIDI Unique Port ID /// - timeStamp: MIDI Event TimeStamp /// public func receivedMIDIPitchWheel(_ pitchWheelValue: MIDIWord, channel: MIDIChannel, portID: MIDIUniqueID? = nil, timeStamp: MIDITimeStamp? = nil) { // Do nothing } /// Receive program change /// /// - Parameters: /// - program: MIDI Program Value (0-127) /// - channel: MIDI Channel (1-16) /// - portID: MIDI Unique Port ID /// - timeStamp:MIDI Event TimeStamp /// public func receivedMIDIProgramChange(_ program: MIDIByte, channel: MIDIChannel, portID: MIDIUniqueID? = nil, timeStamp: MIDITimeStamp? = nil) { // Do nothing } /// MIDI Setup has changed public func receivedMIDISetupChange() { // Do nothing } /// MIDI Object Property has changed public func receivedMIDIPropertyChange(propertyChangeInfo: MIDIObjectPropertyChangeNotification) { // Do nothing } /// Generic MIDI Notification public func receivedMIDINotification(notification: MIDINotification) { // Do nothing } } // MARK: - Management and Communications for BPM Observers extension MIDITempoListener { /// Add a MIDI Tempo Observer /// - Parameter observer: Tempo observer to add public func addObserver(_ observer: MIDITempoObserver) { tempoObservers.append(observer) } /// Remove a tempo observer /// - Parameter observer: Tempo observer to remove public func removeObserver(_ observer: MIDITempoObserver) { tempoObservers.removeAll { $0 == observer } } /// Remove all tempo observers public func removeAllObservers() { tempoObservers.removeAll() } func midiClockActivityStarted() { tempoObservers.forEach { (observer) in observer.midiClockLeaderMode() } } func midiClockActivityStopped() { tempoObservers.forEach { (observer) in observer.midiClockLeaderEnabled() } } func receivedTempo(bpm: BPMType, label: String) { tempoObservers.forEach { (observer) in observer.receivedTempo(bpm: bpm, label: label) } } } #endif
4f12689fbe8c3700ffbc48e049ffa858
34.650386
125
0.595544
false
false
false
false
googlearchive/science-journal-ios
refs/heads/master
ScienceJournal/UI/PitchSensorAnimationView.swift
apache-2.0
1
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import QuartzCore import UIKit import third_party_objective_c_material_components_ios_components_Typography_Typography fileprivate extension MDCTypography { static func boldFont(withSize size: CGFloat) -> UIFont { // This font should load unless something is wrong with Material's fonts. return MDCTypography.fontLoader().boldFont!(ofSize: size) } static var fontName: String { // Arbitrary size to get the font name. return boldFont(withSize: 10).fontName } } // swiftlint:disable type_body_length /// Animation view for the pitch sensor. class PitchSensorAnimationView: SensorAnimationView { // MARK: - Nested private enum Metrics { static let backgroundColorValueBlueHigh: CGFloat = 175 static let backgroundColorValueBlueLow: CGFloat = 248 static let backgroundColorValueGreenHigh: CGFloat = 97 static let backgroundColorValueGreenLow: CGFloat = 202 static let backgroundColorValueRedHigh: CGFloat = 13 static let backgroundColorValueRedLow: CGFloat = 113 static let backgroundRadiusRatio: CGFloat = 0.38 static let dotAngleTop = CGFloat(Double.pi / 2) static let dotEllipseRadiusRatio: CGFloat = 0.44 static let dotRadiusRatio: CGFloat = 0.05 static let musicSignFlat = "\u{266D} " static let musicSignSharp = "\u{266F} " static let noteFontSizeRatio: CGFloat = 0.48 static let noteRatioX: CGFloat = 0.42 static let noteRatioY: CGFloat = 0.46 static let noteLeftTextColor = UIColor(red: 238 / 255, green: 238 / 255, blue: 238 / 255, alpha: 1).cgColor static let noteRightTextColor = UIColor(red: 220 / 255, green: 220 / 255, blue: 220 / 255, alpha: 1).cgColor static let numberOfPianoKeys = 88 static let octaveFontSizeRatio: CGFloat = 0.2 static let octaveRatioX: CGFloat = 0.67 static let octaveRatioY: CGFloat = 0.67 static let octaveTextColor = UIColor(red: 220 / 255, green: 220 / 255, blue: 220 / 255, alpha: 1).cgColor static let signFontSizeRatio: CGFloat = 0.25 static let signRatioX: CGFloat = 0.62 static let signRatioY: CGFloat = 0.43 static let signTextColor = UIColor(red: 220 / 255, green: 220 / 255, blue: 220 / 255, alpha: 1).cgColor static let textShadowColor = UIColor(white: 0, alpha: 0.61).cgColor static let textShadowOffset = CGSize(width: 1, height: 2) static let textShadowRadius: CGFloat = 4 } private struct MusicalNote { let letter: String let octave: String let sign: String var shouldCenter: Bool { // "-" and "+" should be centered. return letter == "-" || letter == "+" } } // MARK: - Properties private let backgroundShapeLayer = CAShapeLayer() private let dotShapeLayer = CAShapeLayer() private let noteLeftTextLayer = CATextLayer() private let noteRightTextLayer = CATextLayer() private let signTextLayer = CATextLayer() private let octaveTextLayer = CATextLayer() // The angle of the dot indicating how close the detected pitch is to the nearest musical note. A // value of 0 positions the dot at the far right. A value of PI/2 positions the dot at the top. A // value of PI positions the dot at the far left. private var angleOfDot = Metrics.dotAngleTop private var level: Int? private var musicalNote: MusicalNote? { guard let level = level else { return nil } return musicalNotes[level] } private let musicalNotes: [MusicalNote] = { let natural = "" var musicalNotes = [MusicalNote]() musicalNotes.append(MusicalNote(letter: "-", octave: "", sign: "")) for i in 1...Metrics.numberOfPianoKeys { var letter = "" var sign = "" switch (i + 8) % 12 { case 0: letter = "C" sign = natural case 1: letter = "C" sign = Metrics.musicSignSharp case 2: letter = "D" sign = natural case 3: letter = "E" sign = Metrics.musicSignFlat case 4: letter = "E" sign = natural case 5: letter = "F" sign = natural case 6: letter = "F" sign = Metrics.musicSignSharp case 7: letter = "G" sign = natural case 8: letter = "A" sign = Metrics.musicSignFlat case 9: letter = "A" sign = natural case 10: letter = "B" sign = Metrics.musicSignFlat case 11: letter = "B" sign = natural default: break } let octave = (i + 8) / 12 musicalNotes.append(MusicalNote(letter: letter, octave: String(octave), sign: sign)) } musicalNotes.append(MusicalNote(letter: "+", octave: "", sign: "")) return musicalNotes }() /// The frequencies of notes of a piano at indices 1-88. Each value is a half step more than the /// previous value. private let noteFrequencies: [Double] = { var noteFrequencies = [Double]() var multiplier = 1.0 while noteFrequencies.count < Metrics.numberOfPianoKeys { for note in SoundUtils.highNotes { guard noteFrequencies.count < Metrics.numberOfPianoKeys else { break } noteFrequencies.append(note * multiplier) } multiplier /= 2.0 } noteFrequencies.reverse() // Add first and last items to make lookup easier. Use the approximate half-step ratio to // determine the first and last items. noteFrequencies.insert(noteFrequencies[0] / SoundUtils.halfStepFrequencyRatio, at: 0) noteFrequencies.append( noteFrequencies[noteFrequencies.endIndex - 1] * SoundUtils.halfStepFrequencyRatio ) return noteFrequencies }() // MARK: - Public override init(frame: CGRect) { super.init(frame: frame) configureView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureView() } override func layoutSubviews() { super.layoutSubviews() // Background shape layer. let backgroundShapeRadius = bounds.width * Metrics.backgroundRadiusRatio let backgroundShapeRect = CGRect(x: bounds.midX - backgroundShapeRadius, y: bounds.midY - backgroundShapeRadius, width: backgroundShapeRadius * 2, height: backgroundShapeRadius * 2) backgroundShapeLayer.path = UIBezierPath(ovalIn: backgroundShapeRect).cgPath // Dot shape layer will be at a point on an invisible ellipse. let ellipseRadius = bounds.width * Metrics.dotEllipseRadiusRatio let dotX = bounds.midX + ellipseRadius * cos(angleOfDot) let dotY = bounds.midY - ellipseRadius * sin(angleOfDot) let dotRadius = bounds.width * Metrics.dotRadiusRatio let dotShapeRect = CGRect(x: dotX - dotRadius, y: dotY - dotRadius, width: dotRadius * 2, height: dotRadius * 2) dotShapeLayer.path = UIBezierPath(ovalIn: dotShapeRect).cgPath // Text layers. if let musicalNote = musicalNote { // Letter let noteFontSize = floor(bounds.height * Metrics.noteFontSizeRatio) noteLeftTextLayer.fontSize = noteFontSize noteRightTextLayer.fontSize = noteFontSize let noteSize = musicalNote.letter.boundingRect( with: .zero, options: [], attributes: [NSAttributedString.Key.font: MDCTypography.boldFont(withSize: noteFontSize)], context: nil).size var noteX: CGFloat var noteY: CGFloat if musicalNote.shouldCenter { noteX = bounds.midX - ceil(noteSize.width) / 2 noteY = bounds.midY - ceil(noteSize.height) / 2 } else { noteX = bounds.width * Metrics.noteRatioX - ceil(noteSize.width) / 2 noteY = bounds.height * Metrics.noteRatioY - ceil(noteSize.height) / 2 } // The note layer on the left is half width. noteLeftTextLayer.frame = CGRect(x: floor(noteX), y: floor(noteY), width: ceil(noteSize.width / 2), height: ceil(noteSize.height)) noteRightTextLayer.frame = CGRect(x: floor(noteX), y: floor(noteY), width: ceil(noteSize.width), height: ceil(noteSize.height)) // Sign. signTextLayer.fontSize = floor(bounds.height * Metrics.signFontSizeRatio) let signFont = MDCTypography.boldFont(withSize: signTextLayer.fontSize) let signSize = musicalNote.sign.boundingRect( with: .zero, options: [], attributes: [NSAttributedString.Key.font: signFont], context: nil).size signTextLayer.frame = CGRect(x: floor(bounds.width * Metrics.signRatioX - signSize.width / 2), y: floor(bounds.height * Metrics.signRatioY - signSize.height / 2), width: ceil(signSize.width), height: ceil(signSize.height)) // Octave octaveTextLayer.fontSize = floor(bounds.height * Metrics.octaveFontSizeRatio) let octaveFont = MDCTypography.boldFont(withSize: octaveTextLayer.fontSize) let octaveSize = musicalNote.octave.boundingRect(with: .zero, options: [], attributes: [NSAttributedString.Key.font: octaveFont], context: nil).size octaveTextLayer.frame = CGRect(x: floor(bounds.width * Metrics.octaveRatioX - octaveSize.width / 2), y: floor(bounds.height * Metrics.octaveRatioY - octaveSize.height / 2), width: ceil(octaveSize.width), height: ceil(octaveSize.height)) } } override func setValue(_ value: Double, minValue: Double, maxValue: Double) { guard let level = noteIndex(fromFrequency: value), level != self.level else { return } // Store the level. self.level = level // Set the fill color of the background shape layer. backgroundShapeLayer.fillColor = backgroundColor(forLevel: level).cgColor // The the angle of the dot. let difference = differenceBetween(pitch: value, andLevel: level) angleOfDot = CGFloat((1 - 2 * difference) * (Double.pi / 2)) // Set the musical note letter, sign and octave. let musicalNote = musicalNotes[level] noteLeftTextLayer.string = musicalNote.letter noteRightTextLayer.string = musicalNote.letter signTextLayer.string = musicalNote.sign octaveTextLayer.string = musicalNote.octave setNeedsLayout() setAccessibilityLabel(withMusicalNote: musicalNote, level: level, differenceBetweenNoteAndPitch: difference) } override func reset() { setValue(0, minValue: 0, maxValue: 0) } /// Returns an image snapshot and an accessibility label for this view, showing a given value. /// /// - Parameters: /// - size: The size of the image on screen. /// - value: The value to display the pitch at. /// - Returns: A tuple containing an optional image snapshot and an optional accessibility label. static func imageAttributes(atSize size: CGSize, withValue value: Double) -> (UIImage?, String?) { let pitchSensorAnimationView = PitchSensorAnimationView(frame: CGRect(origin: .zero, size: size)) pitchSensorAnimationView.setValue(value, minValue: 0, maxValue: 1) return (pitchSensorAnimationView.imageSnapshot, pitchSensorAnimationView.accessibilityLabel) } // MARK: - Private private func backgroundColor(forLevel level: Int) -> UIColor { if level == 0 { return UIColor(red: Metrics.backgroundColorValueRedLow / 255, green: Metrics.backgroundColorValueGreenLow / 255, blue: Metrics.backgroundColorValueBlueLow / 255, alpha: 1) } else if level == noteFrequencies.endIndex - 1 { return UIColor(red: Metrics.backgroundColorValueRedHigh / 255, green: Metrics.backgroundColorValueGreenHigh / 255, blue: Metrics.backgroundColorValueBlueHigh / 255, alpha: 1) } else { let red = round(Metrics.backgroundColorValueRedLow + (Metrics.backgroundColorValueRedHigh - Metrics.backgroundColorValueRedLow) * CGFloat(level) / CGFloat(noteFrequencies.endIndex - 1)) let green = round(Metrics.backgroundColorValueGreenLow + (Metrics.backgroundColorValueGreenHigh - Metrics.backgroundColorValueGreenLow) * CGFloat(level) / CGFloat(noteFrequencies.endIndex - 1)) let blue = round(Metrics.backgroundColorValueBlueLow + (Metrics.backgroundColorValueBlueHigh - Metrics.backgroundColorValueBlueLow) * CGFloat(level) / CGFloat(noteFrequencies.endIndex - 1)) return UIColor(red: red / 255, green: green / 255, blue: blue / 255, alpha: 1) } } private func configureView() { isAccessibilityElement = true // Background image view. let imageView = UIImageView(image: UIImage(named: "sensor_sound_frequency_0")) imageView.autoresizingMask = [.flexibleHeight, .flexibleWidth] imageView.frame = bounds addSubview(imageView) // Background shape layer. backgroundShapeLayer.fillColor = backgroundColor(forLevel: 0).cgColor layer.addSublayer(backgroundShapeLayer) // Dot shape layer. dotShapeLayer.fillColor = UIColor.red.cgColor layer.addSublayer(dotShapeLayer) // Text layer common configuration. [noteRightTextLayer, noteLeftTextLayer, signTextLayer, octaveTextLayer].forEach { $0.alignmentMode = .center $0.contentsScale = UIScreen.main.scale $0.font = CGFont(MDCTypography.fontName as CFString) $0.shadowColor = Metrics.textShadowColor $0.shadowOffset = Metrics.textShadowOffset $0.shadowRadius = Metrics.textShadowRadius layer.addSublayer($0) } // Right note. noteRightTextLayer.foregroundColor = Metrics.noteRightTextColor // Left note. noteLeftTextLayer.foregroundColor = Metrics.noteLeftTextColor noteLeftTextLayer.masksToBounds = true // Sign. signTextLayer.foregroundColor = Metrics.signTextColor // Octave. octaveTextLayer.foregroundColor = Metrics.octaveTextColor // Set the lowest detectable value initially. reset() } // The difference, in half steps, between the detected pitch and the note associated with the // level. func differenceBetween(pitch: Double, andLevel level: Int) -> Double { if level == 0 || level == noteFrequencies.endIndex - 1 { // If the nearest musical note is more than one half step lower than the lowest musical note // or more than one half step higher than the highest musical note, don't calculate the // difference. return 0 } // If the detected pitch equals a musical note the dot is at the top, which is 90 degrees or // Double.pi / 2 radians. If the detected pitch is half way between the nearest musical note and // the next lower musical note, the dot is at the far left, which is 180 degrees, or Double.pi // radians. If the detected pitch is half way between the nearest musical note and the next // higher musical note, the dot is at the far right, which is 0 degrees, or 0 radians. let nearestNote = noteFrequencies[level] var difference = pitch - nearestNote if difference < 0 { // The detected pitch is lower than the nearest musical note. Adjust the difference to the // range of -1 to 0, where -1 is the next lower note. The difference should never be less than // -0.5, since that would indicate that the pitch was actually closer to the lower note. let lowerNote = noteFrequencies[level - 1] difference /= nearestNote - lowerNote } else { // The detected pitch is higher than the nearest musical note. Adjust the difference to the // range of 0 to 1, where 1 is the next higher note. The difference should never be greater // than 0.5, since that would indicate that the pitch was actually closer to the higher note. let higherNote = noteFrequencies[level + 1] difference /= higherNote - nearestNote } return difference } /// The index of the note corresponding to the given sound frequency, where indices 1-88 represent /// the notes of keys on a piano. private func noteIndex(fromFrequency frequency: Double) -> Int? { if frequency < noteFrequencies[0] { // `frequency` is lower than the lowest note. return 0 } else if frequency > noteFrequencies[noteFrequencies.endIndex - 1] { // `frequency` is higher than the highest note. return noteFrequencies.endIndex - 1 } else { var previousNote: Double? for (index, note) in noteFrequencies.enumerated() { if note == frequency { // `frequency` matched a note. return index } if let previousNote = previousNote, frequency > previousNote && frequency < note { // `frequency` is between two notes. let midpoint = (previousNote + note) / 2 return frequency < midpoint ? index - 1 : index } previousNote = note } } return nil } private func setAccessibilityLabel(withMusicalNote musicalNote: MusicalNote, level: Int, differenceBetweenNoteAndPitch difference: Double) { let accessibilityLabel: String if level == 0 { accessibilityLabel = String.pitchLowContentDescription } else if level == noteFrequencies.endIndex - 1 { accessibilityLabel = String.pitchHighContentDescription } else { let formatString: String let differenceString = String.localizedStringWithFormat("%.2f", abs(difference)) if difference < 0 { if musicalNote.sign == Metrics.musicSignFlat { formatString = String.pitchFlatterThanFlatNoteContentDescription } else if musicalNote.sign == Metrics.musicSignSharp { formatString = String.pitchFlatterThanSharpNoteContentDescription } else { // Natural note formatString = String.pitchFlatterThanNaturalNoteContentDescription } accessibilityLabel = String(format: formatString, differenceString, musicalNote.letter, musicalNote.octave) } else if difference > 0 { if musicalNote.sign == Metrics.musicSignFlat { formatString = String.pitchSharperThanFlatNoteContentDescription } else if musicalNote.sign == Metrics.musicSignSharp { formatString = String.pitchSharperThanSharpNoteContentDescription } else { // Natural note formatString = String.pitchSharperThanNaturalNoteContentDescription } accessibilityLabel = String(format: formatString, differenceString, musicalNote.letter, musicalNote.octave) } else { // difference == 0 if musicalNote.sign == Metrics.musicSignFlat { formatString = String.pitchFlatNoteContentDescription } else if musicalNote.sign == Metrics.musicSignSharp { formatString = String.pitchSharpNoteContentDescription } else { // Natural note formatString = String.pitchNaturalNoteContentDescription } accessibilityLabel = String(format: formatString, musicalNote.letter, musicalNote.octave) } } self.accessibilityLabel = accessibilityLabel } } // swiftlint:enable type_body_length
1e2005c22d2b0db1625196cd36dfcd45
38.766667
100
0.658991
false
false
false
false
GeoffSpielman/SimonSays
refs/heads/master
simon_says_iOS_app/WebSocket.swift
mit
1
////////////////////////////////////////////////////////////////////////////////////////////////// // // Websocket.swift // // Created by Dalton Cherry on 7/16/14. // Copyright (c) 2014-2015 Dalton Cherry. // // 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 CoreFoundation import Security public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification" public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification" public let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName" public protocol WebSocketDelegate: class { func websocketDidConnect(socket: WebSocket) func websocketDidDisconnect(socket: WebSocket, error: NSError?) func websocketDidReceiveMessage(socket: WebSocket, text: String) func websocketDidReceiveData(socket: WebSocket, data: NSData) } public protocol WebSocketPongDelegate: class { func websocketDidReceivePong(socket: WebSocket) } public class WebSocket: NSObject, NSStreamDelegate { enum OpCode: UInt8 { case ContinueFrame = 0x0 case TextFrame = 0x1 case BinaryFrame = 0x2 // 3-7 are reserved. case ConnectionClose = 0x8 case Ping = 0x9 case Pong = 0xA // B-F reserved. } public enum CloseCode: UInt16 { case Normal = 1000 case GoingAway = 1001 case ProtocolError = 1002 case ProtocolUnhandledType = 1003 // 1004 reserved. case NoStatusReceived = 1005 // 1006 reserved. case Encoding = 1007 case PolicyViolated = 1008 case MessageTooBig = 1009 } public static let ErrorDomain = "WebSocket" enum InternalErrorCode: UInt16 { // 0-999 WebSocket status codes not used case OutputStreamWriteError = 1 } /// Where the callback is executed. It defaults to the main UI thread queue. public var callbackQueue = dispatch_get_main_queue() var optionalProtocols : [String]? // MARK: - Constants let headerWSUpgradeName = "Upgrade" let headerWSUpgradeValue = "websocket" let headerWSHostName = "Host" let headerWSConnectionName = "Connection" let headerWSConnectionValue = "Upgrade" let headerWSProtocolName = "Sec-WebSocket-Protocol" let headerWSVersionName = "Sec-WebSocket-Version" let headerWSVersionValue = "13" let headerWSKeyName = "Sec-WebSocket-Key" let headerOriginName = "Origin" let headerWSAcceptName = "Sec-WebSocket-Accept" let BUFFER_MAX = 4096 let FinMask: UInt8 = 0x80 let OpCodeMask: UInt8 = 0x0F let RSVMask: UInt8 = 0x70 let MaskMask: UInt8 = 0x80 let PayloadLenMask: UInt8 = 0x7F let MaxFrameSize: Int = 32 let httpSwitchProtocolCode = 101 let supportedSSLSchemes = ["wss", "https"] class WSResponse { var isFin = false var code: OpCode = .ContinueFrame var bytesLeft = 0 var frameCount = 0 var buffer: NSMutableData? } // MARK: - Delegates /// Responds to callback about new messages coming in over the WebSocket /// and also connection/disconnect messages. public weak var delegate: WebSocketDelegate? /// Recives a callback for each pong message recived. public weak var pongDelegate: WebSocketPongDelegate? // MARK: - Block based API. public var onConnect: ((Void) -> Void)? public var onDisconnect: ((NSError?) -> Void)? public var onText: ((String) -> Void)? public var onData: ((NSData) -> Void)? public var onPong: ((Void) -> Void)? public var headers = [String: String]() public var voipEnabled = false public var selfSignedSSL = false public var security: SSLSecurity? public var enabledSSLCipherSuites: [SSLCipherSuite]? public var origin: String? public var timeout = 5 public var isConnected :Bool { return connected } public var currentURL: NSURL { return url } // MARK: - Private private var url: NSURL private var inputStream: NSInputStream? private var outputStream: NSOutputStream? private var connected = false private var isConnecting = false private var writeQueue = NSOperationQueue() private var readStack = [WSResponse]() private var inputQueue = [NSData]() private var fragBuffer: NSData? private var certValidated = false private var didDisconnect = false private var readyToWrite = false private let mutex = NSLock() private let notificationCenter = NSNotificationCenter.defaultCenter() private var canDispatch: Bool { mutex.lock() let canWork = readyToWrite mutex.unlock() return canWork } /// The shared processing queue used for all WebSocket. private static let sharedWorkQueue = dispatch_queue_create("com.vluxe.starscream.websocket", DISPATCH_QUEUE_SERIAL) /// Used for setting protocols. public init(url: NSURL, protocols: [String]? = nil) { self.url = url self.origin = url.absoluteString writeQueue.maxConcurrentOperationCount = 1 optionalProtocols = protocols } /// Connect to the WebSocket server on a background thread. public func connect() { guard !isConnecting else { return } didDisconnect = false isConnecting = true createHTTPRequest() isConnecting = false } /** Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed. If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate. If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate. - Parameter forceTimeout: Maximum time to wait for the server to close the socket. */ public func disconnect(forceTimeout forceTimeout: NSTimeInterval? = nil) { switch forceTimeout { case .Some(let seconds) where seconds > 0: dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))), callbackQueue) { [weak self] in self?.disconnectStream(nil) } fallthrough case .None: writeError(CloseCode.Normal.rawValue) default: disconnectStream(nil) break } } /** Write a string to the websocket. This sends it as a text frame. If you supply a non-nil completion block, I will perform it when the write completes. - parameter str: The string to write. - parameter completion: The (optional) completion handler. */ public func writeString(str: String, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame, writeCompletion: completion) } /** Write binary data to the websocket. This sends it as a binary frame. If you supply a non-nil completion block, I will perform it when the write completes. - parameter data: The data to write. - parameter completion: The (optional) completion handler. */ public func writeData(data: NSData, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(data, code: .BinaryFrame, writeCompletion: completion) } // Write a ping to the websocket. This sends it as a control frame. // Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s public func writePing(data: NSData, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(data, code: .Ping, writeCompletion: completion) } /// Private method that starts the connection. private func createHTTPRequest() { let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET", url, kCFHTTPVersion1_1).takeRetainedValue() var port = url.port if port == nil { if supportedSSLSchemes.contains(url.scheme!) { port = 443 } else { port = 80 } } addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue) addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue) if let protocols = optionalProtocols { addHeader(urlRequest, key: headerWSProtocolName, val: protocols.joinWithSeparator(",")) } addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue) addHeader(urlRequest, key: headerWSKeyName, val: generateWebSocketKey()) if let origin = origin { addHeader(urlRequest, key: headerOriginName, val: origin) } addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)") for (key,value) in headers { addHeader(urlRequest, key: key, val: value) } if let cfHTTPMessage = CFHTTPMessageCopySerializedMessage(urlRequest) { let serializedRequest = cfHTTPMessage.takeRetainedValue() initStreamsWithData(serializedRequest, Int(port!)) } } /// Add a header to the CFHTTPMessage by using the NSString bridges to CFString. private func addHeader(urlRequest: CFHTTPMessage, key: NSString, val: NSString) { CFHTTPMessageSetHeaderFieldValue(urlRequest, key, val) } /// Generate a WebSocket key as needed in RFC. private func generateWebSocketKey() -> String { var key = "" let seed = 16 for _ in 0..<seed { let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25))) key += "\(Character(uni))" } let data = key.dataUsingEncoding(NSUTF8StringEncoding) let baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) return baseKey! } /// Start the stream connection and write the data to the output stream. private func initStreamsWithData(data: NSData, _ port: Int) { //higher level API we will cut over to at some point //NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream) var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? let h: NSString = url.host! CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream) inputStream = readStream!.takeRetainedValue() outputStream = writeStream!.takeRetainedValue() guard let inStream = inputStream, let outStream = outputStream else { return } inStream.delegate = self outStream.delegate = self if supportedSSLSchemes.contains(url.scheme!) { inStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey) outStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey) } else { certValidated = true //not a https session, so no need to check SSL pinning } if voipEnabled { inStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType) outStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType) } if selfSignedSSL { let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool: false), kCFStreamSSLPeerName: kCFNull] inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String) outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String) } if let cipherSuites = self.enabledSSLCipherSuites { if let sslContextIn = CFReadStreamCopyProperty(inputStream, kCFStreamPropertySSLContext) as! SSLContextRef?, sslContextOut = CFWriteStreamCopyProperty(outputStream, kCFStreamPropertySSLContext) as! SSLContextRef? { let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count) let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count) if resIn != errSecSuccess { let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn)) disconnectStream(error) return } if resOut != errSecSuccess { let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut)) disconnectStream(error) return } } } CFReadStreamSetDispatchQueue(inStream, WebSocket.sharedWorkQueue) CFWriteStreamSetDispatchQueue(outStream, WebSocket.sharedWorkQueue) inStream.open() outStream.open() self.mutex.lock() self.readyToWrite = true self.mutex.unlock() let bytes = UnsafePointer<UInt8>(data.bytes) var out = timeout * 1000000 // wait 5 seconds before giving up writeQueue.addOperationWithBlock { [weak self] in while !outStream.hasSpaceAvailable { usleep(100) // wait until the socket is ready out -= 100 if out < 0 { self?.cleanupStream() self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: 2)) return } else if outStream.streamError != nil { return // disconnectStream will be called. } } outStream.write(bytes, maxLength: data.length) } } // Delegate for the stream methods. Processes incoming bytes. public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) { if let sec = security where !certValidated && [.HasBytesAvailable, .HasSpaceAvailable].contains(eventCode) { let possibleTrust: AnyObject? = aStream.propertyForKey(kCFStreamPropertySSLPeerTrust as String) if let trust: AnyObject = possibleTrust { let domain: AnyObject? = aStream.propertyForKey(kCFStreamSSLPeerName as String) if sec.isValid(trust as! SecTrustRef, domain: domain as! String?) { certValidated = true } else { let error = errorWithDetail("Invalid SSL certificate", code: 1) disconnectStream(error) return } } } if eventCode == .HasBytesAvailable { if aStream == inputStream { processInputStream() } } else if eventCode == .ErrorOccurred { disconnectStream(aStream.streamError) } else if eventCode == .EndEncountered { disconnectStream(nil) } } /// Disconnect the stream object and notifies the delegate. private func disconnectStream(error: NSError?) { if error == nil { writeQueue.waitUntilAllOperationsAreFinished() } else { writeQueue.cancelAllOperations() } cleanupStream() doDisconnect(error) } private func cleanupStream() { outputStream?.delegate = nil inputStream?.delegate = nil if let stream = inputStream { CFReadStreamSetDispatchQueue(stream, nil) stream.close() } if let stream = outputStream { CFWriteStreamSetDispatchQueue(stream, nil) stream.close() } outputStream = nil inputStream = nil } /// Handles the incoming bytes and sending them to the proper processing method. private func processInputStream() { let buf = NSMutableData(capacity: BUFFER_MAX) let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes) let length = inputStream!.read(buffer, maxLength: BUFFER_MAX) guard length > 0 else { return } var process = false if inputQueue.count == 0 { process = true } inputQueue.append(NSData(bytes: buffer, length: length)) if process { dequeueInput() } } /// Dequeue the incoming input so it is processed in order. private func dequeueInput() { while !inputQueue.isEmpty { let data = inputQueue[0] var work = data if let fragBuffer = fragBuffer { let combine = NSMutableData(data: fragBuffer) combine.appendData(data) work = combine self.fragBuffer = nil } let buffer = UnsafePointer<UInt8>(work.bytes) let length = work.length if !connected { processTCPHandshake(buffer, bufferLen: length) } else { processRawMessagesInBuffer(buffer, bufferLen: length) } inputQueue = inputQueue.filter{ $0 != data } } } // Handle checking the initial connection status. private func processTCPHandshake(buffer: UnsafePointer<UInt8>, bufferLen: Int) { let code = processHTTP(buffer, bufferLen: bufferLen) switch code { case 0: connected = true guard canDispatch else {return} dispatch_async(callbackQueue) { [weak self] in guard let s = self else { return } s.onConnect?() s.delegate?.websocketDidConnect(s) s.notificationCenter.postNotificationName(WebsocketDidConnectNotification, object: self) } case -1: fragBuffer = NSData(bytes: buffer, length: bufferLen) break // do nothing, we are going to collect more data default: doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code))) } } /// Finds the HTTP Packet in the TCP stream, by looking for the CRLF. private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int { let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] var k = 0 var totalSize = 0 for i in 0..<bufferLen { if buffer[i] == CRLFBytes[k] { k += 1 if k == 3 { totalSize = i + 1 break } } else { k = 0 } } if totalSize > 0 { let code = validateResponse(buffer, bufferLen: totalSize) if code != 0 { return code } totalSize += 1 //skip the last \n let restSize = bufferLen - totalSize if restSize > 0 { processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize) } return 0 //success } return -1 // Was unable to find the full TCP header. } /// Validates the HTTP is a 101 as per the RFC spec. private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int { let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue() CFHTTPMessageAppendBytes(response, buffer, bufferLen) let code = CFHTTPMessageGetResponseStatusCode(response) if code != httpSwitchProtocolCode { return code } if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) { let headers = cfHeaders.takeRetainedValue() as NSDictionary if let acceptKey = headers[headerWSAcceptName] as? NSString { if acceptKey.length > 0 { return 0 } } } return -1 } ///read a 16-bit big endian value from a buffer private static func readUint16(buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 { return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1]) } ///read a 64-bit big endian value from a buffer private static func readUint64(buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 { var value = UInt64(0) for i in 0...7 { value = (value << 8) | UInt64(buffer[offset + i]) } return value } /// Write a 16-bit big endian value to a buffer. private static func writeUint16(buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) { buffer[offset + 0] = UInt8(value >> 8) buffer[offset + 1] = UInt8(value & 0xff) } /// Write a 64-bit big endian value to a buffer. private static func writeUint64(buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) { for i in 0...7 { buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff) } } /// Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process. @warn_unused_result private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> { let response = readStack.last let baseAddress = buffer.baseAddress let bufferLen = buffer.count if response != nil && bufferLen < 2 { fragBuffer = NSData(buffer: buffer) return emptyBuffer } if let response = response where response.bytesLeft > 0 { var len = response.bytesLeft var extra = bufferLen - response.bytesLeft if response.bytesLeft > bufferLen { len = bufferLen extra = 0 } response.bytesLeft -= len response.buffer?.appendData(NSData(bytes: baseAddress, length: len)) processResponse(response) return buffer.fromOffset(bufferLen - extra) } else { let isFin = (FinMask & baseAddress[0]) let receivedOpcode = OpCode(rawValue: (OpCodeMask & baseAddress[0])) let isMasked = (MaskMask & baseAddress[1]) let payloadLen = (PayloadLenMask & baseAddress[1]) var offset = 2 if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .Pong { let errCode = CloseCode.ProtocolError.rawValue doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode)) writeError(errCode) return emptyBuffer } let isControlFrame = (receivedOpcode == .ConnectionClose || receivedOpcode == .Ping) if !isControlFrame && (receivedOpcode != .BinaryFrame && receivedOpcode != .ContinueFrame && receivedOpcode != .TextFrame && receivedOpcode != .Pong) { let errCode = CloseCode.ProtocolError.rawValue doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode)) writeError(errCode) return emptyBuffer } if isControlFrame && isFin == 0 { let errCode = CloseCode.ProtocolError.rawValue doDisconnect(errorWithDetail("control frames can't be fragmented", code: errCode)) writeError(errCode) return emptyBuffer } if receivedOpcode == .ConnectionClose { var code = CloseCode.Normal.rawValue if payloadLen == 1 { code = CloseCode.ProtocolError.rawValue } else if payloadLen > 1 { code = WebSocket.readUint16(baseAddress, offset: offset) if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) { code = CloseCode.ProtocolError.rawValue } offset += 2 } var closeReason = "connection closed by server" if payloadLen > 2 { let len = Int(payloadLen - 2) if len > 0 { let bytes = baseAddress + offset if let customCloseReason = String(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding) { closeReason = customCloseReason } else { code = CloseCode.ProtocolError.rawValue } } } doDisconnect(errorWithDetail(closeReason, code: code)) writeError(code) return emptyBuffer } if isControlFrame && payloadLen > 125 { writeError(CloseCode.ProtocolError.rawValue) return emptyBuffer } var dataLength = UInt64(payloadLen) if dataLength == 127 { dataLength = WebSocket.readUint64(baseAddress, offset: offset) offset += sizeof(UInt64) } else if dataLength == 126 { dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset)) offset += sizeof(UInt16) } if bufferLen < offset || UInt64(bufferLen - offset) < dataLength { fragBuffer = NSData(bytes: baseAddress, length: bufferLen) return emptyBuffer } var len = dataLength if dataLength > UInt64(bufferLen) { len = UInt64(bufferLen-offset) } let data: NSData if len < 0 { len = 0 data = NSData() } else { data = NSData(bytes: baseAddress+offset, length: Int(len)) } if receivedOpcode == .Pong { if canDispatch { dispatch_async(callbackQueue) { [weak self] in guard let s = self else { return } s.onPong?() s.pongDelegate?.websocketDidReceivePong(s) } } return buffer.fromOffset(offset + Int(len)) } var response = readStack.last if isControlFrame { response = nil // Don't append pings. } if isFin == 0 && receivedOpcode == .ContinueFrame && response == nil { let errCode = CloseCode.ProtocolError.rawValue doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode)) writeError(errCode) return emptyBuffer } var isNew = false if response == nil { if receivedOpcode == .ContinueFrame { let errCode = CloseCode.ProtocolError.rawValue doDisconnect(errorWithDetail("first frame can't be a continue frame", code: errCode)) writeError(errCode) return emptyBuffer } isNew = true response = WSResponse() response!.code = receivedOpcode! response!.bytesLeft = Int(dataLength) response!.buffer = NSMutableData(data: data) } else { if receivedOpcode == .ContinueFrame { response!.bytesLeft = Int(dataLength) } else { let errCode = CloseCode.ProtocolError.rawValue doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame", code: errCode)) writeError(errCode) return emptyBuffer } response!.buffer!.appendData(data) } if let response = response { response.bytesLeft -= Int(len) response.frameCount += 1 response.isFin = isFin > 0 ? true : false if isNew { readStack.append(response) } processResponse(response) } let step = Int(offset + numericCast(len)) return buffer.fromOffset(step) } } /// Process all messages in the buffer if possible. private func processRawMessagesInBuffer(pointer: UnsafePointer<UInt8>, bufferLen: Int) { var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen) repeat { buffer = processOneRawMessage(inBuffer: buffer) } while buffer.count >= 2 if buffer.count > 0 { fragBuffer = NSData(buffer: buffer) } } /// Process the finished response of a buffer. private func processResponse(response: WSResponse) -> Bool { if response.isFin && response.bytesLeft <= 0 { if response.code == .Ping { let data = response.buffer! // local copy so it's not perverse for writing dequeueWrite(data, code: OpCode.Pong) } else if response.code == .TextFrame { let str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding) if str == nil { writeError(CloseCode.Encoding.rawValue) return false } if canDispatch { dispatch_async(callbackQueue) { [weak self] in guard let s = self else { return } s.onText?(str! as String) s.delegate?.websocketDidReceiveMessage(s, text: str! as String) } } } else if response.code == .BinaryFrame { if canDispatch { let data = response.buffer! //local copy so it's not perverse for writing dispatch_async(callbackQueue) { [weak self] in guard let s = self else { return } s.onData?(data) s.delegate?.websocketDidReceiveData(s, data: data) } } } readStack.removeLast() return true } return false } /// Create an error. private func errorWithDetail(detail: String, code: UInt16) -> NSError { var details = [String: String]() details[NSLocalizedDescriptionKey] = detail return NSError(domain: WebSocket.ErrorDomain, code: Int(code), userInfo: details) } /// Write a an error to the socket. private func writeError(code: UInt16) { let buf = NSMutableData(capacity: sizeof(UInt16)) let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes) WebSocket.writeUint16(buffer, offset: 0, value: code) dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose) } /// Used to write things to the stream. private func dequeueWrite(data: NSData, code: OpCode, writeCompletion: (() -> ())? = nil) { writeQueue.addOperationWithBlock { [weak self] in //stream isn't ready, let's wait guard let s = self else { return } var offset = 2 let bytes = UnsafeMutablePointer<UInt8>(data.bytes) let dataLength = data.length let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize) let buffer = UnsafeMutablePointer<UInt8>(frame!.mutableBytes) buffer[0] = s.FinMask | code.rawValue if dataLength < 126 { buffer[1] = CUnsignedChar(dataLength) } else if dataLength <= Int(UInt16.max) { buffer[1] = 126 WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength)) offset += sizeof(UInt16) } else { buffer[1] = 127 WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength)) offset += sizeof(UInt64) } buffer[1] |= s.MaskMask let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset) SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey) offset += sizeof(UInt32) for i in 0..<dataLength { buffer[offset] = bytes[i] ^ maskKey[i % sizeof(UInt32)] offset += 1 } var total = 0 while true { guard let outStream = s.outputStream else { break } let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total) let len = outStream.write(writeBuffer, maxLength: offset-total) if len < 0 { var error: NSError? if let streamError = outStream.streamError { error = streamError } else { let errCode = InternalErrorCode.OutputStreamWriteError.rawValue error = s.errorWithDetail("output stream error during write", code: errCode) } s.doDisconnect(error) break } else { total += len } if total >= offset { if let callbackQueue = self?.callbackQueue, callback = writeCompletion { dispatch_async(callbackQueue) { callback() } } break } } } } /// Used to preform the disconnect delegate. private func doDisconnect(error: NSError?) { guard !didDisconnect else { return } didDisconnect = true connected = false guard canDispatch else {return} dispatch_async(callbackQueue) { [weak self] in guard let s = self else { return } s.onDisconnect?(error) s.delegate?.websocketDidDisconnect(s, error: error) let userInfo = error.map{ [WebsocketDisconnectionErrorKeyName: $0] } s.notificationCenter.postNotificationName(WebsocketDidDisconnectNotification, object: self, userInfo: userInfo) } } // MARK: - Deinit deinit { mutex.lock() readyToWrite = false mutex.unlock() cleanupStream() } } private extension NSData { convenience init(buffer: UnsafeBufferPointer<UInt8>) { self.init(bytes: buffer.baseAddress, length: buffer.count) } } private extension UnsafeBufferPointer { func fromOffset(offset: Int) -> UnsafeBufferPointer<Element> { return UnsafeBufferPointer<Element>(start: baseAddress.advancedBy(offset), count: count - offset) } } private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
1bddbadf8cbd8e5c9a8222d47e555c76
40.149321
226
0.581702
false
false
false
false
Angelbear/AutoLayoutDSL-Swift
refs/heads/develop
Source/AutoLayoutDSL-Swift.swift
mit
1
// // AutoLayoutDSK-Swift.swift // Angelbear // // Created by yangyang on 15/6/14. // Copyright (c) 2015 Angelbear. All rights reserved. // import UIKit let UILayoutPriorityDefaultHigh = 750 as Float let UILayoutPriorityDefaultLow = 250 as Float let UILayoutPriorityRequired = 1000 as Float extension NSLayoutConstraint { public convenience init(item view1: AnyObject, attribute attr1: NSLayoutAttribute, relatedBy relation: NSLayoutRelation, toItem view2: AnyObject?, attribute attr2: NSLayoutAttribute, multiplier: CGFloat, constant c: CGFloat, priority: UILayoutPriority) { self.init(item: view1, attribute: attr1, relatedBy: relation, toItem: view2, attribute: attr2, multiplier: multiplier, constant: c) self.priority = priority } } public class NSLayoutConstraintBuilder { public class DestinationComponent { var component: Component! var multiplier: CGFloat = 1 var constant: CGFloat = 0 public init(component: Component) { self.component = component } public func setConstant(constant: CGFloat) -> Self { self.constant = constant return self } public func setMultiplier(multiplier: CGFloat) -> Self { self.multiplier = multiplier return self } } public class Component { var view: UIView? var attribute: NSLayoutAttribute! public init(view: UIView?, attribute: NSLayoutAttribute) { self.view = view self.attribute = attribute } private func createBuilder(component: DestinationComponent, relation: NSLayoutRelation) -> NSLayoutConstraintBuilder { let builder = NSLayoutConstraintBuilder() builder.sourceComponent = self builder.destinationComponent = component builder.relation = relation return builder } public func equal(component: DestinationComponent) -> NSLayoutConstraintBuilder { return createBuilder(component: component, relation: .equal) } public func greaterThanOrEqual(component: DestinationComponent) -> NSLayoutConstraintBuilder { return createBuilder(component: component, relation: .greaterThanOrEqual) } public func lessThanOrEqual(component: DestinationComponent) -> NSLayoutConstraintBuilder { return createBuilder(component: component, relation: .lessThanOrEqual) } public func equal(constant: CGFloat) -> NSLayoutConstraintBuilder { return createBuilder(component: DestinationComponent(component: Component(view: nil, attribute: .notAnAttribute)).setConstant(constant: constant), relation: .equal) } public func greaterThanOrEqual(constant: CGFloat) -> NSLayoutConstraintBuilder { return createBuilder(component: DestinationComponent(component: Component(view: nil, attribute: .notAnAttribute)).setConstant(constant: constant), relation: .greaterThanOrEqual) } public func lessThanOrEqual(constant: CGFloat) -> NSLayoutConstraintBuilder { return createBuilder(component: DestinationComponent(component: Component(view: nil, attribute: .notAnAttribute)).setConstant(constant: constant), relation: .lessThanOrEqual) } } var sourceComponent: Component! var relation: NSLayoutRelation! var destinationComponent: DestinationComponent! var layoutPrority: UILayoutPriority = UILayoutPriorityRequired public func setPriority(priority: UILayoutPriority) -> Self { self.layoutPrority = priority return self } public func build() -> NSLayoutConstraint { return NSLayoutConstraint(item: sourceComponent.view!, attribute: sourceComponent.attribute, relatedBy: relation, toItem: destinationComponent.component.view, attribute: destinationComponent.component.attribute, multiplier: destinationComponent.multiplier, constant: destinationComponent.constant, priority: layoutPrority) } } extension UIView { private func attribute(attribute: NSLayoutAttribute) -> NSLayoutConstraintBuilder.Component { return NSLayoutConstraintBuilder.Component(view: self, attribute: attribute) } public var left: NSLayoutConstraintBuilder.Component { get { return attribute(attribute: .left) } } public var right: NSLayoutConstraintBuilder.Component { get { return attribute(attribute: .right) } } public var top: NSLayoutConstraintBuilder.Component { get { return attribute(attribute: .top) } } public var bottom: NSLayoutConstraintBuilder.Component { get { return attribute(attribute: .bottom) } } public var centerX: NSLayoutConstraintBuilder.Component { get { return attribute(attribute: .centerX) } } public var centerY: NSLayoutConstraintBuilder.Component { get { return attribute(attribute: .centerY) } } public var width: NSLayoutConstraintBuilder.Component { get { return attribute(attribute: .width) } } public var height: NSLayoutConstraintBuilder.Component { get { return attribute(attribute: .height) } } public var leading: NSLayoutConstraintBuilder.Component { get { return attribute(attribute: .leading) } } public var trailing: NSLayoutConstraintBuilder.Component { get { return attribute(attribute: .trailing) } } public var baseline: NSLayoutConstraintBuilder.Component { get { return attribute(attribute: .lastBaseline) } } } // Usage // sourceView.sourceAttribute = destinationView.destinationAttribute (*|/) multiplier (+|-) constant // * Support chain operions and will follow operation precedence to re-calculate multipliers and constaints public func == (component: NSLayoutConstraintBuilder.Component, destinationComponent: NSLayoutConstraintBuilder.DestinationComponent) -> NSLayoutConstraint { let builder = NSLayoutConstraintBuilder() builder.sourceComponent = component builder.destinationComponent = destinationComponent builder.relation = .equal return builder.build() } public func == (component: NSLayoutConstraintBuilder.Component, destinationComponent: NSLayoutConstraintBuilder.Component) -> NSLayoutConstraint { let builder = NSLayoutConstraintBuilder() builder.sourceComponent = component builder.destinationComponent = NSLayoutConstraintBuilder.DestinationComponent(component: destinationComponent) builder.relation = .equal return builder.build() } public func == (component: NSLayoutConstraintBuilder.Component, constant: CGFloat) -> NSLayoutConstraint { let builder = NSLayoutConstraintBuilder() builder.sourceComponent = component builder.destinationComponent = NSLayoutConstraintBuilder.DestinationComponent(component: NSLayoutConstraintBuilder.Component(view: nil, attribute: .notAnAttribute)).setConstant(constant: constant) builder.relation = .equal return builder.build() } public func >= (component: NSLayoutConstraintBuilder.Component, destinationComponent: NSLayoutConstraintBuilder.DestinationComponent) -> NSLayoutConstraint { let builder = NSLayoutConstraintBuilder() builder.sourceComponent = component builder.destinationComponent = destinationComponent builder.relation = .greaterThanOrEqual return builder.build() } public func >= (component: NSLayoutConstraintBuilder.Component, destinationComponent: NSLayoutConstraintBuilder.Component) -> NSLayoutConstraint { let builder = NSLayoutConstraintBuilder() builder.sourceComponent = component builder.destinationComponent = NSLayoutConstraintBuilder.DestinationComponent(component: destinationComponent) builder.relation = .greaterThanOrEqual return builder.build() } public func >= (component: NSLayoutConstraintBuilder.Component, constant: CGFloat) -> NSLayoutConstraint { let builder = NSLayoutConstraintBuilder() builder.sourceComponent = component builder.destinationComponent = NSLayoutConstraintBuilder.DestinationComponent(component: NSLayoutConstraintBuilder.Component(view: nil, attribute: .notAnAttribute)).setConstant(constant: constant) builder.relation = .greaterThanOrEqual return builder.build() } public func <= (component: NSLayoutConstraintBuilder.Component, destinationComponent: NSLayoutConstraintBuilder.DestinationComponent) -> NSLayoutConstraint { let builder = NSLayoutConstraintBuilder() builder.sourceComponent = component builder.destinationComponent = destinationComponent builder.relation = .lessThanOrEqual return builder.build() } public func <= (component: NSLayoutConstraintBuilder.Component, destinationComponent: NSLayoutConstraintBuilder.Component) -> NSLayoutConstraint { let builder = NSLayoutConstraintBuilder() builder.sourceComponent = component builder.destinationComponent = NSLayoutConstraintBuilder.DestinationComponent(component: destinationComponent) builder.relation = .lessThanOrEqual return builder.build() } public func <= (component: NSLayoutConstraintBuilder.Component, constant: CGFloat) -> NSLayoutConstraint { let builder = NSLayoutConstraintBuilder() builder.sourceComponent = component builder.destinationComponent = NSLayoutConstraintBuilder.DestinationComponent(component: NSLayoutConstraintBuilder.Component(view: nil, attribute: .notAnAttribute)).setConstant(constant: constant) builder.relation = .lessThanOrEqual return builder.build() } public func * (component: NSLayoutConstraintBuilder.Component, multiplier: CGFloat) -> NSLayoutConstraintBuilder.DestinationComponent { return NSLayoutConstraintBuilder.DestinationComponent(component: component).setMultiplier(multiplier: multiplier) } public func * (component: NSLayoutConstraintBuilder.DestinationComponent, multiplier: CGFloat) -> NSLayoutConstraintBuilder.DestinationComponent { return component.setMultiplier(multiplier: component.multiplier * multiplier).setConstant(constant: component.constant * multiplier) } public func / (component: NSLayoutConstraintBuilder.Component, multiplier: CGFloat) -> NSLayoutConstraintBuilder.DestinationComponent { return NSLayoutConstraintBuilder.DestinationComponent(component: component).setMultiplier(multiplier: 1.0 / multiplier) } public func / (component: NSLayoutConstraintBuilder.DestinationComponent, multiplier: CGFloat) -> NSLayoutConstraintBuilder.DestinationComponent { return component.setMultiplier(multiplier: component.multiplier / multiplier).setConstant(constant: component.constant / multiplier) } public func + (component: NSLayoutConstraintBuilder.Component, constant: CGFloat) -> NSLayoutConstraintBuilder.DestinationComponent { return NSLayoutConstraintBuilder.DestinationComponent(component: component).setConstant(constant: constant) } public func + (component: NSLayoutConstraintBuilder.DestinationComponent, constant: CGFloat) -> NSLayoutConstraintBuilder.DestinationComponent { return component.setConstant(constant: component.constant + constant) } public func - (component: NSLayoutConstraintBuilder.Component, contant: CGFloat) -> NSLayoutConstraintBuilder.DestinationComponent { return NSLayoutConstraintBuilder.DestinationComponent(component: component).setConstant(constant: -contant) } public func - (component: NSLayoutConstraintBuilder.DestinationComponent, constant: CGFloat) -> NSLayoutConstraintBuilder.DestinationComponent { return component.setConstant(constant: component.constant - constant) } precedencegroup AssignConstraint { associativity: left lowerThan: ComparisonPrecedence } // Help Function for adding NSLayoutConstaint的 // => dont change c=priority, default is UILayoutPriorityRequired // ~~> change priority to UILayoutPriorityDefaultHigh(750) // ~~~> change priority to UILayoutPriorityDefaultLow(250) // Operations will return view itself // we set precedence ot 120,so that it will be lower than ==, <=, >= // reference swift operation precedence from http://nshipster.com/swift-operators/ infix operator => : AssignConstraint public func => (view: UIView, constaint: NSLayoutConstraint) -> UIView { view.addConstraint(constaint) return view } infix operator ~~> : AssignConstraint public func ~~> (view: UIView, constaint: NSLayoutConstraint) -> UIView { constaint.priority = UILayoutPriorityDefaultHigh view.addConstraint(constaint) return view } infix operator ~~~> : AssignConstraint public func ~~~> (view: UIView, constaint: NSLayoutConstraint) -> UIView { constaint.priority = UILayoutPriorityDefaultLow view.addConstraint(constaint) return view }
5e7c515c0279aa51de8b2891fbe93440
41.222581
330
0.736496
false
false
false
false
alblue/swift
refs/heads/master
test/Profiler/pgo_switchenum.swift
apache-2.0
6
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -Xfrontend -enable-sil-ownership -profile-generate -Xfrontend -disable-incremental-llvm-codegen -module-name pgo_switchenum -o %t/main // This unusual use of 'sh' allows the path of the profraw file to be // substituted by %target-run. // RUN: %target-run sh -c 'env LLVM_PROFILE_FILE=$1 $2' -- %t/default.profraw %t/main // RUN: %llvm-profdata merge %t/default.profraw -o %t/default.profdata // need to move counts attached to expr for this // RUN: %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -enable-sil-ownership -emit-sorted-sil -emit-sil -module-name pgo_switchenum -o - | %FileCheck %s --check-prefix=SIL // need to lower switch_enum(addr) into IR for this // %target-swift-frontend %s -enable-sil-ownership -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -emit-ir -module-name pgo_switchenum -o - | %FileCheck %s --check-prefix=IR // need to check Opt support // %target-swift-frontend %s -enable-sil-ownership -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-sorted-sil -emit-sil -module-name pgo_switchenum -o - | %FileCheck %s --check-prefix=SIL-OPT // need to lower switch_enum(addr) into IR for this // %target-swift-frontend -enable-sil-ownership %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-ir -module-name pgo_switchenum -o - | %FileCheck %s --check-prefix=IR-OPT // REQUIRES: profile_runtime // REQUIRES: executable_test // REQUIRES: OS=macosx public enum MaybePair { case Neither case Left(Int32) case Right(String) case Both(Int32, String) } // SIL-LABEL: // pgo_switchenum.guess1 // SIL-LABEL: sil @$s14pgo_switchenum6guess11xs5Int32VAA9MaybePairO_tF : $@convention(thin) (@guaranteed MaybePair) -> Int32 !function_entry_count(5011) { // IR-LABEL: define swiftcc i32 @$s9pgo_switchenum6guess1s5Int32VAD1x_tF // IR-OPT-LABEL: define swiftcc i32 @$s9pgo_switchenum6guess1s5Int32VAD1x_tF public func guess1(x: MaybePair) -> Int32 { // SIL: switch_enum {{.*}} : $MaybePair, case #MaybePair.Neither!enumelt: {{.*}} !case_count(2), case #MaybePair.Left!enumelt.1: {{.*}} !case_count(5001), case #MaybePair.Right!enumelt.1: {{.*}} !case_count(3), case #MaybePair.Both!enumelt.1: {{.*}} !case_count(5) // SIL-OPT: switch_enum {{.*}} : $MaybePair, case #MaybePair.Neither!enumelt: {{.*}} !case_count(2), case #MaybePair.Left!enumelt.1: {{.*}} !case_count(5001), case #MaybePair.Right!enumelt.1: {{.*}} !case_count(3), case #MaybePair.Both!enumelt.1: {{.*}} !case_count(5) switch x { case .Neither: return 1 case let .Left(val): return val*2 case let .Right(val): return Int32(val.count) case let .Both(valNum, valStr): return valNum + Int32(valStr.count) } } // SIL-LABEL: // pgo_switchenum.guess2 // SIL-LABEL: sil @$s14pgo_switchenum6guess21xs5Int32VAA9MaybePairO_tF : $@convention(thin) (@guaranteed MaybePair) -> Int32 !function_entry_count(5011) { public func guess2(x: MaybePair) -> Int32 { // SIL: switch_enum {{.*}} : $MaybePair, case #MaybePair.Neither!enumelt: {{.*}} !case_count(2), case #MaybePair.Left!enumelt.1: {{.*}} !case_count(5001), default {{.*}} !default_count(8) // SIL-OPT: switch_enum {{.*}} : $MaybePair, case #MaybePair.Neither!enumelt: {{.*}} !case_count(2), case #MaybePair.Left!enumelt.1: {{.*}} !case_count(5001), default {{.*}} !default_count(8) switch x { case .Neither: return 1 case let .Left(val): return val*2 default: return 42; } } func main() { var guesses : Int32 = 0; guesses += guess1(x: MaybePair.Neither) guesses += guess1(x: MaybePair.Neither) guesses += guess1(x: MaybePair.Left(42)) guesses += guess1(x: MaybePair.Right("The Answer")) guesses += guess1(x: MaybePair.Right("The Answer")) guesses += guess1(x: MaybePair.Right("The Answer")) guesses += guess1(x: MaybePair.Both(42, "The Answer")) guesses += guess1(x: MaybePair.Both(42, "The Answer")) guesses += guess1(x: MaybePair.Both(42, "The Answer")) guesses += guess1(x: MaybePair.Both(42, "The Answer")) guesses += guess1(x: MaybePair.Both(42, "The Answer")) for _ in 1...5000 { guesses += guess1(x: MaybePair.Left(10)) } guesses += guess2(x: MaybePair.Neither) guesses += guess2(x: MaybePair.Neither) guesses += guess2(x: MaybePair.Left(42)) guesses += guess2(x: MaybePair.Right("The Answer")) guesses += guess2(x: MaybePair.Right("The Answer")) guesses += guess2(x: MaybePair.Right("The Answer")) guesses += guess2(x: MaybePair.Both(42, "The Answer")) guesses += guess2(x: MaybePair.Both(42, "The Answer")) guesses += guess2(x: MaybePair.Both(42, "The Answer")) guesses += guess2(x: MaybePair.Both(42, "The Answer")) guesses += guess2(x: MaybePair.Both(42, "The Answer")) for _ in 1...5000 { guesses += guess2(x: MaybePair.Left(10)) } } main() // IR: !{!"branch_weights", i32 5001, i32 3} // IR-OPT: !{!"branch_weights", i32 5001, i32 3}
31599df335163b71b29f71e2c8a357c6
46.190476
270
0.681534
false
false
false
false
grandiere/box
refs/heads/master
box/Controller/Main/CParent.swift
mit
1
import UIKit class CParent:UIViewController { enum TransitionVertical:CGFloat { case fromTop = -1 case fromBottom = 1 case none = 0 } enum TransitionHorizontal:CGFloat { case fromLeft = -1 case fromRight = 1 case none = 0 } private(set) weak var viewParent:VParent! private var barHidden:Bool = true private var statusBarStyle:UIStatusBarStyle = UIStatusBarStyle.lightContent init() { super.init(nibName:nil, bundle:nil) } required init?(coder:NSCoder) { return nil } override func viewDidLoad() { super.viewDidLoad() let controllerLanding:CLanding = CLanding() mainController(controller:controllerLanding) } override func loadView() { let viewParent:VParent = VParent(controller:self) self.viewParent = viewParent view = viewParent } override var preferredStatusBarStyle:UIStatusBarStyle { return statusBarStyle } override var prefersStatusBarHidden:Bool { return barHidden } //MARK: private private func slide(controller:CController, left:CGFloat) { guard let currentController:CController = childViewControllers.last as? CController, let newView:VView = controller.view as? VView, let currentView:VView = currentController.view as? VView else { return } addChildViewController(controller) controller.beginAppearanceTransition(true, animated:true) currentController.beginAppearanceTransition(false, animated:true) viewParent.slide( currentView:currentView, newView:newView, left:left) { controller.endAppearanceTransition() currentController.endAppearanceTransition() currentController.removeFromParentViewController() } } //MARK: public func hideBar(barHidden:Bool) { self.barHidden = barHidden setNeedsStatusBarAppearanceUpdate() } func statusBarAppareance(statusBarStyle:UIStatusBarStyle) { self.statusBarStyle = statusBarStyle setNeedsStatusBarAppearanceUpdate() } func slideTo(horizontal:TransitionHorizontal, controller:CController) { let left:CGFloat = -viewParent.bounds.maxX * horizontal.rawValue slide(controller:controller, left:left) } func mainController(controller:CController) { addChildViewController(controller) guard let newView:VView = controller.view as? VView else { return } viewParent.mainView(view:newView) } func push( controller:CController, horizontal:TransitionHorizontal = TransitionHorizontal.none, vertical:TransitionVertical = TransitionVertical.none, background:Bool = true, completion:(() -> ())? = nil) { let width:CGFloat = viewParent.bounds.maxX let height:CGFloat = viewParent.bounds.maxY let left:CGFloat = width * horizontal.rawValue let top:CGFloat = height * vertical.rawValue guard let currentController:CController = childViewControllers.last as? CController, let newView:VView = controller.view as? VView else { return } addChildViewController(controller) controller.beginAppearanceTransition(true, animated:true) currentController.beginAppearanceTransition(false, animated:true) viewParent.panRecognizer.isEnabled = true viewParent.push( newView:newView, left:left, top:top, background:background) { controller.endAppearanceTransition() currentController.endAppearanceTransition() completion?() } } func animateOver(controller:CController) { guard let currentController:CController = childViewControllers.last as? CController, let newView:VView = controller.view as? VView else { return } addChildViewController(controller) controller.beginAppearanceTransition(true, animated:true) currentController.beginAppearanceTransition(false, animated:true) viewParent.animateOver( newView:newView) { controller.endAppearanceTransition() currentController.endAppearanceTransition() } } func removeBetweenFirstAndLast() { var controllers:Int = childViewControllers.count - 1 while controllers > 1 { controllers -= 1 guard let controller:CController = childViewControllers[controllers] as? CController, let view:VView = controller.view as? VView else { continue } controller.beginAppearanceTransition(false, animated:false) view.removeFromSuperview() controller.endAppearanceTransition() controller.removeFromParentViewController() } } func removeAllButLast() { var controllers:Int = childViewControllers.count - 1 while controllers > 0 { controllers -= 1 guard let controller:CController = childViewControllers[controllers] as? CController, let view:VView = controller.view as? VView else { continue } controller.beginAppearanceTransition(false, animated:false) view.removeFromSuperview() controller.endAppearanceTransition() controller.removeFromParentViewController() } } func pop( horizontal:TransitionHorizontal = TransitionHorizontal.none, vertical:TransitionVertical = TransitionVertical.none, completion:(() -> ())? = nil) { let width:CGFloat = viewParent.bounds.maxX let height:CGFloat = viewParent.bounds.maxY let left:CGFloat = width * horizontal.rawValue let top:CGFloat = height * vertical.rawValue let controllers:Int = childViewControllers.count if controllers > 1 { guard let currentController:CController = childViewControllers[controllers - 1] as? CController, let previousController:CController = childViewControllers[controllers - 2] as? CController, let currentView:VView = currentController.view as? VView else { return } currentController.beginAppearanceTransition(false, animated:true) previousController.beginAppearanceTransition(true, animated:true) viewParent.pop( currentView:currentView, left:left, top:top) { previousController.endAppearanceTransition() currentController.endAppearanceTransition() currentController.removeFromParentViewController() completion?() if self.childViewControllers.count > 1 { self.viewParent.panRecognizer.isEnabled = true } else { self.viewParent.panRecognizer.isEnabled = false } } } } func popSilent(removeIndex:Int) { let controllers:Int = childViewControllers.count if controllers > removeIndex { guard let removeController:CController = childViewControllers[removeIndex] as? CController, let removeView:VView = removeController.view as? VView else { return } removeView.pushBackground?.removeFromSuperview() removeView.removeFromSuperview() removeController.removeFromParentViewController() if childViewControllers.count < 2 { self.viewParent.panRecognizer.isEnabled = false } } } func dismissAnimateOver(completion:(() -> ())?) { guard let currentController:CController = childViewControllers.last as? CController, let currentView:VView = currentController.view as? VView else { return } currentController.removeFromParentViewController() guard let previousController:CController = childViewControllers.last as? CController else { return } currentController.beginAppearanceTransition(false, animated:true) previousController.beginAppearanceTransition(true, animated:true) viewParent.dismissAnimateOver( currentView:currentView) { currentController.endAppearanceTransition() previousController.endAppearanceTransition() completion?() } } }
18c9517978d9860ae735fd406012a3ff
27.401146
107
0.560533
false
false
false
false
interstateone/Climate
refs/heads/master
Climate/FeedFormatter.swift
mit
1
// // FeedFormatter.swift // Climate // // Created by Brandon Evans on 2014-11-29. // Copyright (c) 2014 Brandon Evans. All rights reserved. // import UIKit class FeedFormatter: NSObject { private let valueFormatter = NSNumberFormatter() override init() { valueFormatter.roundingMode = .RoundHalfUp valueFormatter.maximumFractionDigits = 0 valueFormatter.groupingSeparator = " " valueFormatter.groupingSize = 3 valueFormatter.usesGroupingSeparator = true super.init() } func humanizeStreamName(streamName: String) -> String { return join(" ", streamName.componentsSeparatedByString("_")) } func formatValue(value: Float, symbol: String) -> String { let value = valueFormatter.stringFromNumber(value) ?? "0" return "\(value) \(symbol)" } }
43d201ab092278e5643945d7d895944e
25.53125
69
0.663133
false
false
false
false
vapor/vapor
refs/heads/main
Sources/Vapor/Middleware/Middleware.swift
mit
1
/// `Middleware` is placed between the server and your router. It is capable of /// mutating both incoming requests and outgoing responses. `Middleware` can choose /// to pass requests on to the next `Middleware` in a chain, or they can short circuit and /// return a custom `Response` if desired. public protocol Middleware { /// Called with each `Request` that passes through this middleware. /// - parameters: /// - request: The incoming `Request`. /// - next: Next `Responder` in the chain, potentially another middleware or the main router. /// - returns: An asynchronous `Response`. func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> } extension Array where Element == Middleware { /// Wraps a `Responder` in an array of `Middleware` creating a new `Responder`. /// - note: The array of middleware must be `[Middleware]` not `[M] where M: Middleware`. public func makeResponder(chainingTo responder: Responder) -> Responder { var responder = responder for middleware in reversed() { responder = middleware.makeResponder(chainingTo: responder) } return responder } } public extension Middleware { /// Wraps a `Responder` in a single `Middleware` creating a new `Responder`. func makeResponder(chainingTo responder: Responder) -> Responder { return HTTPMiddlewareResponder(middleware: self, responder: responder) } } private struct HTTPMiddlewareResponder: Responder { var middleware: Middleware var responder: Responder init(middleware: Middleware, responder: Responder) { self.middleware = middleware self.responder = responder } /// Chains an incoming request to another `Responder` on the router. /// - parameters: /// - request: The incoming `Request`. /// - returns: An asynchronous `Response`. func respond(to request: Request) -> EventLoopFuture<Response> { return self.middleware.respond(to: request, chainingTo: self.responder) } }
97a3322ca5bbb6049ac4d74b38365fb0
41.428571
101
0.686388
false
false
false
false
gradyzhuo/GZHTTPConnection
refs/heads/master
GZHTTPConnection/GZHTTPConnectionValueParam.swift
mit
1
// // GZHTTPConnectionDataParam.swift // Flingy // // Created by Grady Zhuo on 2/27/15. // Copyright (c) 2015 Grady Zhuo. All rights reserved. // import UIKit class GZHTTPConnectionValueParam{ var type:GZHTTPConnectionParamType{ return .String } var key:String var value:AnyObject init(key:String, value:AnyObject){ self.key = key self.value = value as AnyObject } } class GZHTTPConnectionStringValueParam: GZHTTPConnectionValueParam { //Empty init(key:String, stringValue:String){ super.init(key: key, value: stringValue) } } //class GZHTTPConnectionArrayPartValueParam: GZHTTPConnectionValueParam { // //Empty // // init(key:String, arrayValue:[AnyObject]){ // super.init(key: key, value: arrayValue) // } // //} class GZHTTPConnectionFileValueParam: GZHTTPConnectionValueParam { override var type:GZHTTPConnectionParamType{ return .File } var filenmae = "Default" var contentType:GZHTTPConnectionFileContentType = .All init(key: String, fileData: NSData) { super.init(key: key, value: fileData) } convenience init(filename:String, key: String, fileData: NSData) { self.init(contentType:.All, filename:filename, key: key, fileData: fileData) } convenience init(contentType:GZHTTPConnectionFileContentType, filename:String, key: String, fileData: NSData) { self.init(key: key, fileData: fileData) self.filenmae = filename self.contentType = contentType } } class GZHTTPConnectionImageDataValueParam: GZHTTPConnectionFileValueParam { override var type:GZHTTPConnectionParamType{ return .File } override init(key: String, fileData: NSData) { super.init(key: key, fileData: fileData) self.contentType = .JPEG } } //MARK: - add params extension GZHTTPConnectionData { func addParam(param:GZHTTPConnectionValueParam){ self.paramsArray.append(param) } func addParam(key key:String, boolValue value:Bool?)->GZHTTPConnectionValueParam{ let defaultValue = false return self.addParam(key: key, intValue: Int(value ?? defaultValue)) } func addParam(key key:String, intValue value:Int?)->GZHTTPConnectionValueParam{ let defaultValue = 0 let stringValue = "\(value ?? defaultValue)" return self.addParam(key: key, stringValue: stringValue) } func addParam(key key:String, stringValue value:String?)->GZHTTPConnectionValueParam{ let defaultValue = "" let param = GZHTTPConnectionStringValueParam(key: key, stringValue: value ?? defaultValue) self.addParam(param) return param } func addParam(key key:String, stringValueFromArray value:[AnyObject]?, componentsJoinedByString separator:String = ",")->GZHTTPConnectionValueParam{ return self += key & (value ?? []) << separator } //MARK: - file handler func addParam(key key:String, fileData value:NSData?, contentType:GZHTTPConnectionFileContentType, filename:String)->GZHTTPConnectionValueParam{ let defaultValue = NSData() let param = GZHTTPConnectionImageDataValueParam(contentType: contentType, filename: filename, key: key, fileData: value ?? defaultValue) self.addParam(param) return param } func addAnyFileDataValueParam(key key:String, fileData value:NSData?, filename:String)->GZHTTPConnectionValueParam{ return self.addParam(key: key, fileData: value, contentType: .All, filename: filename) } //MARK: image handler func addJPEGImageDataValueParam(key key:String, fileData value:NSData?, filename:String)->GZHTTPConnectionValueParam{ return self.addParam(key: key, fileData: value, contentType: .JPEG, filename: filename) } func addJPEGImageDataValueParam(key key:String, image:UIImage!, filename:String, compressionQuality:CGFloat)->GZHTTPConnectionValueParam{ let data = UIImageJPEGRepresentation(image, compressionQuality) return self.addJPEGImageDataValueParam(key: key, fileData: data, filename: filename) } func addPNGImageDataValueParam(key key:String, fileData value:NSData?, filename:String)->GZHTTPConnectionValueParam{ return self.addParam(key: key, fileData: value, contentType: .PNG, filename: filename) } func addPNGImageDataValueParam(key key:String, image:UIImage!, filename:String)->GZHTTPConnectionValueParam{ let data = UIImagePNGRepresentation(image) return self.addPNGImageDataValueParam(key: key, fileData: data, filename: filename) } } //MARK: - remove param extension GZHTTPConnectionData { func removeParam(forKey key:String){ self.paramsArray = self.paramsArray.filter{ return $0.key != key } } func removeParam(param:GZHTTPConnectionValueParam){ self.removeParam(forKey: param.key) } }
1d72cb6c2ba0e36cdd199f54681c009b
29.43787
152
0.673989
false
false
false
false
gribozavr/swift
refs/heads/master
test/Constraints/if_expr.swift
apache-2.0
3
// RUN: %target-typecheck-verify-swift func useInt(_ x: Int) {} func useDouble(_ x: Double) {} class B { init() {} } class D1 : B { override init() { super.init() } } class D2 : B { override init() { super.init() } } func useB(_ x: B) {} func useD1(_ x: D1) {} func useD2(_ x: D2) {} var a = true ? 1 : 0 // should infer Int var b : Double = true ? 1 : 0 // should infer Double var c = true ? 1 : 0.0 // should infer Double var d = true ? 1.0 : 0 // should infer Double useInt(a) useDouble(b) useDouble(c) useDouble(d) var z = true ? a : b // expected-error{{result values in '? :' expression have mismatching types 'Int' and 'Double'}} var _ = a ? b : b // expected-error{{cannot convert value of type 'Int' to expected condition type 'Bool'}} var e = true ? B() : B() // should infer B var f = true ? B() : D1() // should infer B var g = true ? D1() : B() // should infer B var h = true ? D1() : D1() // should infer D1 var i = true ? D1() : D2() // should infer B useB(e) useD1(e) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}} useB(f) useD1(f) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}} useB(g) useD1(g) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}} useB(h) useD1(h) useB(i) useD1(i) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}} useD2(i) // expected-error{{cannot convert value of type 'B' to expected argument type 'D2'}} var x = true ? 1 : 0 var y = 22 ? 1 : 0 // expected-error{{cannot convert value of type 'Int' to expected condition type 'Bool'}} _ = x ? x : x // expected-error {{cannot convert value of type 'Int' to expected condition type 'Bool'}} _ = true ? x : 1.2 // expected-error {{result values in '? :' expression have mismatching types 'Int' and 'Double'}} _ = (x: true) ? true : false // expected-error {{cannot convert value of type '(x: Bool)' to expected condition type 'Bool'}} _ = (x: 1) ? true : false // expected-error {{cannot convert value of type '(x: Int)' to expected condition type 'Bool'}} let ib: Bool! = false let eb: Bool? = .some(false) let conditional = ib ? "Broken" : "Heart" // should infer Bool! let conditional = eb ? "Broken" : "Heart" // expected-error {{value of optional type 'Bool?' must be unwrapped}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} // <rdar://problem/39586166> - crash when IfExpr has UnresolvedType in condition struct Delegate { var shellTasks: [ShellTask] } extension Array { subscript(safe safe: Int) -> Element? { get { } set { } } } struct ShellTask { var commandLine: [String] } let delegate = Delegate(shellTasks: []) _ = delegate.shellTasks[safe: 0]?.commandLine.compactMap({ $0.asString.hasPrefix("") ? $0 : nil }).count ?? 0 // expected-error@-1 {{value of type 'String' has no member 'asString'}}
5c15ee56bc715b2aed8f4529238244af
33.931034
125
0.651201
false
false
false
false
jesshmusic/MarkovAnalyzer
refs/heads/master
MarkovAnalyzer/ChordAnalysis.swift
mit
1
// // ChordAnalysis.swift // MarkovAnalyzer // // Created by Jess Hendricks on 7/25/15. // Copyright © 2015 Existential Music. All rights reserved. // import Cocoa class ChordAnalysis: NSObject { // MARK: class functions called without instantiating ChordAnalysis class func modTwelve(var number: Int) -> Int { number = number % 12 if number < 0 { number = number + 12 } return number } // MARK: Instantiated functions // func generateChordFromNotes(var notes: [Note]) -> [Chord] { // var returnChords = [Chord]() // if notes.count > 1 { // notes = self.stackChordInThirds(notes) // // } else { // // for possibleNote in notes[0].enharmonicNoteNames { // returnChords.append(Chord(chordName: possibleNote)) // } // return returnChords // } // // return returnChords // } // func stackChordInThirds(var notes: [Note]) -> [Note] { // let thirdIntervals = [3, 4, 6, 7, 10, 11] // var isStackedInThirds = false // while !isStackedInThirds { // notes = notes.sort({$0.noteNumber < $1.noteNumber}) // var intervalsChanged = false // for index in 1..<notes.count { // let interval = notes[index].noteNumber - notes[0].noteNumber // if !thirdIntervals.contains(interval) { // notes[index].noteNumber = notes[index].noteNumber - 12 // intervalsChanged = true // } // } // if !intervalsChanged { // isStackedInThirds = true // } // } // return notes.sort({$0.noteNumber < $1.noteNumber}) // } // private func getChordsFromNotes(notes: [Note]) -> [Chord] { // var intervalList = [Int]() // var newChord = Chord(chordName: notes[0].noteName) // for index in 1..<notes.count { // // TODO: Use intervals of stacked chord to get quality. // } // return [] // } // private func getChordForChordName(chordName: String, bassNote: Note) -> Chord { // // var bassNoteString = "" // if bassNote.noteName.rangeOfString(chordName) == nil { // bassNoteString = "/\(bassNote.noteName)" // } // return Chord(chordName: chordName + bassNoteString) // } // // private func getChordsForChordNames(chordNames: [String], bassNote: Note) -> [Chord] { // var returnChords = [Chord]() // for chordName in chordNames { // var bassNoteString = "" // if bassNote.noteName.rangeOfString(chordName) == nil { // bassNoteString = "/\(bassNote.noteName)" // } // returnChords.append(Chord(chordName: chordName + bassNoteString)) // } // return returnChords // } private func getBassNote(notes: [Note]) -> Note { var lowestNote: Note! for note in notes { if lowestNote == nil { lowestNote = note } else { if lowestNote.noteNumber > note.noteNumber { lowestNote = note } } } return lowestNote } private func getNoteFromNumber(noteNumber: Int) -> Note { let noteNumberMod = noteNumber % 12 switch noteNumberMod { case 0: return Note(noteName: "C", noteNumber: noteNumber) case 1: return Note(noteName: "C#", noteNumber: noteNumber) case 2: return Note(noteName: "D", noteNumber: noteNumber) case 3: return Note(noteName: "Eb", noteNumber: noteNumber) case 4: return Note(noteName: "E", noteNumber: noteNumber) case 5: return Note(noteName: "F", noteNumber: noteNumber) case 6: return Note(noteName: "F#", noteNumber: noteNumber) case 7: return Note(noteName: "G", noteNumber: noteNumber) case 8: return Note(noteName: "Ab", noteNumber: noteNumber) case 9: return Note(noteName: "A", noteNumber: noteNumber) case 10: return Note(noteName: "Bb", noteNumber: noteNumber) default: return Note(noteName: "B", noteNumber: noteNumber) } } private func getNoteListFromNumber(noteNumber: Int) -> [Note] { let noteNumberMod = noteNumber % 12 switch noteNumberMod { case 0: return [Note(noteName: "C", noteNumber: noteNumber), Note(noteName: "B#", noteNumber: noteNumber)] case 1: return [Note(noteName: "Db", noteNumber: noteNumber), Note(noteName: "C#", noteNumber: noteNumber)] case 2: return [Note(noteName: "D", noteNumber: noteNumber)] case 3: return [Note(noteName: "Eb", noteNumber: noteNumber), Note(noteName: "D#", noteNumber: noteNumber)] case 4: return [Note(noteName: "E", noteNumber: noteNumber), Note(noteName: "Fb", noteNumber: noteNumber)] case 5: return [Note(noteName: "F", noteNumber: noteNumber), Note(noteName: "E#", noteNumber: noteNumber)] case 6: return [Note(noteName: "Gb", noteNumber: noteNumber), Note(noteName: "F#", noteNumber: noteNumber)] case 7: return [Note(noteName: "G", noteNumber: noteNumber)] case 8: return [Note(noteName: "Ab", noteNumber: noteNumber), Note(noteName: "G#", noteNumber: noteNumber)] case 9: return [Note(noteName: "A", noteNumber: noteNumber)] case 10: return [Note(noteName: "Bb", noteNumber: noteNumber), Note(noteName: "A#", noteNumber: noteNumber)] default: return [Note(noteName: "B", noteNumber: noteNumber), Note(noteName: "Cb", noteNumber: noteNumber)] } } } //func generateChordFromNotes(notes: [Note]) -> (chords:[Chord], normalOrderSet:Set<Int>) { // // var returnChords: [Chord]! // var reducedNotes = Set<Int>() // let bassNote = self.getBassNote(notes) // for note in notes { // reducedNotes.insert(note.noteNumber % 12) // } // var reducedNotesArray = [Note]() // for reducedNote in reducedNotes { // reducedNotesArray.append(self.getNoteFromNumber(reducedNote)) // } // let normalOrderSet = self.getNormalOrder(reducedNotesArray) // var testNoteSet = normalOrderSet.notes // var transposeNumber = 0 // var returnChord = Chord(chordName: "N/A") // for _ in 0..<12 { // if self.chordQualities[normalOrderSet.noteNumbers] != nil { // returnChord = self.getChordForChordName(normalOrderSet.notes[transposeNumber].noteName + self.chordQualities[normalOrderSet.noteNumbers]!, bassNote: bassNote) // break // } // transposeNumber++ // testNoteSet = self.transposeByInterval(transposeNumber, notes: testNoteSet) // } // // // if returnChords == nil { // returnChords = [Chord(chordName: "N/A")] // } // return ([returnChord], normalOrderSet.noteNumbers) //} // self.triadNames = [ // // // Triads // Set<Int>([0, 4, 7]): ["C", "B#"], // Set<Int>([0, 3, 7]): ["Cm", "B#m"], // Set<Int>([0, 3, 6]): ["Co", "B#o"], // Set<Int>([0, 4, 8]): ["C+", "E+", "G#+", "Ab+"], // // Set<Int>([1, 5, 8]): ["Db", "C#"], // Set<Int>([1, 4, 8]): ["Dbm", "C#m"], // Set<Int>([1, 4, 7]): ["Dbo", "C#o"], // Set<Int>([1, 5, 9]): ["Db+", "C#+", "F+", "A+"], // // Set<Int>([2, 6, 9]): ["D"], // Set<Int>([2, 5, 9]): ["Dm"], // Set<Int>([2, 5, 8]): ["Do"], // Set<Int>([2, 6, 10]): ["D+", "F#+", "Gb+", "A#+", "Bb+"], // // Set<Int>([3, 7, 10]): ["Eb", "D#"], // Set<Int>([3, 6, 10]): ["Ebm", "D#m"], // Set<Int>([3, 6, 9]): ["Ebo", "D#o"], // Set<Int>([3, 7, 11]): ["Eb+", "D#+", "G+", "B+"], // // Set<Int>([4, 8, 11]): ["E", "Fb"], // Set<Int>([4, 7, 11]): ["Em", "Fbm"], // Set<Int>([4, 7, 10]): ["Eo", "Fbo"], // // Set<Int>([0, 5, 9]): ["F", "E#"], // Set<Int>([0, 5, 8]): ["Fm", "E#m"], // Set<Int>([5, 8, 11]): ["Fo", "E#o"], // // Set<Int>([1, 6, 10]): ["Gb", "F#"], // Set<Int>([1, 6, 9]): ["Gbm", "F#m"], // Set<Int>([0, 6, 9]): ["Gbo", "F#o"], // // Set<Int>([2, 7, 11]): ["G"], // Set<Int>([2, 7, 10]): ["Gm"], // Set<Int>([1, 7, 10]): ["Go"], // // Set<Int>([0, 3, 8]): ["Ab", "G#"], // Set<Int>([3, 8, 11]): ["Abm", "G#m"], // Set<Int>([2, 8, 11]): ["Abo", "G#o"], // // Set<Int>([1, 4, 9]): ["A"], // Set<Int>([0, 4, 9]): ["Am"], // Set<Int>([0, 3, 9]): ["Ao"], // // Set<Int>([2, 5, 10]): ["Bb", "A#"], // Set<Int>([1, 5, 10]): ["Bbm", "A#m"], // Set<Int>([1, 4, 10]): ["Bbo", "A#o"], // // Set<Int>([3, 6, 11]): ["B", "Cb"], // Set<Int>([2, 6, 11]): ["Bm", "Cbm"], // Set<Int>([2, 5, 11]): ["Bo", "Cbo"], // // // Italian Augemented-Six chords or Dominant seventh without fifth // // Set<Int>([0, 4, 10]): ["C7", "B#7", "ItaA6"], // Set<Int>([1, 5, 11]): ["Db7", "C#7", "ItaA6"], // Set<Int>([2, 6, 0]): ["D7", "ItaA6"], // Set<Int>([3, 7, 1]): ["Eb7", "D#7", "ItaA6"], // Set<Int>([4, 8, 2]): ["E7", "Fb7", "ItaA6"], // Set<Int>([5, 9, 3]): ["F7", "E#7", "ItaA6"], // Set<Int>([6, 10, 4]): ["Gb7", "F#7", "ItaA6"], // Set<Int>([7, 11, 5]): ["G7", "ItaA6"], // Set<Int>([8, 0, 6]): ["Ab7", "G#7", "ItaA6"], // Set<Int>([9, 1, 7]): ["A7", "ItaA6"], // Set<Int>([10, 2, 8]): ["Bb7", "A#7", "ItaA6"], // Set<Int>([11, 3, 9]): ["B7", "Cb7", "ItaA6"] // ] // // // self.seventhChordNames = [ // // Seventh Chords Standard // Set<Int>([0, 3, 7, 10]): ["Cm7", "B#m7"], // Set<Int>([0, 3, 7, 11]): ["CmM7", "B#mM7"], // Set<Int>([0, 4, 7, 10]): ["C7", "B#7", "GerA6"], // Set<Int>([0, 4, 7, 11]): ["Cmaj7", "B#maj7"], // // Set<Int>([1, 4, 8, 11]): ["Dbm7", "C#m7"], // Set<Int>([1, 4, 8, 0]): ["DbmM7", "C#mM7"], // Set<Int>([1, 5, 8, 11]): ["Db7", "C#7", "GerA6"], // Set<Int>([1, 5, 8, 0]): ["Dbmaj7", "C#maj7"], // // Set<Int>([2, 5, 9, 0]): ["Dm7"], // Set<Int>([2, 5, 9, 1]): ["DmM7"], // Set<Int>([2, 6, 9, 0]): ["D7"], // Set<Int>([2, 6, 9, 1]): ["Dmaj7"], // // Set<Int>([3, 6, 10, 1]): ["Ebm7", "D#m7"], // Set<Int>([3, 6, 10, 2]): ["EbmM7", "D#mM7"], // Set<Int>([3, 7, 10, 1]): ["Eb7", "D#7", "GerA6"], // Set<Int>([3, 7, 10, 2]): ["Ebmaj7", "D#maj7"], // // Set<Int>([4, 7, 11, 2]): ["Em7", "Fbm7"], // Set<Int>([4, 7, 11, 3]): ["EmM7", "FbmM7"], // Set<Int>([4, 8, 11, 2]): ["E7", "Fb7", "GerA6"], // Set<Int>([4, 8, 11, 3]): ["Emaj7", "Fbmaj7"], // // Set<Int>([5, 8, 0, 3]): ["Fm7", "E#m7"], // Set<Int>([5, 8, 0, 4]): ["FmM7", "E#mM7"], // Set<Int>([5, 9, 0, 3]): ["F7", "E#7", "GerA6"], // Set<Int>([5, 9, 0, 4]): ["Fmaj7", "Emaj7"], // // Set<Int>([6, 9, 1, 4]): ["Gbm7", "F#m7"], // Set<Int>([6, 9, 1, 5]): ["GbmM7", "F#mM7"], // Set<Int>([6, 10, 1, 4]): ["Gb7", "F#7", "GerA6"], // Set<Int>([6, 10, 1, 5]): ["Gbmaj7", "F#maj7"], // // Set<Int>([7, 10, 2, 5]): ["Gm7"], // Set<Int>([7, 10, 2, 6]): ["GmM7"], // Set<Int>([7, 11, 2, 5]): ["G7", "GerA6"], // Set<Int>([7, 11, 2, 6]): ["Gmaj7"], // // Set<Int>([8, 11, 3, 6]): ["Abm7", "G#m7"], // Set<Int>([8, 11, 3, 7]): ["AbmM7", "G#mM7"], // Set<Int>([8, 0, 3, 6]): ["Ab7", "G#7", "GerA6"], // Set<Int>([8, 0, 3, 7]): ["Abmaj7", "G#maj7"], // // Set<Int>([9, 0, 4, 7]): ["Am7"], // Set<Int>([9, 0, 4, 8]): ["AmM7"], // Set<Int>([9, 1, 4, 7]): ["A7", "GerA6"], // Set<Int>([9, 1, 4, 8]): ["Amaj7"], // // Set<Int>([10, 1, 5, 8]): ["Bbm7", "A#m7"], // Set<Int>([10, 1, 5, 9]): ["BbmM7", "A#mM7"], // Set<Int>([10, 2, 5, 8]): ["Bb7", "A#7", "GerA6"], // Set<Int>([10, 2, 5, 9]): ["Bbmaj7", "A#maj7"], // // Set<Int>([11, 2, 6, 9]): ["Em7", "Fbm7"], // Set<Int>([11, 2, 6, 10]): ["EmM7", "FbmM7"], // Set<Int>([11, 3, 6, 9]): ["E7", "Fb7", "GerA6"], // Set<Int>([11, 3, 6, 10]): ["Emaj7", "Fbmaj7"], // // // Half Diminished 7th chords // Set<Int>([0, 3, 6, 10]): ["Cø7", "B#ø7"], // Set<Int>([1, 4, 7, 11]): ["Dbø7", "C#ø7"], // Set<Int>([2, 5, 8, 0]): ["Dø7"], // Set<Int>([3, 6, 9, 1]): ["Ebø7", "D#ø7"], // Set<Int>([4, 7, 10, 2]): ["Eø7", "Fbø7"], // Set<Int>([5, 8, 11, 3]): ["Fø7", "E#ø7"], // Set<Int>([6, 9, 0, 4]): ["F#ø7", "Gbø7"], // Set<Int>([7, 10, 1, 5]): ["Gø7"], // Set<Int>([8, 11, 2, 6]): ["Abø7", "G#ø7"], // Set<Int>([9, 0, 3, 7]): ["Aø7"], // Set<Int>([10, 1, 4, 8]): ["Bbø7", "A#ø7"], // Set<Int>([11, 2, 5, 9]): ["Bø7", "Cø7"], // // // Fully Diminished 7th chords (When the bass note is known, simply replace the first character with that // Set<Int>([0, 3, 6, 9]): ["o7"], // Set<Int>([1, 4, 7, 10]): ["o7"], // Set<Int>([2, 5, 8, 11]): ["o7"], // // // French Augemented-Six chords // Set<Int>([0, 4, 6, 10]): ["FrenchA6"], // Set<Int>([1, 5, 7, 11]): ["FrenchA6"], // Set<Int>([2, 6, 8, 0]): ["FrenchA6"], // Set<Int>([3, 7, 9, 1]): ["FrenchA6"], // Set<Int>([4, 8, 10, 2]): ["FrenchA6"], // Set<Int>([5, 9, 11, 3]): ["FrenchA6"] // ] // MARK: Chord Pitch Sets // self.chordQualities = [ // Set<Int>([0]): "", // Set<Int>([7, 0]): "5", // Set<Int>([0, 4]): "", // Set<Int>([0, 3]): "m", // Set<Int>([0, 4, 7]): "", // Set<Int>([0, 3, 7]): "m", // Set<Int>([0, 3, 6]): "dim", // Set<Int>([0, 4, 8]): "aug", // Set<Int>([10, 0, 4]): "7", // Set<Int>([7, 10, 0]): "7", // Set<Int>([4, 7, 10, 0]): "7", // Set<Int>([11, 0, 4, 7]): "maj7", // Set<Int>([7, 10, 0, 3]): "m7", // Set<Int>([11, 0, 3, 7]): "m(maj7)", // Set<Int>([10, 0, 3, 6]): "ø7", // Set<Int>([0, 3, 6, 9]): "º7", // Set<Int>([0, 2, 4, 7]): "9", // Set<Int>([0, 1, 4, 7]): "7b9", // Set<Int>([0, 2, 3, 7]): "m9", // Set<Int>([0, 1, 3, 7]): "m7b9", // Set<Int>([10, 0, 2, 4, 7]): "9", // Set<Int>([11, 0, 2, 4, 7]): "maj9", // Set<Int>([10, 0, 1, 4, 7]): "7b9", // Set<Int>([7, 10, 0, 2, 3]): "m9", // Set<Int>([7, 10, 0, 1, 3]): "m7b9", // Set<Int>([11, 0, 2, 3, 6]): "m(maj9)", // Set<Int>([11, 0, 2, 3, 7]): "m(maj7)9", // Set<Int>([11, 0, 1, 3, 7]): "m(maj7)b9", // Set<Int>([4, 6, 10, 0]): "FrenchA6" // ] //This version is in order to see if there might be a trick for 7ths , 9ths, 11ths, etc. // self.chordQualities = [ // // Set<Int>([0, 4, 7]): "", // Set<Int>([0, 3, 7]): "m", // Set<Int>([0, 3, 6]): "dim", // Set<Int>([0, 4, 8]): "aug", // Set<Int>([0, 4, 10]): "7", // Set<Int>([0, 7, 10]): "7", // Set<Int>([0, 4, 7, 10]): "7", // Set<Int>([0, 4, 7, 11]): "maj7", // Set<Int>([0, 3, 7, 10]): "m7", // Set<Int>([0, 3, 7, 11]): "m(maj7)", // Set<Int>([0, 3, 6, 10]): "ø7", // Set<Int>([0, 3, 6, 9]): "º7", // Set<Int>([0, 2, 4, 7]): "9", // Set<Int>([0, 1, 4, 7]): "7b9", // Set<Int>([0, 2, 3, 7]): "m9", // Set<Int>([0, 1, 3, 7]): "m7b9", // Set<Int>([0, 2, 4, 7, 10]): "9", // Set<Int>([0, 2, 4, 7, 11]): "maj9", // Set<Int>([0, 1, 4, 7, 10]): "7b9", // Set<Int>([0, 2, 3, 7, 10]): "m9", // Set<Int>([0, 1, 3, 7, 10]): "m7b9", // Set<Int>([0, 2, 3, 6, 11]): "m(maj9)", // Set<Int>([0, 2, 3, 7, 11]): "m(maj7)9", // Set<Int>([0, 1, 3, 7, 11]): "m(maj7)b9", // Set<Int>([0, 1, 3, 7, 11]): "mM7b9", // Set<Int>([4, 6, 10, 0]): "FrenchA6" // ] //private func getNormalOrder(notes: [Note]) -> (notes: [Note], noteNumbers: Set<Int>) { // var sortedPitchSet = notes.sort({$0.noteNumber < $1.noteNumber}) // if sortedPitchSet.count > 1 { // var pitchSetPermutations = [[Note]]() // pitchSetPermutations.append(sortedPitchSet) // for index in 1..<sortedPitchSet.count { // pitchSetPermutations.append(self.rotatePitchSet(pitchSetPermutations[index - 1])) // } // func compareNormalOrders (pitchSet1: [Note], pitchSet2: [Note]) -> [Note] { // var indexToCheck = sortedPitchSet.count - 1 // // while indexToCheck != 0 { // var checkedPitchSet1 = pitchSet1[indexToCheck].noteNumber - pitchSet1[0].noteNumber // var checkedPitchSet2 = pitchSet2[indexToCheck].noteNumber - pitchSet2[0].noteNumber // checkedPitchSet1 = self.modTwelve(checkedPitchSet1) // checkedPitchSet2 = self.modTwelve(checkedPitchSet2) // if checkedPitchSet1 == checkedPitchSet2 { // if indexToCheck == 1 { // if pitchSet1[0].noteNumber < pitchSet2[0].noteNumber { // return pitchSet1 // } else { // return pitchSet2 // } // } // } // if checkedPitchSet1 < checkedPitchSet2 { // return pitchSet1 // } // if checkedPitchSet1 > checkedPitchSet2 { // return pitchSet2 // } // indexToCheck-- // } // return sortedPitchSet // } // for index in 1..<pitchSetPermutations.count { // sortedPitchSet = compareNormalOrders(sortedPitchSet, pitchSet2: pitchSetPermutations[index]) // } // } // var noteNumbers = Set<Int>() // for note in sortedPitchSet { // noteNumbers.insert(note.noteNumber) // } // return (sortedPitchSet, noteNumbers) //} // //private func transposeByInterval(interval: Int, notes: [Note]) -> [Note] { // for var note in notes { // note.noteNumber = modTwelve(note.noteNumber + interval) // note = self.getNoteFromNumber(note.noteNumber) // } // return notes //} // // //private func rotatePitchSet(notes: [Note]) -> [Note] { // var rotatedPitchSet = notes // if rotatedPitchSet.count > 1 { // rotatedPitchSet.insert(rotatedPitchSet.last!, atIndex: 0) // rotatedPitchSet.removeLast() // } // return rotatedPitchSet //}
7751733271748f862962dbbca7e2b2e0
40.989796
173
0.42017
false
false
false
false
YauheniYarotski/APOD
refs/heads/master
APOD/IAPHelper.swift
mit
1
// // IAPHelper.swift // APOD // // Created by Yauheni Yarotski on 8/17/16. // Copyright © 2016 Yauheni_Yarotski. All rights reserved. // import StoreKit public typealias ProductIdentifier = String public typealias ProductsRequestCompletionHandler = (_ success: Bool, _ products: [SKProduct]?) -> () open class IAPHelper : NSObject { fileprivate let productIdentifiers: Set<ProductIdentifier> fileprivate var purchasedProductIdentifiers = Set<ProductIdentifier>() fileprivate var productsRequest: SKProductsRequest? fileprivate var productsRequestCompletionHandler: ProductsRequestCompletionHandler? static let kIAPHelperPurchaseNotification = "IAPHelperPurchaseNotification" static let kIAPHelperPurchaseFailedNotification = "IAPHelperPurchaseFailedNotification" public init(productIds: Set<ProductIdentifier>) { self.productIdentifiers = productIds for productIdentifier in productIds { let purchased = UserDefaults.standard.bool(forKey: productIdentifier) if purchased { purchasedProductIdentifiers.insert(productIdentifier) print("Previously purchased: \(productIdentifier)") } else { print("Not purchased: \(productIdentifier)") } } super.init() SKPaymentQueue.default().add(self) } } // MARK: - StoreKit API extension IAPHelper { public func requestProducts(_ completionHandler: @escaping ProductsRequestCompletionHandler) { productsRequest?.cancel() productsRequestCompletionHandler = completionHandler productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers) productsRequest!.delegate = self productsRequest!.start() } public func buyProduct(_ product: SKProduct) { print("Buying \(product.productIdentifier)...") let payment = SKPayment(product: product) SKPaymentQueue.default().add(payment) } public func isProductPurchased(_ productIdentifier: ProductIdentifier) -> Bool { return purchasedProductIdentifiers.contains(productIdentifier) } public class func canMakePayments() -> Bool { return true } public func restorePurchases() { SKPaymentQueue.default().restoreCompletedTransactions() } } // MARK: - SKProductsRequestDelegate extension IAPHelper: SKProductsRequestDelegate { public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { let products = response.products productsRequestCompletionHandler?(true, products) clearRequestAndHandler() } public func request(_ request: SKRequest, didFailWithError error: Error) { print("Failed to load list of products.") print("Error: \(error.localizedDescription)") productsRequestCompletionHandler?(false, nil) clearRequestAndHandler() } fileprivate func clearRequestAndHandler() { productsRequest = nil productsRequestCompletionHandler = nil } } // MARK: - SKPaymentTransactionObserver extension IAPHelper: SKPaymentTransactionObserver { public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction in transactions { switch (transaction.transactionState) { case .purchased: completeTransaction(transaction) break case .failed: failedTransaction(transaction) break case .restored: restoreTransaction(transaction) break case .deferred: break case .purchasing: break } } } fileprivate func completeTransaction(_ transaction: SKPaymentTransaction) { print("completeTransaction...") deliverPurchaseNotificatioForIdentifier(transaction.payment.productIdentifier) SKPaymentQueue.default().finishTransaction(transaction) } fileprivate func restoreTransaction(_ transaction: SKPaymentTransaction) { guard let productIdentifier = transaction.original?.payment.productIdentifier else { return } print("restoreTransaction... \(productIdentifier)") deliverPurchaseNotificatioForIdentifier(productIdentifier) SKPaymentQueue.default().finishTransaction(transaction) } fileprivate func failedTransaction(_ transaction: SKPaymentTransaction?) { print("failedTransaction...") if let transaction = transaction { if transaction.error!._code != SKError.paymentCancelled.rawValue { print("Transaction Error: \(transaction.error?.localizedDescription)") } SKPaymentQueue.default().finishTransaction(transaction) } NotificationCenter.default.post(name: Notification.Name(rawValue: IAPHelper.kIAPHelperPurchaseFailedNotification), object: transaction) } fileprivate func deliverPurchaseNotificatioForIdentifier(_ identifier: String?) { guard let identifier = identifier else { return } purchasedProductIdentifiers.insert(identifier) UserDefaults.standard.set(true, forKey: identifier) UserDefaults.standard.synchronize() NotificationCenter.default.post(name: Notification.Name(rawValue: IAPHelper.kIAPHelperPurchaseNotification), object: identifier) } public func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) { failedTransaction(nil) } }
4405747e02323c5b3ebf78fcc11238d1
33.969697
143
0.679549
false
false
false
false
nestorgt/LeetCode-Algorithms-Swift
refs/heads/master
LeetCode-Algorithms/LeetCode-Algorithms/003_LongestSubstringWithoutRepeatingCharacters.swift
mit
1
// // 003_LongestSubstringWithoutRepeatingCharacters.swift // LeetCode-Algorithms // // Created by nestorgt on 14/03/16. // Copyright © 2016 nestorgt. All rights reserved. // /* #3 Longest Substring Without Repeating Characters - Medium - https://leetcode.com/problems/longest-substring-without-repeating-characters/ - QUESTION Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1. - SOLUTION Loop through string and use a hashmap to save positions of caracters already seen. When the new character is in the hashmap and it's in a valid position (startIndex > characterIndex) reset. t = O(N), s = O(1) */ import Foundation struct _003_LongestSubstringWithoutRepeatingCharacters { struct SubstringHelper { var startIndex: Int = 0 var endIndex: Int = 0 var mapper = [Character : Int]() // [char : position] var size: Int { get { return endIndex - startIndex + 1 } } } func lengthOfLongestSubstring(s: String) -> Int { guard s.characters.count > 0 else { return 0 } var longestString: SubstringHelper = SubstringHelper(startIndex: 0, endIndex: 0, mapper: [Character : Int]()) var currentString: SubstringHelper = SubstringHelper(startIndex: 0, endIndex: 0, mapper: [Character : Int]()) var currentIndex = 0 for c in s.characters { if let indexOfChar: Int = currentString.mapper[c] where indexOfChar >= currentString.startIndex { if currentString.size > longestString.size { longestString = currentString } currentString.endIndex = currentIndex currentString.startIndex = indexOfChar + 1 } currentString.mapper[c] = currentIndex currentString.endIndex = currentIndex currentIndex += 1 } if currentString.size > longestString.size { longestString = currentString } return longestString.size } }
89362cc4725011641e500669c46750a6
35.222222
259
0.638755
false
false
false
false
justin/Aspen
refs/heads/master
AspenTests/AspenTests.swift
mit
1
import XCTest @testable import Aspen class AspenTests: AspenTestCase { override func setUp() { super.setUp() super.registerLoggers() } override func tearDown() { super.tearDown() } // MARK: - Verbose mode func testVerbosePasses() { Aspen.setLoggingLevel(.verbose) self.expectLog { aspenVerbose(passVerbose) } self.expectLog { aspenInfo(passInfo) } self.expectLog { aspenWarn(passWarn) } self.expectLog { aspenError(passError) } } // MARK: - Info mode func testInfoPasses() { Aspen.setLoggingLevel(.info) self.expectLog { aspenInfo(passInfo) } self.expectLog { aspenWarn(passWarn) } self.expectLog { aspenError(passError) } } func testInfoFailures() { Aspen.setLoggingLevel(.info) self.expectNoLog { aspenVerbose(failVerbose) } } // MARK: - Warn mode func testWarnPasses() { Aspen.setLoggingLevel(.warning) self.expectLog { aspenWarn(passWarn) } self.expectLog { aspenError(passError) } } func testWarnFailures() { Aspen.setLoggingLevel(.warning) self.expectNoLog { aspenInfo(failInfo) } self.expectNoLog { aspenVerbose(failVerbose) } } // MARK: - Error mode func testErrorPasses() { Aspen.setLoggingLevel(.error) self.expectLog { aspenError(passError) } } func testErrorFailures() { Aspen.setLoggingLevel(.error) self.expectNoLog { aspenVerbose(failVerbose) } self.expectNoLog { aspenInfo(failInfo) } self.expectNoLog { aspenWarn(failWarn) } } } let passVerbose = "Verbose; should pass" let passInfo = "Info; should pass" let passWarn = "Warn; should pass" let passError = "Error; should pass" let failVerbose = "Verbose; should fail" let failInfo = "Info; should fail" let failWarn = "Warn; should fail" let failError = "Error; should fail"
1f3a07f99fdfa1b7b0179ffff37b2279
19.837209
48
0.695871
false
true
false
false
smittytone/FightingFantasy
refs/heads/master
FightingFantasy/FFBookmarkButton.swift
mit
1
// FightingFantasy // Created by Tony Smith on 02/11/2017. // Software © 2017 Tony Smith. All rights reserved. // Software ONLY issued under MIT Licence // Fighting Fantasy © 2016 Steve Jackson and Ian Livingstone import Cocoa class FFBookmarkButton: NSButton { var bookmarkState: Bool = false var trackingArea: NSTrackingArea? = nil override func awakeFromNib() { // When the button is loaded from the nib, set its tracking area so that // mouse movements in and out of the button can be trapped and used to // modify the button image if let trackingArea = self.trackingArea { self.removeTrackingArea(trackingArea) } let options: NSTrackingArea.Options = [.mouseEnteredAndExited, .activeAlways] let trackingArea = NSTrackingArea(rect: self.bounds, options: options, owner: self, userInfo: nil) self.addTrackingArea(trackingArea) } override func mouseEntered(with event: NSEvent) { // Mouse moves over the button, so set the image to a + or a - depending on // whether the bookmark is showing (+ to show bookmark, - to hide it). // 'bookmarkState' says which is which: true for bookmark showing if !bookmarkState { self.image = NSImage.init(named: NSImage.Name("button_blue_on")) } else { self.image = NSImage.init(named: NSImage.Name("button_blue_off")) } super.mouseEntered(with: event) } override func mouseExited(with event: NSEvent) { // Mouse moves away from the button, so set the image to a plain circle self.image = NSImage.init(named: NSImage.Name("button_blue")) super.mouseExited(with: event) } }
53dce189340b1859f1cf0878f6dcbbbd
32.480769
106
0.66054
false
false
false
false
jordane-quincy/M2_DevMobileIos
refs/heads/master
JSONProject/Demo/JsonModel_params.swift
mit
1
// // JsonModel_params.swift // Demo // // Created by MAC ISTV on 26/03/2017. // Copyright © 2017 UVHC. All rights reserved. // import Foundation class Choice: Hashable, CustomStringConvertible { let value: String let label: String var selected: Bool = false init?(jsonContent: [String: Any]) throws { guard let value = jsonContent["value"] as? String else { throw SerializationError.missing("value") } guard let label = jsonContent["label"] as? String else { throw SerializationError.missing("label") } let selected = jsonContent["selected"] as? Bool //assignation self.value = value self.label = label self.selected = selected ?? false } //Hashable var hashValue: Int { return value.hashValue ^ value.hashValue } static func == (c1: Choice, c2: Choice) -> Bool { return c1.value == c2.value } //toString() public var description: String { return "choice(value:'\(value)', label:'\(label)', selected:\(selected) )" } } class Params: CustomStringConvertible { let minLength: Int? let maxLenght: Int? let placeholder: String? let choices: Set<Choice>? init?(jsonContent: [String: Any], inputType: InputType) throws { switch inputType { case .text: var minLength: Int? = nil if (jsonContent["minLength"] != nil) { minLength = jsonContent["minLength"] as? Int } var maxLength: Int? = nil if (jsonContent["maxLength"] != nil) { maxLength = jsonContent["maxLength"] as? Int } var placeholder = "" if (jsonContent["placeholder"] != nil) { placeholder = (jsonContent["placeholder"] as? String)! } //assignation self.minLength = minLength self.maxLenght = maxLength self.placeholder = placeholder self.choices = nil case .radio, .select, .check: // Extract and validate choices guard let choicesJsonArray = jsonContent["choices"] as? [[String: Any]] else { throw SerializationError.missing("choices") } //print("choicesJsonArray : \(choicesJsonArray)")//FIXME: pour debug uniquement var choices: Set<Choice> = [] for choicesJsonElement in choicesJsonArray { //print("choicesJsonElement : \(choicesJsonElement)")//FIXME: pour debug uniquement do { guard let choice = try Choice(jsonContent: choicesJsonElement) else { throw SerializationError.invalid("choices", choicesJsonElement) } choices.insert(choice) } catch let serializationError { print(serializationError) } } //assignation self.choices = choices self.minLength = nil self.maxLenght = nil self.placeholder = nil default: // special case for .date // FIXME: nothing more than initialize to do here because executable line(s) is mandatory self.minLength = nil self.maxLenght = nil self.placeholder = nil self.choices = nil } } //toString() public var description: String { return "Params(minLength:\(minLength), maxLenght:\(maxLenght), placeholder:'\(placeholder)', choices:\(choices) )" } }
6b80143f5c5a134bc75bbb98162821bb
30.705882
153
0.537238
false
false
false
false
honishi/Hakumai
refs/heads/main
Hakumai/Managers/MessageContainer/MessageContainer.swift
mit
1
// // ChatContainer.swift // Hakumai // // Created by Hiroyuki Onishi on 11/26/14. // Copyright (c) 2014 Hiroyuki Onishi. All rights reserved. // import Foundation // thread safe chat container final class MessageContainer { // MARK: - Properties // MARK: Public var enableMuteUserIds = false var muteUserIds = [[String: String]]() var enableMuteWords = false var muteWords = [[String: String]]() var enableEmotionMessage = true var enableDebugMessage = false private(set) var filteredMessages = [Message]() // MARK: Private private var messageNo = 0 private var sourceMessages = [Message]() private var firstChat = [String: Bool]() private var rebuildingFilteredMessages = false private var calculatingActive = false } extension MessageContainer { // MARK: - Basic Operation to Content Array @discardableResult func append(systemMessage: String) -> (appended: Bool, count: Int) { objc_sync_enter(self) defer { objc_sync_exit(self) } let message = Message(messageNo: messageNo, system: systemMessage) return append(message: message) } @discardableResult func append(chat: Chat) -> (appended: Bool, count: Int, message: Message?) { objc_sync_enter(self) defer { objc_sync_exit(self) } let isFirst = chat.premium.isUser && firstChat[chat.userId] == nil if isFirst { firstChat[chat.userId] = true } let message = Message(messageNo: messageNo, chat: chat, isFirst: isFirst) let appendResult = append(message: message) return ( appendResult.appended, appendResult.count, appendResult.appended ? message : nil ) } @discardableResult func append(debug: String) -> (appended: Bool, count: Int) { objc_sync_enter(self) defer { objc_sync_exit(self) } let message = Message(messageNo: messageNo, debug: debug) return append(message: message) } private func append(message: Message) -> (appended: Bool, count: Int) { messageNo += 1 sourceMessages.append(message) let appended = appendIfConditionMet( message: message, into: &filteredMessages) let count = filteredMessages.count return (appended, count) } func count() -> Int { objc_sync_enter(self) let count = filteredMessages.count objc_sync_exit(self) return count } subscript (index: Int) -> Message { objc_sync_enter(self) let content = filteredMessages[index] objc_sync_exit(self) return content } func messages(fromUserId userId: String) -> [Message] { var userMessages = [Message]() objc_sync_enter(self) for message in sourceMessages { switch message.content { case .system, .debug: continue case .chat(let chat): guard chat.userId == userId else { continue } userMessages.append(message) } } objc_sync_exit(self) return userMessages } func removeAll() { objc_sync_enter(self) sourceMessages.removeAll(keepingCapacity: false) filteredMessages.removeAll(keepingCapacity: false) firstChat.removeAll(keepingCapacity: false) messageNo = 0 objc_sync_exit(self) } // MARK: - Utility func calculateActive(completion: @escaping (Int?) -> Void) { if rebuildingFilteredMessages { log.debug("detected rebuilding filtered messages, so skip calculating active.") completion(nil) return } if calculatingActive { log.debug("detected duplicate calculating, so skip calculating active.") completion(nil) return } objc_sync_enter(self) calculatingActive = true objc_sync_exit(self) // log.debug("calcurating active") // swift way to use background gcd, http://stackoverflow.com/a/25070476 DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async { var activeUsers = [String: Bool]() let fiveMinutesAgo = Date(timeIntervalSinceNow: (Double)(-5 * 60)) // log.debug("start counting active") objc_sync_enter(self) let count = self.sourceMessages.count objc_sync_exit(self) var i = count while 0 < i { objc_sync_enter(self) let message = self.sourceMessages[i - 1] objc_sync_exit(self) i -= 1 guard case let .chat(chat) = message.content, chat.isUser else { continue } // is "chat.date < fiveMinutesAgo" ? if chat.date.compare(fiveMinutesAgo) == .orderedAscending { break } activeUsers[chat.userId] = true } // log.debug("end counting active") completion(activeUsers.count) objc_sync_enter(self) self.calculatingActive = false objc_sync_exit(self) } } func rebuildFilteredMessages(completion: @escaping () -> Void) { // 1st pass: // copy and filter source messages. this could be long operation so use background thread DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async { // log.debug("started 1st pass rebuilding filtered messages (bg section)") var workingMessages = [Message]() let sourceCount = self.sourceMessages.count for i in 0..<sourceCount { self.appendIfConditionMet( message: self.sourceMessages[i], into: &workingMessages) } // log.debug("completed 1st pass") // 2nd pass: // we need to replace old filtered messages with new one with the following conditions; // - exclusive to ui updates, so use main thread // - atomic to any other operation like append, count, calcurate and so on, so use objc_sync_enter/exit DispatchQueue.main.async { // log.debug("started 2nd pass rebuilding filtered messages (critical section)") objc_sync_enter(self) self.rebuildingFilteredMessages = true self.filteredMessages = workingMessages // log.debug("copied working messages to filtered messages") let deltaCount = self.sourceMessages.count for i in sourceCount..<deltaCount { self.appendIfConditionMet( message: self.sourceMessages[i], into: &self.filteredMessages) } // log.debug("copied delta messages \(sourceCount)..<\(deltaCount)") self.rebuildingFilteredMessages = false objc_sync_exit(self) // log.debug("completed 2nd pass") log.debug("completed to rebuild filtered messages") completion() } } } } // MARK: - Internal Functions private extension MessageContainer { // MARK: Filtered Message Append Utility @discardableResult func appendIfConditionMet(message: Message, into messages: inout [Message]) -> Bool { var appended = false if shouldAppend(message: message) { messages.append(message) appended = true } return appended } func shouldAppend(message: Message) -> Bool { switch message.content { case .system: return true case .chat(let chat): return shouldAppendByMuteWords(chat) && shouldAppendByUserId(chat) && shouldAppendByEmotion(chat) case .debug: return enableDebugMessage } } func shouldAppendByMuteWords(_ chat: ChatMessage) -> Bool { guard enableMuteWords else { return true } for muteWord in muteWords { if let word = muteWord[MuteUserWordKey.word], chat.comment.lowercased().range(of: word.lowercased()) != nil { return false } } return true } func shouldAppendByUserId(_ chat: ChatMessage) -> Bool { guard enableMuteUserIds else { return true } for muteUserId in muteUserIds where muteUserId[MuteUserIdKey.userId] == chat.userId { return false } return true } func shouldAppendByEmotion(_ chat: ChatMessage) -> Bool { if enableEmotionMessage { return true } let isEmotion = chat.slashCommand == .emotion return !isEmotion } }
ea648b52124db22163539b925c412464
31.478102
115
0.583324
false
false
false
false
alexhillc/AXPhotoViewer
refs/heads/master
Source/Classes/Transition Controller + Animators/AXPhotosTransitionController.swift
mit
1
// // AXPhotosTransitionController.swift // AXPhotoViewer // // Created by Alex Hill on 6/4/17. // Copyright © 2017 Alex Hill. All rights reserved. // import UIKit #if os(iOS) import FLAnimatedImage #elseif os(tvOS) import FLAnimatedImage_tvOS #endif class AXPhotosTransitionController: NSObject, UIViewControllerTransitioningDelegate, AXPhotosTransitionAnimatorDelegate { fileprivate static let supportedModalPresentationStyles: [UIModalPresentationStyle] = [.fullScreen, .currentContext, .custom, .overFullScreen, .overCurrentContext] weak var delegate: AXPhotosTransitionControllerDelegate? /// Custom animator for presentation. fileprivate var presentationAnimator: AXPhotosPresentationAnimator? /// Custom animator for dismissal. fileprivate var dismissalAnimator: AXPhotosDismissalAnimator? /// If this flag is `true`, the transition controller will ignore any user gestures and instead trigger an immediate dismissal. var forceNonInteractiveDismissal = false /// The transition configuration passed in at initialization. The controller uses this object to apply customization to the transition. let transitionInfo: AXTransitionInfo fileprivate var supportsContextualPresentation: Bool { get { return (self.transitionInfo.startingView != nil) } } fileprivate var supportsContextualDismissal: Bool { get { return (self.transitionInfo.endingView != nil) } } fileprivate var supportsInteractiveDismissal: Bool { get { #if os(iOS) return self.transitionInfo.interactiveDismissalEnabled #else return false #endif } } init(transitionInfo: AXTransitionInfo) { self.transitionInfo = transitionInfo super.init() } // MARK: - UIViewControllerTransitioningDelegate public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { var photosViewController: AXPhotosViewController if let dismissed = dismissed as? AXPhotosViewController { photosViewController = dismissed } else if let childViewController = dismissed.children.filter({ $0 is AXPhotosViewController }).first as? AXPhotosViewController { photosViewController = childViewController } else { assertionFailure("Could not find AXPhotosViewController in container's children.") return nil } guard let photo = photosViewController.dataSource.photo(at: photosViewController.currentPhotoIndex) else { return nil } // resolve transitionInfo's endingView self.transitionInfo.resolveEndingViewClosure?(photo, photosViewController.currentPhotoIndex) if !type(of: self).supportedModalPresentationStyles.contains(photosViewController.modalPresentationStyle) { return nil } if !self.supportsContextualDismissal && !self.supportsInteractiveDismissal { return nil } self.dismissalAnimator = self.dismissalAnimator ?? AXPhotosDismissalAnimator(transitionInfo: self.transitionInfo) self.dismissalAnimator?.delegate = self return self.dismissalAnimator } public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { var photosViewController: AXPhotosViewController if let presented = presented as? AXPhotosViewController { photosViewController = presented } else if let childViewController = presented.children.filter({ $0 is AXPhotosViewController }).first as? AXPhotosViewController { photosViewController = childViewController } else { assertionFailure("Could not find AXPhotosViewController in container's children.") return nil } if !type(of: self).supportedModalPresentationStyles.contains(photosViewController.modalPresentationStyle) { return nil } if !self.supportsContextualPresentation { return nil } self.presentationAnimator = AXPhotosPresentationAnimator(transitionInfo: self.transitionInfo) self.presentationAnimator?.delegate = self return self.presentationAnimator } public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { if !self.supportsInteractiveDismissal || self.forceNonInteractiveDismissal { return nil } self.dismissalAnimator = self.dismissalAnimator ?? AXPhotosDismissalAnimator(transitionInfo: self.transitionInfo) self.dismissalAnimator?.delegate = self return self.dismissalAnimator } #if os(iOS) // MARK: - Interaction handling public func didPanWithGestureRecognizer(_ sender: UIPanGestureRecognizer, in viewController: UIViewController) { self.dismissalAnimator?.didPanWithGestureRecognizer(sender, in: viewController) } #endif // MARK: - AXPhotosTransitionAnimatorDelegate func transitionAnimator(_ animator: AXPhotosTransitionAnimator, didCompletePresentationWith transitionView: UIImageView) { self.delegate?.transitionController(self, didCompletePresentationWith: transitionView) self.presentationAnimator = nil } func transitionAnimator(_ animator: AXPhotosTransitionAnimator, didCompleteDismissalWith transitionView: UIImageView) { self.delegate?.transitionController(self, didCompleteDismissalWith: transitionView) self.dismissalAnimator = nil } func transitionAnimatorDidCancelDismissal(_ animator: AXPhotosTransitionAnimator) { self.delegate?.transitionControllerDidCancelDismissal(self) self.dismissalAnimator = nil } } protocol AXPhotosTransitionControllerDelegate: class { func transitionController(_ transitionController: AXPhotosTransitionController, didCompletePresentationWith transitionView: UIImageView) func transitionController(_ transitionController: AXPhotosTransitionController, didCompleteDismissalWith transitionView: UIImageView) func transitionControllerDidCancelDismissal(_ transitionController: AXPhotosTransitionController) }
48b185cbb18a083ff09097dbe500fc0b
41.50303
151
0.673036
false
false
false
false
JSTPMobile/iOS
refs/heads/master
Sources/Shared/Core/Errors.swift
mit
1
// // Errors.swift // JSTP // // Created by Andrew Visotskyy on 7/25/16. // Copyright © 2016-2017 Andrew Visotskyy. All rights reserved. // public class ConnectionError: Error, LocalizedError, CustomNSError, CustomStringConvertible { public typealias Code = Int public typealias ErrorType = ConnectionErrorType public init(type: ErrorType, description: String? = nil) { self.type = type self.code = type.rawValue self.errorDescription = description ?? ConnectionError.defaultMessages[type.rawValue] } public init(code: Int, description: String? = nil) { self.code = code self.type = ErrorType(rawValue: code) self.errorDescription = description ?? ConnectionError.defaultMessages[code] } public convenience init?(with object: Value?) { guard let data = object as? [Value], let code = data[0] as? Int else { return nil } self.init(code: code, description: data[safe: 1] as? String) } // MARK: - public let code: Code public let type: ErrorType? public let errorDescription: String? internal var asObject: Value { return ["code": code, "message": localizedDescription] } // MARK: - private static let defaultMessages = [ 10: "Application not found", 11: "Authentication failed", 12: "Interface not found", 13: "Incompatible interface", 14: "Method not found", 15: "Not a server", 16: "Internal API error", 17: "Invalid signature" ] // MARK: - CustomNSError public static var errorDomain: String { return "com.gagnant.jstp" } public var errorCode: Int { return self.code } // MARK: - CustomStringConvertible public var description: String { return localizedDescription } } public enum ConnectionErrorType: Int { case appNotFound = 10 case authFailed = 11 case interfaceNotFound = 12 case interfaceIncompatible = 13 case methodNotFound = 14 case notSerever = 15 case internalError = 16 case invalidSignature = 17 }
e2fb0ab7720b98edf831eb6a39d0a5c3
21.833333
93
0.711679
false
false
false
false
qasim/CDFLabs
refs/heads/master
CDFLabs/Printers/PrintersViewController.swift
mit
1
// // PrintersViewController.swift // CDFLabs // // Created by Qasim Iqbal on 12/28/15. // Copyright © 2015 Qasim Iqbal. All rights reserved. // import UIKit import Just class PrintersViewController: UINavigationController, UITableViewDelegate, UITableViewDataSource { var contentViewController: UIViewController? var refreshControl: UIRefreshControl? var refreshButton: UIBarButtonItem? var printerData: [Printer] = [] var tableView: UITableView? override func loadView() { super.loadView() self.printerData = [ Printer(name: "P2210a", description: "Kyocera Network Printer in BA2210", jobs: [ PrintJob(owner: "g5vicli@", rank: "done", size: "431613", time: "12:52:41"), PrintJob(owner: "g4joe@", rank: "stalled", size: "139434", time: "13:02:38"), PrintJob(owner: "g2juan@", rank: "2", size: "1841531", time: "15:39:36"), PrintJob(owner: "g2juan@", rank: "3", size: "1956348", time: "15:39:37"), PrintJob(owner: "g3mary@", rank: "4", size: "223422", time: "15:42:54"), PrintJob(owner: "g3mary@", rank: "5", size: "221583", time: "15:42:54"), PrintJob(owner: "g3mary@", rank: "6", size: "518310", time: "15:42:55"), PrintJob(owner: "g5seung@", rank: "7", size: "960694", time: "15:43:02"), PrintJob(owner: "g5seung@", rank: "8", size: "1199044", time: "15:43:02"), PrintJob(owner: "g5seung@", rank: "9", size: "1547443", time: "15:43:02"), PrintJob(owner: "g5seung@", rank: "10", size: "1649745", time: "15:43:03"), PrintJob(owner: "g5seung@", rank: "11", size: "1405074", time: "15:43:03") ]), Printer(name: "P2210b", description: "Kyocera Network Printer in BA2210", jobs: [ PrintJob(owner: "g5wan@", rank: "done", size: "223422", time: "14:02:26"), PrintJob(owner: "g3jill@", rank: "active", size: "377822", time: "14:03:13"), PrintJob(owner: "g3anna@", rank: "2", size: "247763", time: "14:03:38"), PrintJob(owner: "g3anna@", rank: "3", size: "266874", time: "14:03:38"), PrintJob(owner: "g3anna@", rank: "4", size: "221583", time: "14:03:38"), PrintJob(owner: "g5nagee@", rank: "5", size: "1183837", time: "14:06:12") ]), Printer(name: "P3185a", description: "Redirected to P3175a in BA3175", jobs: [ PrintJob(owner: "g5q@", rank: "done", size: "853311", time: "12:07:32") ]), Printer(name: "P3175a", description: "Kyocera Network Printer in BA3175", jobs: [ PrintJob(owner: "g5q@", rank: "done", size: "853311", time: "12:07:32") ]) ] self.loadContentView() self.pushViewController(contentViewController!, animated: false) self.refreshButton = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: #selector(self.refresh as Void -> Void)) self.contentViewController!.navigationItem.rightBarButtonItem = self.refreshButton! /* let infoButton = UIButton(type: .InfoLight) infoButton.tintColor = UIColor.whiteColor() infoButton.addTarget(self, action: #selector(self.info), forControlEvents: .TouchUpInside) let infoBarButton = UIBarButtonItem(customView: infoButton) self.contentViewController!.navigationItem.leftBarButtonItem = infoBarButton */ // self.refresh() if NSUserDefaults.standardUserDefaults().isFirstPrintersLaunch() { PopupView.showFirstPrintersLaunchPopup() } } func loadContentView() { self.contentViewController = UIViewController() self.contentViewController!.title = "Printers" let contentView = self.contentViewController!.view self.loadTableView() contentView.addSubview(self.tableView!) let viewsDict: [String: AnyObject] = [ "tableView": self.tableView! ] let options = NSLayoutFormatOptions(rawValue: 0) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat( "|[tableView]|", options: options, metrics: nil, views: viewsDict)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat( "V:|[tableView]|", options: options, metrics: nil, views: viewsDict)) } func loadTableView() { self.tableView = CLTableView() self.tableView?.estimatedRowHeight = CLTable.printerCellHeight self.tableView?.rowHeight = UITableViewAutomaticDimension self.tableView?.delegate = self self.tableView?.dataSource = self self.refreshControl = UIRefreshControl() self.refreshControl?.addTarget(self, action: #selector(self.refresh(_:) as UIRefreshControl -> Void), forControlEvents: .ValueChanged) self.tableView?.addSubview(refreshControl!) self.tableView?.reloadData() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return printerData.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return PrinterTableViewCell(printer: self.printerData[indexPath.row]) } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let printerViewController = PrinterViewController(printer: self.printerData[indexPath.row], row: indexPath.row) self.pushViewController(printerViewController, animated: true) } func refresh() { self.tableView?.setContentOffset(CGPointMake(0, self.tableView!.contentOffset.y - self.refreshControl!.frame.size.height), animated: true) self.refreshControl!.beginRefreshing() self.refresh(self.refreshControl!) } func refresh(refreshControl: UIRefreshControl) { Just.get("http://www.cdf.toronto.edu/~g3cheunh/cdfprinters.json") { (r) in if r.ok { if let json = r.json as? [String:AnyObject] { self.printerData = [] let printers = json["printers"] as! [[String:AnyObject]] for printer in printers { var name = printer["name"] as! String name = name.titleCaseString let rawJobs = printer["jobs"] as! [[String:String]] var jobs: [PrintJob] = [] for job in rawJobs { jobs.append(PrintJob( owner: job["owner"]!, rank: job["rank"]!, size: job["size"]!, time: job["time"]!)) } let description = printer["description"] as! String let printer = Printer(name: name, description: description, jobs: jobs) self.printerData.append(printer) } } } CATransaction.begin() CATransaction.setCompletionBlock({ self.tableView?.reloadData() }) refreshControl.endRefreshing() CATransaction.commit() } } func refresh(row: Int) -> [PrintJob] { self.refresh(self.refreshControl!) return self.printerData[row].jobs } }
82df213936cc9c1b5132e902d4d26b47
43.423077
146
0.550402
false
false
false
false
937447974/YJCocoa
refs/heads/master
YJCocoa/Classes/System/Dispatch/YJDispatchQueue.swift
mit
1
// // YJDispatchQueue.swift // YJCocoa // // HomePage:https://github.com/937447974/YJCocoa // YJ技术支持群:557445088 // // Created by 阳君 on 2019/5/30. // Copyright © 2016-现在 YJCocoa. All rights reserved. // import UIKit public typealias YJDispatchWork = () -> Void public extension DispatchQueue { // MARK: main queue /// main queue 同步执行 class func syncMain(_ work: @escaping YJDispatchWork) { if pthread_main_np() == 0 { DispatchQueue.main.sync(execute: work) } else { work() } } /// main queue 异步执行 class func asyncMain(_ work: @escaping YJDispatchWork) { DispatchQueue.main.async(execute: work) } /// main queue 延时执行 class func afterMain(delayInSeconds: TimeInterval, execute work: @escaping YJDispatchWork) { DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds, execute: work) } // MARK: default queue /// default queue 异步执行 class func asyncDefault(_ work: @escaping YJDispatchWork) { DispatchQueue.global(qos: .default).async(execute: work) } /// default queue 延时执行 class func afterDefault(delayInSeconds: TimeInterval, execute work: @escaping YJDispatchWork) { DispatchQueue.global(qos: .default).asyncAfter(deadline: .now() + delayInSeconds, execute: work) } /// background queue 异步执行 class func asyncBackground(_ work: @escaping YJDispatchWork) { DispatchQueue.global(qos: .background).async(execute: work) } /// serial queue 异步执行 class func asyncSerial(_ work: @escaping YJDispatchWork) { YJDispatchQueue.serial.async(work) } /// concurrent queue 异步执行 class func asyncConcurrent(_ work: @escaping YJDispatchWork) { YJDispatchQueue.concurrent.async(work) } } /// 调度队列 @objcMembers open class YJDispatchQueue: NSObject { var queue: DispatchQueue! var semaphore: DispatchSemaphore! let key = DispatchSpecificKey<String>() /// 串行 public static var serial: YJDispatchQueue = { let queue = DispatchQueue(label: "com.yjcocoa.serial") return YJDispatchQueue(queue: queue, maxConcurrent: 1) }() /// 并行 public static var concurrent: YJDispatchQueue = { let queue = DispatchQueue(label: "com.yjcocoa.concurrent", attributes: DispatchQueue.Attributes.concurrent) return YJDispatchQueue(queue: queue, maxConcurrent: 16) }() /** * init * - Parameter queue: 队列 * - Parameter maxConcurrent: 最大并发数 */ public init(queue: DispatchQueue, maxConcurrent: Int) { self.queue = queue self.semaphore = DispatchSemaphore(value: maxConcurrent) self.queue.setSpecific(key: self.key, value: "yj.dispatch.queue") } /// 同步执行 public func sync(_ work: @escaping YJDispatchWork) { self.execute(async: false, work: work) } /// 异步执行 public func async(_ work: @escaping YJDispatchWork) { self.execute(async: true, work: work) } private func execute(async: Bool, work: @escaping YJDispatchWork) { let semaphoreWork = {[weak self] in self?.semaphore.wait() work(); self?.semaphore.signal() } if DispatchQueue.getSpecific(key: self.key) != nil { work(); } else if async { self.queue.async(execute: semaphoreWork) } else { self.queue.sync(execute: semaphoreWork) } } }
58d429747e85d8c3b55027d4fdeb67c8
28.032787
115
0.623659
false
false
false
false
sonnygauran/trailer
refs/heads/master
Trailer/PreferencesWindow.swift
mit
1
import Foundation final class PreferencesWindow : NSWindow, NSWindowDelegate, NSTableViewDelegate, NSTableViewDataSource, NSTabViewDelegate { // Preferences window @IBOutlet weak var refreshButton: NSButton! @IBOutlet weak var activityDisplay: NSProgressIndicator! @IBOutlet weak var projectsTable: NSTableView! @IBOutlet weak var versionNumber: NSTextField! @IBOutlet weak var launchAtStartup: NSButton! @IBOutlet weak var refreshDurationLabel: NSTextField! @IBOutlet weak var refreshDurationStepper: NSStepper! @IBOutlet weak var hideUncommentedPrs: NSButton! @IBOutlet weak var repoFilter: NSTextField! @IBOutlet weak var showAllComments: NSButton! @IBOutlet weak var sortingOrder: NSButton! @IBOutlet weak var sortModeSelect: NSPopUpButton! @IBOutlet weak var showCreationDates: NSButton! @IBOutlet weak var dontKeepPrsMergedByMe: NSButton! @IBOutlet weak var hideAvatars: NSButton! @IBOutlet weak var dontConfirmRemoveAllMerged: NSButton! @IBOutlet weak var dontConfirmRemoveAllClosed: NSButton! @IBOutlet weak var displayRepositoryNames: NSButton! @IBOutlet weak var includeRepositoriesInFiltering: NSButton! @IBOutlet weak var groupByRepo: NSButton! @IBOutlet weak var markUnmergeableOnUserSectionsOnly: NSButton! @IBOutlet weak var repoCheckLabel: NSTextField! @IBOutlet weak var repoCheckStepper: NSStepper! @IBOutlet weak var countOnlyListedItems: NSButton! @IBOutlet weak var prMergedPolicy: NSPopUpButton! @IBOutlet weak var prClosedPolicy: NSPopUpButton! @IBOutlet weak var checkForUpdatesAutomatically: NSButton! @IBOutlet weak var checkForUpdatesLabel: NSTextField! @IBOutlet weak var checkForUpdatesSelector: NSStepper! @IBOutlet weak var openPrAtFirstUnreadComment: NSButton! @IBOutlet weak var logActivityToConsole: NSButton! @IBOutlet weak var commentAuthorBlacklist: NSTokenField! // Statuses @IBOutlet weak var showStatusItems: NSButton! @IBOutlet weak var makeStatusItemsSelectable: NSButton! @IBOutlet weak var statusItemRescanLabel: NSTextField! @IBOutlet weak var statusItemRefreshCounter: NSStepper! @IBOutlet weak var statusItemsRefreshNote: NSTextField! @IBOutlet weak var notifyOnStatusUpdates: NSButton! @IBOutlet weak var notifyOnStatusUpdatesForAllPrs: NSButton! @IBOutlet weak var statusTermMenu: NSPopUpButton! @IBOutlet weak var statusTermsField: NSTokenField! // Comments @IBOutlet weak var disableAllCommentNotifications: NSButton! @IBOutlet weak var autoParticipateOnTeamMentions: NSButton! @IBOutlet weak var autoParticipateWhenMentioned: NSButton! // Display @IBOutlet weak var useVibrancy: NSButton! @IBOutlet weak var includeLabelsInFiltering: NSButton! @IBOutlet weak var includeTitlesInFiltering: NSButton! @IBOutlet weak var includeStatusesInFiltering: NSButton! @IBOutlet weak var grayOutWhenRefreshing: NSButton! @IBOutlet weak var assignedPrHandlingPolicy: NSPopUpButton! @IBOutlet weak var includeServersInFiltering: NSButton! @IBOutlet weak var includeUsersInFiltering: NSButton! // Labels @IBOutlet weak var labelRescanLabel: NSTextField! @IBOutlet weak var labelRefreshNote: NSTextField! @IBOutlet weak var labelRefreshCounter: NSStepper! @IBOutlet weak var showLabels: NSButton! // Servers @IBOutlet weak var serverList: NSTableView! @IBOutlet weak var apiServerName: NSTextField! @IBOutlet weak var apiServerApiPath: NSTextField! @IBOutlet weak var apiServerWebPath: NSTextField! @IBOutlet weak var apiServerAuthToken: NSTextField! @IBOutlet weak var apiServerSelectedBox: NSBox! @IBOutlet weak var apiServerTestButton: NSButton! @IBOutlet weak var apiServerDeleteButton: NSButton! @IBOutlet weak var apiServerReportError: NSButton! // Misc @IBOutlet weak var repeatLastExportAutomatically: NSButton! @IBOutlet weak var lastExportReport: NSTextField! @IBOutlet weak var dumpApiResponsesToConsole: NSButton! // Keyboard @IBOutlet weak var hotkeyEnable: NSButton! @IBOutlet weak var hotkeyCommandModifier: NSButton! @IBOutlet weak var hotkeyOptionModifier: NSButton! @IBOutlet weak var hotkeyShiftModifier: NSButton! @IBOutlet weak var hotkeyLetter: NSPopUpButton! @IBOutlet weak var hotKeyHelp: NSTextField! @IBOutlet weak var hotKeyContainer: NSBox! @IBOutlet weak var hotkeyControlModifier: NSButton! // Repos @IBOutlet weak var allPrsSetting: NSPopUpButton! @IBOutlet weak var allIssuesSetting: NSPopUpButton! @IBOutlet weak var allNewPrsSetting: NSPopUpButton! @IBOutlet weak var allNewIssuesSetting: NSPopUpButton! // Tabs @IBOutlet weak var tabs: NSTabView! override init(contentRect: NSRect, styleMask aStyle: Int, backing bufferingType: NSBackingStoreType, `defer` flag: Bool) { super.init(contentRect: contentRect, styleMask: aStyle, backing: bufferingType, `defer`: flag) } override func awakeFromNib() { super.awakeFromNib() delegate = self updateAllItemSettingButtons() allNewPrsSetting.addItemsWithTitles(RepoDisplayPolicy.labels) allNewIssuesSetting.addItemsWithTitles(RepoDisplayPolicy.labels) reloadSettings() versionNumber.stringValue = versionString() let selectedIndex = min(tabs.numberOfTabViewItems-1, Settings.lastPreferencesTabSelectedOSX) tabs.selectTabViewItem(tabs.tabViewItemAtIndex(selectedIndex)) let n = NSNotificationCenter.defaultCenter() n.addObserver(serverList, selector: Selector("reloadData"), name: API_USAGE_UPDATE, object: nil) n.addObserver(self, selector: Selector("updateImportExportSettings"), name: SETTINGS_EXPORTED, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(serverList) NSNotificationCenter.defaultCenter().removeObserver(self) } private func updateAllItemSettingButtons() { allPrsSetting.removeAllItems() allIssuesSetting.removeAllItems() let rowCount = projectsTable.selectedRowIndexes.count if rowCount > 1 { allPrsSetting.addItemWithTitle("Set selected PRs...") allIssuesSetting.addItemWithTitle("Set selected issues...") } else { allPrsSetting.addItemWithTitle("Set all PRs...") allIssuesSetting.addItemWithTitle("Set all issues...") } allPrsSetting.addItemsWithTitles(RepoDisplayPolicy.labels) allIssuesSetting.addItemsWithTitles(RepoDisplayPolicy.labels) } func reloadSettings() { serverList.selectRowIndexes(NSIndexSet(index: 0), byExtendingSelection: false) fillServerApiFormFromSelectedServer() api.updateLimitsFromServer() updateStatusTermPreferenceControls() commentAuthorBlacklist.objectValue = Settings.commentAuthorBlacklist setupSortMethodMenu() sortModeSelect.selectItemAtIndex(Settings.sortMethod) prMergedPolicy.selectItemAtIndex(Settings.mergeHandlingPolicy) prClosedPolicy.selectItemAtIndex(Settings.closeHandlingPolicy) launchAtStartup.integerValue = StartupLaunch.isAppLoginItem() ? 1 : 0 dontConfirmRemoveAllClosed.integerValue = Settings.dontAskBeforeWipingClosed ? 1 : 0 displayRepositoryNames.integerValue = Settings.showReposInName ? 1 : 0 includeRepositoriesInFiltering.integerValue = Settings.includeReposInFilter ? 1 : 0 includeLabelsInFiltering.integerValue = Settings.includeLabelsInFilter ? 1 : 0 includeTitlesInFiltering.integerValue = Settings.includeTitlesInFilter ? 1 : 0 includeUsersInFiltering.integerValue = Settings.includeUsersInFilter ? 1 : 0 includeServersInFiltering.integerValue = Settings.includeServersInFilter ? 1 : 0 includeStatusesInFiltering.integerValue = Settings.includeStatusesInFilter ? 1 : 0 dontConfirmRemoveAllMerged.integerValue = Settings.dontAskBeforeWipingMerged ? 1 : 0 hideUncommentedPrs.integerValue = Settings.hideUncommentedItems ? 1 : 0 autoParticipateWhenMentioned.integerValue = Settings.autoParticipateInMentions ? 1 : 0 autoParticipateOnTeamMentions.integerValue = Settings.autoParticipateOnTeamMentions ? 1 : 0 hideAvatars.integerValue = Settings.hideAvatars ? 1 : 0 dontKeepPrsMergedByMe.integerValue = Settings.dontKeepPrsMergedByMe ? 1 : 0 grayOutWhenRefreshing.integerValue = Settings.grayOutWhenRefreshing ? 1 : 0 notifyOnStatusUpdates.integerValue = Settings.notifyOnStatusUpdates ? 1 : 0 notifyOnStatusUpdatesForAllPrs.integerValue = Settings.notifyOnStatusUpdatesForAllPrs ? 1 : 0 disableAllCommentNotifications.integerValue = Settings.disableAllCommentNotifications ? 1 : 0 showAllComments.integerValue = Settings.showCommentsEverywhere ? 1 : 0 sortingOrder.integerValue = Settings.sortDescending ? 1 : 0 showCreationDates.integerValue = Settings.showCreatedInsteadOfUpdated ? 1 : 0 groupByRepo.integerValue = Settings.groupByRepo ? 1 : 0 assignedPrHandlingPolicy.selectItemAtIndex(Settings.assignedPrHandlingPolicy) showStatusItems.integerValue = Settings.showStatusItems ? 1 : 0 makeStatusItemsSelectable.integerValue = Settings.makeStatusItemsSelectable ? 1 : 0 markUnmergeableOnUserSectionsOnly.integerValue = Settings.markUnmergeableOnUserSectionsOnly ? 1 : 0 countOnlyListedItems.integerValue = Settings.countOnlyListedItems ? 0 : 1 openPrAtFirstUnreadComment.integerValue = Settings.openPrAtFirstUnreadComment ? 1 : 0 logActivityToConsole.integerValue = Settings.logActivityToConsole ? 1 : 0 dumpApiResponsesToConsole.integerValue = Settings.dumpAPIResponsesInConsole ? 1 : 0 showLabels.integerValue = Settings.showLabels ? 1 : 0 useVibrancy.integerValue = Settings.useVibrancy ? 1 : 0 allNewPrsSetting.selectItemAtIndex(Settings.displayPolicyForNewPrs) allNewIssuesSetting.selectItemAtIndex(Settings.displayPolicyForNewIssues) hotkeyEnable.integerValue = Settings.hotkeyEnable ? 1 : 0 hotkeyControlModifier.integerValue = Settings.hotkeyControlModifier ? 1 : 0 hotkeyCommandModifier.integerValue = Settings.hotkeyCommandModifier ? 1 : 0 hotkeyOptionModifier.integerValue = Settings.hotkeyOptionModifier ? 1 : 0 hotkeyShiftModifier.integerValue = Settings.hotkeyShiftModifier ? 1 : 0 enableHotkeySegments() hotkeyLetter.addItemsWithTitles(["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]) hotkeyLetter.selectItemWithTitle(Settings.hotkeyLetter) refreshUpdatePreferences() updateStatusItemsOptions() updateLabelOptions() hotkeyEnable.enabled = true repoCheckStepper.floatValue = Settings.newRepoCheckPeriod newRepoCheckChanged(nil) refreshDurationStepper.floatValue = min(Settings.refreshPeriod, 3600) refreshDurationChanged(nil) updateImportExportSettings() updateActivity() } func updateActivity() { if app.isRefreshing { refreshButton.enabled = false projectsTable.enabled = false allPrsSetting.enabled = false allIssuesSetting.enabled = false activityDisplay.startAnimation(nil) } else { refreshButton.enabled = ApiServer.someServersHaveAuthTokensInMoc(mainObjectContext) projectsTable.enabled = true allPrsSetting.enabled = true allIssuesSetting.enabled = true activityDisplay.stopAnimation(nil) } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @IBAction func showLabelsSelected(sender: NSButton) { Settings.showLabels = (sender.integerValue==1) app.deferredUpdateTimer.push() updateLabelOptions() api.resetAllLabelChecks() if Settings.showLabels { ApiServer.resetSyncOfEverything() } } @IBAction func dontConfirmRemoveAllMergedSelected(sender: NSButton) { Settings.dontAskBeforeWipingMerged = (sender.integerValue==1) } @IBAction func markUnmergeableOnUserSectionsOnlySelected(sender: NSButton) { Settings.markUnmergeableOnUserSectionsOnly = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func displayRepositoryNameSelected(sender: NSButton) { Settings.showReposInName = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func useVibrancySelected(sender: NSButton) { Settings.useVibrancy = (sender.integerValue==1) app.prMenu.updateVibrancy() app.issuesMenu.updateVibrancy() } @IBAction func logActivityToConsoleSelected(sender: NSButton) { Settings.logActivityToConsole = (sender.integerValue==1) logActivityToConsole.integerValue = Settings.logActivityToConsole ? 1 : 0 if Settings.logActivityToConsole { let alert = NSAlert() alert.messageText = "Warning" #if DEBUG alert.informativeText = "Sorry, logging is always active in development versions" #else alert.informativeText = "Logging is a feature meant for error reporting, having it constantly enabled will cause this app to be less responsive, use more power, and constitute a security risk" #endif alert.addButtonWithTitle("OK") alert.beginSheetModalForWindow(self, completionHandler: nil) } } @IBAction func dumpApiResponsesToConsoleSelected(sender: NSButton) { Settings.dumpAPIResponsesInConsole = (sender.integerValue==1) if Settings.dumpAPIResponsesInConsole { let alert = NSAlert() alert.messageText = "Warning" alert.informativeText = "This is a feature meant for error reporting, having it constantly enabled will cause this app to be less responsive, use more power, and constitute a security risk" alert.addButtonWithTitle("OK") alert.beginSheetModalForWindow(self, completionHandler: nil) } } @IBAction func includeServersInFilteringSelected(sender: NSButton) { Settings.includeServersInFilter = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func includeUsersInFilteringSelected(sender: NSButton) { Settings.includeUsersInFilter = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func includeLabelsInFilteringSelected(sender: NSButton) { Settings.includeLabelsInFilter = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func includeStatusesInFilteringSelected(sender: NSButton) { Settings.includeStatusesInFilter = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func includeTitlesInFilteringSelected(sender: NSButton) { Settings.includeTitlesInFilter = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func includeRepositoriesInfilterSelected(sender: NSButton) { Settings.includeReposInFilter = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func dontConfirmRemoveAllClosedSelected(sender: NSButton) { Settings.dontAskBeforeWipingClosed = (sender.integerValue==1) } @IBAction func autoParticipateOnMentionSelected(sender: NSButton) { Settings.autoParticipateInMentions = (sender.integerValue==1) DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func autoParticipateOnTeamMentionSelected(sender: NSButton) { Settings.autoParticipateOnTeamMentions = (sender.integerValue==1) DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func dontKeepMyPrsSelected(sender: NSButton) { Settings.dontKeepPrsMergedByMe = (sender.integerValue==1) } @IBAction func grayOutWhenRefreshingSelected(sender: NSButton) { Settings.grayOutWhenRefreshing = (sender.integerValue==1) } @IBAction func disableAllCommentNotificationsSelected(sender: NSButton) { Settings.disableAllCommentNotifications = (sender.integerValue==1) } @IBAction func notifyOnStatusUpdatesSelected(sender: NSButton) { Settings.notifyOnStatusUpdates = (sender.integerValue==1) } @IBAction func notifyOnStatusUpdatesOnAllPrsSelected(sender: NSButton) { Settings.notifyOnStatusUpdatesForAllPrs = (sender.integerValue==1) } @IBAction func hideAvatarsSelected(sender: NSButton) { Settings.hideAvatars = (sender.integerValue==1) DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } private func affectedReposFromSelection() -> [Repo] { let selectedRows = projectsTable.selectedRowIndexes var affectedRepos = [Repo]() if selectedRows.count > 1 { for row in selectedRows { if !tableView(projectsTable, isGroupRow: row) { affectedRepos.append(repoForRow(row)) } } } else { affectedRepos = Repo.reposForFilter(repoFilter.stringValue) } return affectedRepos } @IBAction func allPrsPolicySelected(sender: NSPopUpButton) { let index = sender.indexOfSelectedItem - 1 if index < 0 { return } for r in affectedReposFromSelection() { r.displayPolicyForPrs = index if index != RepoDisplayPolicy.Hide.rawValue { r.resetSyncState() } } projectsTable.reloadData() sender.selectItemAtIndex(0) updateDisplayIssuesSetting() } @IBAction func allIssuesPolicySelected(sender: NSPopUpButton) { let index = sender.indexOfSelectedItem - 1 if index < 0 { return } for r in affectedReposFromSelection() { r.displayPolicyForIssues = index if index != RepoDisplayPolicy.Hide.rawValue { r.resetSyncState() } } projectsTable.reloadData() sender.selectItemAtIndex(0) updateDisplayIssuesSetting() } private func updateDisplayIssuesSetting() { DataManager.postProcessAllItems() app.preferencesDirty = true app.deferredUpdateTimer.push() DataManager.saveDB() Settings.possibleExport(nil) } @IBAction func allNewPrsPolicySelected(sender: NSPopUpButton) { Settings.displayPolicyForNewPrs = sender.indexOfSelectedItem } @IBAction func allNewIssuesPolicySelected(sender: NSPopUpButton) { Settings.displayPolicyForNewIssues = sender.indexOfSelectedItem } @IBAction func hideUncommentedRequestsSelected(sender: NSButton) { Settings.hideUncommentedItems = (sender.integerValue==1) DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func showAllCommentsSelected(sender: NSButton) { Settings.showCommentsEverywhere = (sender.integerValue==1) DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func sortOrderSelected(sender: NSButton) { Settings.sortDescending = (sender.integerValue==1) setupSortMethodMenu() DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func countOnlyListedItemsSelected(sender: NSButton) { Settings.countOnlyListedItems = (sender.integerValue==0) DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func openPrAtFirstUnreadCommentSelected(sender: NSButton) { Settings.openPrAtFirstUnreadComment = (sender.integerValue==1) } @IBAction func sortMethodChanged(sender: AnyObject) { Settings.sortMethod = sortModeSelect.indexOfSelectedItem DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func showStatusItemsSelected(sender: NSButton) { Settings.showStatusItems = (sender.integerValue==1) app.deferredUpdateTimer.push() updateStatusItemsOptions() api.resetAllStatusChecks() if Settings.showStatusItems { ApiServer.resetSyncOfEverything() } } private func setupSortMethodMenu() { let m = NSMenu(title: "Sorting") if Settings.sortDescending { m.addItemWithTitle("Youngest First", action: Selector("sortMethodChanged:"), keyEquivalent: "") m.addItemWithTitle("Most Recently Active", action: Selector("sortMethodChanged:"), keyEquivalent: "") m.addItemWithTitle("Reverse Alphabetically", action: Selector("sortMethodChanged:"), keyEquivalent: "") } else { m.addItemWithTitle("Oldest First", action: Selector("sortMethodChanged:"), keyEquivalent: "") m.addItemWithTitle("Inactive For Longest", action: Selector("sortMethodChanged:"), keyEquivalent: "") m.addItemWithTitle("Alphabetically", action: Selector("sortMethodChanged:"), keyEquivalent: "") } sortModeSelect.menu = m sortModeSelect.selectItemAtIndex(Settings.sortMethod) } private func updateStatusItemsOptions() { let enable = Settings.showStatusItems makeStatusItemsSelectable.enabled = enable notifyOnStatusUpdates.enabled = enable notifyOnStatusUpdatesForAllPrs.enabled = enable statusTermMenu.enabled = enable statusTermsField.enabled = enable statusItemRefreshCounter.enabled = enable statusItemRescanLabel.alphaValue = enable ? 1.0 : 0.5 statusItemsRefreshNote.alphaValue = enable ? 1.0 : 0.5 let count = Settings.statusItemRefreshInterval statusItemRefreshCounter.integerValue = count statusItemRescanLabel.stringValue = count>1 ? "...and re-scan once every \(count) refreshes" : "...and re-scan on every refresh" } private func updateLabelOptions() { let enable = Settings.showLabels labelRefreshCounter.enabled = enable labelRescanLabel.alphaValue = enable ? 1.0 : 0.5 labelRefreshNote.alphaValue = enable ? 1.0 : 0.5 let count = Settings.labelRefreshInterval labelRefreshCounter.integerValue = count labelRescanLabel.stringValue = count>1 ? "...and re-scan once every \(count) refreshes" : "...and re-scan on every refresh" } @IBAction func labelRefreshCounterChanged(sender: NSStepper) { Settings.labelRefreshInterval = labelRefreshCounter.integerValue updateLabelOptions() } @IBAction func statusItemRefreshCountChanged(sender: NSStepper) { Settings.statusItemRefreshInterval = statusItemRefreshCounter.integerValue updateStatusItemsOptions() } @IBAction func makeStatusItemsSelectableSelected(sender: NSButton) { Settings.makeStatusItemsSelectable = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func showCreationSelected(sender: NSButton) { Settings.showCreatedInsteadOfUpdated = (sender.integerValue==1) DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func groupbyRepoSelected(sender: NSButton) { Settings.groupByRepo = (sender.integerValue==1) app.deferredUpdateTimer.push() } @IBAction func assignedPrHandlingPolicySelected(sender: NSPopUpButton) { Settings.assignedPrHandlingPolicy = sender.indexOfSelectedItem; DataManager.postProcessAllItems() app.deferredUpdateTimer.push() } @IBAction func checkForUpdatesAutomaticallySelected(sender: NSButton) { Settings.checkForUpdatesAutomatically = (sender.integerValue==1) refreshUpdatePreferences() } private func refreshUpdatePreferences() { let setting = Settings.checkForUpdatesAutomatically let interval = Settings.checkForUpdatesInterval checkForUpdatesLabel.hidden = !setting checkForUpdatesSelector.hidden = !setting checkForUpdatesSelector.integerValue = interval checkForUpdatesAutomatically.integerValue = setting ? 1 : 0 checkForUpdatesLabel.stringValue = interval<2 ? "Check every hour" : "Check every \(interval) hours" } @IBAction func checkForUpdatesIntervalChanged(sender: NSStepper) { Settings.checkForUpdatesInterval = sender.integerValue refreshUpdatePreferences() } @IBAction func launchAtStartSelected(sender: NSButton) { StartupLaunch.setLaunchOnLogin(sender.integerValue==1) } @IBAction func refreshReposSelected(sender: NSButton?) { app.prepareForRefresh() let tempContext = DataManager.tempContext() api.fetchRepositoriesToMoc(tempContext) { if ApiServer.shouldReportRefreshFailureInMoc(tempContext) { var errorServers = [String]() for apiServer in ApiServer.allApiServersInMoc(tempContext) { if apiServer.goodToGo && !apiServer.syncIsGood { errorServers.append(apiServer.label ?? "NoServerName") } } let serverNames = errorServers.joinWithSeparator(", ") let alert = NSAlert() alert.messageText = "Error" alert.informativeText = "Could not refresh repository list from \(serverNames), please ensure that the tokens you are using are valid" alert.addButtonWithTitle("OK") alert.runModal() } else { do { try tempContext.save() } catch _ { } } app.completeRefresh() } } private func selectedServer() -> ApiServer? { let selected = serverList.selectedRow if selected >= 0 { return ApiServer.allApiServersInMoc(mainObjectContext)[selected] } return nil } @IBAction func deleteSelectedServerSelected(sender: NSButton) { if let selectedServer = selectedServer(), index = indexOfObject(ApiServer.allApiServersInMoc(mainObjectContext), value: selectedServer) { mainObjectContext.deleteObject(selectedServer) serverList.reloadData() serverList.selectRowIndexes(NSIndexSet(index: min(index, serverList.numberOfRows-1)), byExtendingSelection: false) fillServerApiFormFromSelectedServer() app.deferredUpdateTimer.push() DataManager.saveDB() } } @IBAction func apiServerReportErrorSelected(sender: NSButton) { if let apiServer = selectedServer() { apiServer.reportRefreshFailures = (sender.integerValue != 0) storeApiFormToSelectedServer() } } func updateImportExportSettings() { repeatLastExportAutomatically.integerValue = Settings.autoRepeatSettingsExport ? 1 : 0 if let lastExportDate = Settings.lastExportDate, fileName = Settings.lastExportUrl?.absoluteString, unescapedName = fileName.stringByRemovingPercentEncoding { let time = itemDateFormatter.stringFromDate(lastExportDate) lastExportReport.stringValue = "Last exported \(time) to \(unescapedName)" } else { lastExportReport.stringValue = "" } } @IBAction func repeatLastExportSelected(sender: AnyObject) { Settings.autoRepeatSettingsExport = (repeatLastExportAutomatically.integerValue==1) } @IBAction func exportCurrentSettingsSelected(sender: NSButton) { let s = NSSavePanel() s.title = "Export Current Settings..." s.prompt = "Export" s.nameFieldLabel = "Settings File" s.message = "Export Current Settings..." s.extensionHidden = false s.nameFieldStringValue = "Trailer Settings" s.allowedFileTypes = ["trailerSettings"] s.beginSheetModalForWindow(self, completionHandler: { response in if response == NSFileHandlingPanelOKButton, let url = s.URL { Settings.writeToURL(url) DLog("Exported settings to %@", url.absoluteString) } }) } @IBAction func importSettingsSelected(sender: NSButton) { let o = NSOpenPanel() o.title = "Import Settings From File..." o.prompt = "Import" o.nameFieldLabel = "Settings File" o.message = "Import Settings From File..." o.extensionHidden = false o.allowedFileTypes = ["trailerSettings"] o.beginSheetModalForWindow(self, completionHandler: { response in if response == NSFileHandlingPanelOKButton, let url = o.URL { atNextEvent { app.tryLoadSettings(url, skipConfirm: Settings.dontConfirmSettingsImport) } } }) } private func colorButton(button: NSButton, withColor: NSColor) { let title = button.attributedTitle.mutableCopy() as! NSMutableAttributedString title.addAttribute(NSForegroundColorAttributeName, value: withColor, range: NSMakeRange(0, title.length)) button.attributedTitle = title } private func enableHotkeySegments() { if Settings.hotkeyEnable { colorButton(hotkeyCommandModifier, withColor: Settings.hotkeyCommandModifier ? NSColor.controlTextColor() : NSColor.disabledControlTextColor()) colorButton(hotkeyControlModifier, withColor: Settings.hotkeyControlModifier ? NSColor.controlTextColor() : NSColor.disabledControlTextColor()) colorButton(hotkeyOptionModifier, withColor: Settings.hotkeyOptionModifier ? NSColor.controlTextColor() : NSColor.disabledControlTextColor()) colorButton(hotkeyShiftModifier, withColor: Settings.hotkeyShiftModifier ? NSColor.controlTextColor() : NSColor.disabledControlTextColor()) } hotKeyContainer.hidden = !Settings.hotkeyEnable hotKeyHelp.hidden = Settings.hotkeyEnable } @IBAction func enableHotkeySelected(sender: NSButton) { Settings.hotkeyEnable = hotkeyEnable.integerValue != 0 Settings.hotkeyLetter = hotkeyLetter.titleOfSelectedItem ?? "T" Settings.hotkeyControlModifier = hotkeyControlModifier.integerValue != 0 Settings.hotkeyCommandModifier = hotkeyCommandModifier.integerValue != 0 Settings.hotkeyOptionModifier = hotkeyOptionModifier.integerValue != 0 Settings.hotkeyShiftModifier = hotkeyShiftModifier.integerValue != 0 enableHotkeySegments() app.addHotKeySupport() } private func reportNeedFrontEnd() { let alert = NSAlert() alert.messageText = "Please provide a full URL for the web front end of this server first" alert.addButtonWithTitle("OK") alert.runModal() } @IBAction func createTokenSelected(sender: NSButton) { if apiServerWebPath.stringValue.isEmpty { reportNeedFrontEnd() } else { let address = apiServerWebPath.stringValue + "/settings/tokens/new" NSWorkspace.sharedWorkspace().openURL(NSURL(string: address)!) } } @IBAction func viewExistingTokensSelected(sender: NSButton) { if apiServerWebPath.stringValue.isEmpty { reportNeedFrontEnd() } else { let address = apiServerWebPath.stringValue + "/settings/applications" NSWorkspace.sharedWorkspace().openURL(NSURL(string: address)!) } } @IBAction func viewWatchlistSelected(sender: NSButton) { if apiServerWebPath.stringValue.isEmpty { reportNeedFrontEnd() } else { let address = apiServerWebPath.stringValue + "/watching" NSWorkspace.sharedWorkspace().openURL(NSURL(string: address)!) } } @IBAction func prMergePolicySelected(sender: NSPopUpButton) { Settings.mergeHandlingPolicy = sender.indexOfSelectedItem } @IBAction func prClosePolicySelected(sender: NSPopUpButton) { Settings.closeHandlingPolicy = sender.indexOfSelectedItem } private func updateStatusTermPreferenceControls() { let mode = Settings.statusFilteringMode statusTermMenu.selectItemAtIndex(mode) if mode != 0 { statusTermsField.enabled = true statusTermsField.alphaValue = 1.0 } else { statusTermsField.enabled = false statusTermsField.alphaValue = 0.8 } statusTermsField.objectValue = Settings.statusFilteringTerms } @IBAction func statusFilterMenuChanged(sender: NSPopUpButton) { Settings.statusFilteringMode = sender.indexOfSelectedItem Settings.statusFilteringTerms = statusTermsField.objectValue as! [String] updateStatusTermPreferenceControls() app.deferredUpdateTimer.push() } @IBAction func testApiServerSelected(sender: NSButton) { sender.enabled = false let apiServer = selectedServer()! api.testApiToServer(apiServer) { error in let alert = NSAlert() if error != nil { alert.messageText = "The test failed for " + (apiServer.apiPath ?? "NoApiPath") alert.informativeText = error!.localizedDescription } else { alert.messageText = "This API server seems OK!" } alert.addButtonWithTitle("OK") alert.runModal() sender.enabled = true } } @IBAction func apiRestoreDefaultsSelected(sender: NSButton) { if let apiServer = selectedServer() { apiServer.resetToGithub() fillServerApiFormFromSelectedServer() storeApiFormToSelectedServer() } } private func fillServerApiFormFromSelectedServer() { if let apiServer = selectedServer() { apiServerName.stringValue = apiServer.label ?? "" apiServerWebPath.stringValue = apiServer.webPath ?? "" apiServerApiPath.stringValue = apiServer.apiPath ?? "" apiServerAuthToken.stringValue = apiServer.authToken ?? "" apiServerSelectedBox.title = apiServer.label ?? "New Server" apiServerTestButton.enabled = !(apiServer.authToken ?? "").isEmpty apiServerDeleteButton.enabled = (ApiServer.countApiServersInMoc(mainObjectContext) > 1) apiServerReportError.integerValue = apiServer.reportRefreshFailures.boolValue ? 1 : 0 } } private func storeApiFormToSelectedServer() { if let apiServer = selectedServer() { apiServer.label = apiServerName.stringValue apiServer.apiPath = apiServerApiPath.stringValue apiServer.webPath = apiServerWebPath.stringValue apiServer.authToken = apiServerAuthToken.stringValue apiServerTestButton.enabled = !(apiServer.authToken ?? "").isEmpty serverList.reloadData() } } @IBAction func addNewApiServerSelected(sender: NSButton) { let a = ApiServer.insertNewServerInMoc(mainObjectContext) a.label = "New API Server" serverList.reloadData() if let index = indexOfObject(ApiServer.allApiServersInMoc(mainObjectContext), value: a) { serverList.selectRowIndexes(NSIndexSet(index: index), byExtendingSelection: false) fillServerApiFormFromSelectedServer() } } @IBAction func refreshDurationChanged(sender: NSStepper?) { Settings.refreshPeriod = refreshDurationStepper.floatValue refreshDurationLabel.stringValue = "Refresh items every \(refreshDurationStepper.integerValue) seconds" } @IBAction func newRepoCheckChanged(sender: NSStepper?) { Settings.newRepoCheckPeriod = repoCheckStepper.floatValue repoCheckLabel.stringValue = "Refresh repos & teams every \(repoCheckStepper.integerValue) hours" } func windowWillClose(notification: NSNotification) { if ApiServer.someServersHaveAuthTokensInMoc(mainObjectContext) && app.preferencesDirty { app.startRefresh() } else { if app.refreshTimer == nil && Settings.refreshPeriod > 0.0 { app.startRefreshIfItIsDue() } } app.setUpdateCheckParameters() app.closedPreferencesWindow() } override func controlTextDidChange(n: NSNotification?) { if let obj: AnyObject = n?.object { if obj===apiServerName { if let apiServer = selectedServer() { apiServer.label = apiServerName.stringValue storeApiFormToSelectedServer() } } else if obj===apiServerApiPath { if let apiServer = selectedServer() { apiServer.apiPath = apiServerApiPath.stringValue storeApiFormToSelectedServer() apiServer.clearAllRelatedInfo() app.reset() } } else if obj===apiServerWebPath { if let apiServer = selectedServer() { apiServer.webPath = apiServerWebPath.stringValue storeApiFormToSelectedServer() } } else if obj===apiServerAuthToken { if let apiServer = selectedServer() { apiServer.authToken = apiServerAuthToken.stringValue storeApiFormToSelectedServer() apiServer.clearAllRelatedInfo() app.reset() } } else if obj===repoFilter { projectsTable.reloadData() } else if obj===statusTermsField { let existingTokens = Settings.statusFilteringTerms let newTokens = statusTermsField.objectValue as! [String] if existingTokens != newTokens { Settings.statusFilteringTerms = newTokens app.deferredUpdateTimer.push() } } else if obj===commentAuthorBlacklist { let existingTokens = Settings.commentAuthorBlacklist let newTokens = commentAuthorBlacklist.objectValue as! [String] if existingTokens != newTokens { Settings.commentAuthorBlacklist = newTokens } } } } ///////////// Tabs func tabView(tabView: NSTabView, willSelectTabViewItem tabViewItem: NSTabViewItem?) { if let item = tabViewItem { let newIndex = tabView.indexOfTabViewItem(item) if newIndex == 1 { if (app.lastRepoCheck.isEqualToDate(never()) || Repo.countVisibleReposInMoc(mainObjectContext) == 0) && ApiServer.someServersHaveAuthTokensInMoc(mainObjectContext) { refreshReposSelected(nil) } } Settings.lastPreferencesTabSelectedOSX = newIndex } } ///////////// Repo table func tableViewSelectionDidChange(notification: NSNotification) { if self.serverList === notification.object { fillServerApiFormFromSelectedServer() } else if self.projectsTable === notification.object { updateAllItemSettingButtons() } } private func repoForRow(row: Int) -> Repo { let parentCount = Repo.countParentRepos(repoFilter.stringValue) var r = row if r > parentCount { r-- } let filteredRepos = Repo.reposForFilter(repoFilter.stringValue) return filteredRepos[r-1] } func tableView(tv: NSTableView, shouldSelectRow row: Int) -> Bool { return !tableView(tv, isGroupRow:row) } func tableView(tv: NSTableView, willDisplayCell c: AnyObject, forTableColumn tableColumn: NSTableColumn?, row: Int) { let cell = c as! NSCell if tv === projectsTable { if tableColumn?.identifier == "repos" { if tableView(tv, isGroupRow:row) { cell.title = row==0 ? "Parent Repositories" : "Forked Repositories" cell.enabled = false } else { cell.enabled = true let r = repoForRow(row) let repoName = r.fullName ?? "NoRepoName" let title = (r.inaccessible?.boolValue ?? false) ? repoName + " (inaccessible)" : repoName let textColor = (row == tv.selectedRow) ? NSColor.selectedControlTextColor() : (r.shouldSync() ? NSColor.textColor() : NSColor.textColor().colorWithAlphaComponent(0.4)) cell.attributedStringValue = NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName: textColor]) } } else { if let menuCell = cell as? NSPopUpButtonCell { menuCell.removeAllItems() if tableView(tv, isGroupRow:row) { menuCell.selectItemAtIndex(-1) menuCell.enabled = false menuCell.arrowPosition = NSPopUpArrowPosition.NoArrow } else { let r = repoForRow(row) menuCell.enabled = true menuCell.arrowPosition = NSPopUpArrowPosition.ArrowAtBottom var count = 0 let fontSize = NSFont.systemFontSizeForControlSize(NSControlSize.SmallControlSize) for policy in RepoDisplayPolicy.policies { let m = NSMenuItem() m.attributedTitle = NSAttributedString(string: policy.name(), attributes: [ NSFontAttributeName: count==0 ? NSFont.systemFontOfSize(fontSize) : NSFont.boldSystemFontOfSize(fontSize), NSForegroundColorAttributeName: policy.color(), ]) menuCell.menu?.addItem(m) count++ } let selectedIndex = tableColumn?.identifier == "prs" ? (r.displayPolicyForPrs?.integerValue ?? 0) : (r.displayPolicyForIssues?.integerValue ?? 0) menuCell.selectItemAtIndex(selectedIndex) } } } } else { let allServers = ApiServer.allApiServersInMoc(mainObjectContext) let apiServer = allServers[row] if tableColumn?.identifier == "server" { cell.title = apiServer.label ?? "NoApiServer" let tc = c as! NSTextFieldCell if apiServer.lastSyncSucceeded?.boolValue ?? false { tc.textColor = NSColor.textColor() } else { tc.textColor = NSColor.redColor() } } else { // api usage let c = cell as! NSLevelIndicatorCell c.minValue = 0 let rl = apiServer.requestsLimit?.doubleValue ?? 0.0 c.maxValue = rl c.warningValue = rl*0.5 c.criticalValue = rl*0.8 c.doubleValue = rl - (apiServer.requestsRemaining?.doubleValue ?? 0) } } } func tableView(tableView: NSTableView, isGroupRow row: Int) -> Bool { if tableView === projectsTable { return (row == 0 || row == Repo.countParentRepos(repoFilter.stringValue) + 1) } else { return false } } func numberOfRowsInTableView(tableView: NSTableView) -> Int { if tableView === projectsTable { return Repo.reposForFilter(repoFilter.stringValue).count + 2 } else { return ApiServer.countApiServersInMoc(mainObjectContext) } } func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? { return nil } func tableView(tv: NSTableView, setObjectValue object: AnyObject?, forTableColumn tableColumn: NSTableColumn?, row: Int) { if tv === projectsTable { if !tableView(tv, isGroupRow: row) { let r = repoForRow(row) if let index = object?.integerValue { if tableColumn?.identifier == "prs" { r.displayPolicyForPrs = index } else if tableColumn?.identifier == "issues" { r.displayPolicyForIssues = index } if index != RepoDisplayPolicy.Hide.rawValue { r.resetSyncState() } updateDisplayIssuesSetting() } } } } }
834388f2d0cd1db253c854cd81478030
36.008507
196
0.768816
false
false
false
false
mathiasquintero/RandomStuff
refs/heads/master
Swift/Matrix.swift
mit
1
import Foundation // I wanted to write Matix multiplication without ever using a loop // or an index typealias Vector = [Double] typealias Matrix = [Vector] infix operator ++ func *(lhs: Vector, rhs: Vector) -> Double { return zip(lhs, rhs).reduce(0) { $0 + $1.0 * $1.1 } } func ++(lhs: Matrix, rhs: Vector) -> Matrix { return zip(lhs, rhs).map { $0 + [$1] } } extension Array where Element == Vector { private static func of(length: Int) -> Matrix { return (0..<length).map { _ in [] } } func transposed() -> Matrix { guard let count = first?.count else { return [] } return reduce(.of(length: count)) { $0 ++ $1 } } } func *(lhs: Matrix, rhs: Matrix) -> Matrix { let rhs = rhs.transposed() return lhs.reduce([]) { matrix, vector in return matrix + [rhs.map { $0 * vector }] } } let a = [ [2.0, 3.0], [4.0, 5.0] ] let b = [ [2.0, 3.0], [4.0, 5.0] ] a * b
b2fbb71a4fef55a629d0b1e148de1efa
18.693878
67
0.54715
false
false
false
false
exercism/xswift
refs/heads/master
exercises/grade-school/Sources/GradeSchool/GradeSchoolExample.swift
mit
2
struct GradeSchool { var roster = [Int: [String]]() mutating func addStudent(_ name: String, grade: Int) { if let students = roster[grade] { var students = students students.append(name) roster[grade] = students } else { roster[grade] = [name] } } func studentsInGrade(_ grade: Int) -> [String] { return roster[grade] ?? [String]() } var sortedRoster: [Int: [String]] { var sortedRoster = [Int: [String]](minimumCapacity: roster.count) for (grade, students) in roster { sortedRoster[grade] = students.sorted() } return sortedRoster } }
8036ea79637290edd51ddb82c5e747e8
26.64
73
0.545586
false
false
false
false
C4Framework/C4iOS
refs/heads/master
C4/Core/Rect.swift
mit
2
// Copyright © 2014 C4 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: The above copyright // notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. import Foundation import CoreGraphics /// A structure that contains the location and dimensions of a rectangle. public struct Rect: Equatable, CustomStringConvertible { /// The origin (top-left) of the rect. public var origin: Point /// The size (width / height) of the rect. public var size: Size /// The width of the rect. public var width: Double { get { return size.width } set { size.width = newValue } } /// The height of the rect. public var height: Double { get { return size.height } set { size.height = newValue } } /// Initializes a new Rect with the origin {0,0} and the size {0,0} /// ```` /// let r = Rect() /// ```` public init() { self.init(0, 0, 0, 0) } /// Initializes a new Rect with the origin {x,y} and the size {w,h} /// ```` /// let r = Rect(0.0,0.0,10.0,10.0) /// ```` public init(_ x: Double, _ y: Double, _ w: Double, _ h: Double) { origin = Point(x, y) size = Size(w, h) } /// Initializes a new Rect with the origin {x,y} and the size {w,h}, converting values from Int to Double /// ```` /// let r = Rect(0,0,10,10) /// ```` public init(_ x: Int, _ y: Int, _ w: Int, _ h: Int) { origin = Point(x, y) size = Size(w, h) } /// Initializes a new Rect with the origin {o.x,o.y} and the size {s.w,s.h} /// ```` /// let p = Point() /// let s = Size() /// let r = Rect(p,s) /// ```` public init(_ o: Point, _ s: Size) { origin = o size = s } /// Initializes a Rect from a CGRect public init(_ rect: CGRect) { origin = Point(rect.origin) size = Size(rect.size) } /// Initializes a rectangle that contains all of the specified coordinates in an array. /// ```` /// let pts = [Point(), Point(0,5), Point(10,10), Point(9,8)] /// let r = Rect(pts) //-> {{0.0, 0.0}, {10.0, 10.0}} /// ```` /// - parameter points: An array of Point coordinates public init(_ points: [Point]) { let count = points.count assert(count >= 2, "To create a Polygon you need to specify an array of at least 2 points") var cgPoints = [CGPoint]() for i in 0..<count { cgPoints.append(CGPoint(points[i])) } let r = CGRectMakeFromPoints(cgPoints) let f = Rect(r) self.init(f.origin, f.size) } /// Initializes a rectangle that contains the specified coordinates in a tuple. /// ```` /// let pts = (Point(), Point(0,5)) /// let r = Rect(pts) /// ```` /// - parameter points: An tuple of Point coordinates public init(_ points: (Point, Point)) { let r = CGRectMakeFromPoints([CGPoint(points.0), CGPoint(points.1)]) let f = Rect(r) self.init(f.origin, f.size) } // MARK: - Comparing /// Returns whether two rectangles intersect. /// ```` /// let r1 = Rect(0,0,10,10) /// let r2 = Rect(5,5,10,10) /// let r3 = Rect(10,10,10,10) /// r1.intersects(r2) //-> true /// r1.intersects(r3) //-> false /// ```` /// - parameter rect: The rectangle to examine. /// - returns: true if the two specified rectangles intersect; otherwise, false. public func intersects(_ rect: Rect) -> Bool { return CGRect(self).intersects(CGRect(rect)) } // MARK: - Center & Max /// The center point of the receiver. /// ```` /// let r = Rect(0,0,10,10) /// r.center //-> {5,5} /// ```` public var center: Point { get { return Point(origin.x + size.width/2, origin.y + size.height/2) } set { origin.x = newValue.x - size.width/2 origin.y = newValue.y - size.height/2 } } /// The bottom-right point of the receiver. /// ```` /// let r = Rect(5,5,10,10) /// r.max //-> {15,15} /// ```` public var max: Point { return Point(origin.x + size.width, origin.y + size.height) } /// Checks to see if the receiver has zero size and position /// ```` /// let r = Point() /// r.isZero() //-> true /// ```` /// - returns: true if origin = {0,0} and size = {0,0} public func isZero() -> Bool { return origin.isZero() && size.isZero() } // MARK: - Membership /// Returns whether a rectangle contains a specified point. /// ```` /// let r1 = Rect(0,0,10,10) /// let r2 = Rect(5,5,10,10) /// let p = Rect(2,2,2,2) /// r1.contains(p) //-> true /// r2.contains(p) //-> false /// ```` /// - parameter point: The point to examine. /// - returns: true if the rectangle is not null or empty and the point is located within the rectangle; otherwise, false. public func contains(_ point: Point) -> Bool { return CGRect(self).contains(CGPoint(point)) } /// Returns whether the first rectangle contains the second rectangle. /// ```` /// let r1 = Rect(0,0,10,10) /// let r2 = Rect(5,5,10,10) /// let r3 = Rect(2,2,2,2) /// r1.contains(r2) //-> false /// r1.contains(r3) //-> true /// ```` /// - parameter rect: The rectangle to examine for containment. /// - returns: `true` if the rectangle is contained in this rectangle; otherwise, `false`. public func contains(_ rect: Rect) -> Bool { return CGRect(self).contains(CGRect(rect)) } /// A string representation of the rect. /// - returns: A string formatted to look like {{x,y},{w,h}} public var description: String { return "{\(origin),\(size)}" } } // MARK: - Comparing /// Checks to see if two Rects share identical origin and size /// /// ```` /// let r1 = Rect(0,0,10,10) /// let r2 = Rect(0,0,10,10.5) /// println(r1 == r2) //-> false /// ```` /// - parameter lhs: The first rectangle to compare /// - parameter rhs: The second rectangle to compare /// - returns: A bool, `true` if the rects are identical, otherwise `false`. public func == (lhs: Rect, rhs: Rect) -> Bool { return lhs.origin == rhs.origin && lhs.size == rhs.size } // MARK: - Manipulating /// Returns the intersection of two rectangles. /// /// ```` /// let r1 = Rect(0,0,10,10) /// let r2 = Rect(5,5,10,10) /// intersection(r1,r2) //-> {5,5,5,5} /// ```` /// /// - parameter rect1: The first source rectangle. /// - parameter rect2: The second source rectangle. /// /// - returns: A rectangle that represents the intersection of the two specified rectangles. public func intersection(_ rect1: Rect, rect2: Rect) -> Rect { return Rect(CGRect(rect1).intersection(CGRect(rect2))) } /// Returns the smallest rectangle that contains the two source rectangles. /// /// ```` /// let r1 = Rect(0,0,10,10) /// let r2 = Rect(5,5,10,10) /// intersection(r1,r2) //-> {0,0,15,15} /// ```` /// /// - parameter rect1: The first source rectangle. /// - parameter rect2: The second source rectangle. /// - returns: The smallest rectangle that completely contains both of the source rectangles. public func union(_ rect1: Rect, rect2: Rect) -> Rect { return Rect(CGRect(rect1).union(CGRect(rect2))) } /// Returns the smallest rectangle that results from converting the source rectangle values to integers. /// /// ```` /// let r = Rect(0.1, 0.9, 9.1, 9.9) /// integral(r) //-> {0, 0, 10, 10} /// ```` /// /// - parameter r: The source rectangle. /// - returns: A rectangle with the smallest integer values for its origin and size that contains the source rectangle. public func integral(_ r: Rect) -> Rect { return Rect(CGRect(r).integral) } /// Returns a rectangle with a positive width and height. /// /// ```` /// let r = Rect(0, 0, -10, -10) /// standardize(r) //-> {-10, -10, 10, 10} /// ```` /// /// - parameter r: The source rectangle. /// - returns: A rectangle that represents the source rectangle, but with positive width and height values. public func standardize(_ r: Rect) -> Rect { return Rect(CGRect(r).standardized) } /// Returns a rectangle that is smaller or larger than the source rectangle, with the same center point. /// /// ```` /// let r = Rect(0,0,10,10) /// inset(r, 1, 1) //-> {1,1,8,8} /// ```` /// /// - parameter r: The source Rect structure. /// - parameter dx: The x-coordinate value to use for adjusting the source rectangle. /// - parameter dy: The y-coordinate value to use for adjusting the source rectangle. /// - returns: A rectangle. public func inset(_ r: Rect, dx: Double, dy: Double) -> Rect { return Rect(CGRect(r).insetBy(dx: CGFloat(dx), dy: CGFloat(dy))) } // MARK: - Casting to CGRect public extension CGRect { /// Initializes a CGRect from a Rect public init(_ rect: Rect) { self.init(origin: CGPoint(rect.origin), size: CGSize(rect.size)) } }
034c3840308000be01ab35cdfbe03503
31.433225
126
0.592849
false
false
false
false
SnowdogApps/Project-Needs-Partner
refs/heads/master
CooperationFinder/Async.swift
apache-2.0
1
// // Async.swift // // Created by Tobias DM on 15/07/14. // // OS X 10.10+ and iOS 8.0+ // Only use with ARC // // The MIT License (MIT) // Copyright (c) 2014 Tobias Due Munk // // 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 // MARK: - HACK: For Swift 1.1 extension qos_class_t { public var id:Int { return Int(value) } } // MARK: - DSL for GCD queues private class GCD { /* dispatch_get_queue() */ class func mainQueue() -> dispatch_queue_t { return dispatch_get_main_queue() // Don't ever use dispatch_get_global_queue(qos_class_main().id, 0) re https://gist.github.com/duemunk/34babc7ca8150ff81844 } class func userInteractiveQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE.id, 0) } class func userInitiatedQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_USER_INITIATED.id, 0) } class func utilityQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_UTILITY.id, 0) } class func backgroundQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_BACKGROUND.id, 0) } } // MARK: - Async – Struct public struct Async { private let block: dispatch_block_t private init(_ block: dispatch_block_t) { self.block = block } } // MARK: - Async – Static methods extension Async { /* dispatch_async() */ private static func async(block: dispatch_block_t, inQueue queue: dispatch_queue_t) -> Async { // Create a new block (Qos Class) from block to allow adding a notification to it later (see matching regular Async methods) // Create block with the "inherit" type let _block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, block) // Add block to queue dispatch_async(queue, _block) // Wrap block in a struct since dispatch_block_t can't be extended return Async(_block) } public static func main(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.mainQueue()) } public static func userInteractive(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.userInteractiveQueue()) } public static func userInitiated(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.userInitiatedQueue()) } public static func utility(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.utilityQueue()) } public static func background(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.backgroundQueue()) } public static func customQueue(queue: dispatch_queue_t, block: dispatch_block_t) -> Async { return Async.async(block, inQueue: queue) } /* dispatch_after() */ private static func after(seconds: Double, block: dispatch_block_t, inQueue queue: dispatch_queue_t) -> Async { let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) return at(time, block: block, inQueue: queue) } private static func at(time: dispatch_time_t, block: dispatch_block_t, inQueue queue: dispatch_queue_t) -> Async { // See Async.async() for comments let _block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, block) dispatch_after(time, queue, _block) return Async(_block) } public static func main(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.mainQueue()) } public static func userInteractive(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.userInteractiveQueue()) } public static func userInitiated(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.userInitiatedQueue()) } public static func utility(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.utilityQueue()) } public static func background(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.backgroundQueue()) } public static func customQueue(#after: Double, queue: dispatch_queue_t, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: queue) } } // MARK: - Async – Regualar methods matching static ones extension Async { /* dispatch_async() */ private func chain(block chainingBlock: dispatch_block_t, runInQueue queue: dispatch_queue_t) -> Async { // See Async.async() for comments let _chainingBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingBlock) dispatch_block_notify(self.block, queue, _chainingBlock) return Async(_chainingBlock) } public func main(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.mainQueue()) } public func userInteractive(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.userInteractiveQueue()) } public func userInitiated(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.userInitiatedQueue()) } public func utility(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.utilityQueue()) } public func background(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.backgroundQueue()) } public func customQueue(queue: dispatch_queue_t, chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: queue) } /* dispatch_after() */ private func after(seconds: Double, block chainingBlock: dispatch_block_t, runInQueue queue: dispatch_queue_t) -> Async { // Create a new block (Qos Class) from block to allow adding a notification to it later (see Async) // Create block with the "inherit" type let _chainingBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingBlock) // Wrap block to be called when previous block is finished let chainingWrapperBlock: dispatch_block_t = { // Calculate time from now let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) dispatch_after(time, queue, _chainingBlock) } // Create a new block (Qos Class) from block to allow adding a notification to it later (see Async) // Create block with the "inherit" type let _chainingWrapperBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingWrapperBlock) // Add block to queue *after* previous block is finished dispatch_block_notify(self.block, queue, _chainingWrapperBlock) // Wrap block in a struct since dispatch_block_t can't be extended return Async(_chainingBlock) } public func main(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.mainQueue()) } public func userInteractive(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.userInteractiveQueue()) } public func userInitiated(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.userInitiatedQueue()) } public func utility(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.utilityQueue()) } public func background(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.backgroundQueue()) } public func customQueue(#after: Double, queue: dispatch_queue_t, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: queue) } /* cancel */ public func cancel() { dispatch_block_cancel(block) } /* wait */ /// If optional parameter forSeconds is not provided, use DISPATCH_TIME_FOREVER public func wait(seconds: Double = 0.0) { if seconds != 0.0 { let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) dispatch_block_wait(block, time) } else { dispatch_block_wait(block, DISPATCH_TIME_FOREVER) } } } // MARK: - Apply public struct Apply { // DSL for GCD dispatch_apply() // // Apply runs a block multiple times, before returning. // If you want run the block asynchounusly from the current thread, // wrap it in an Async block, // e.g. Async.main { Apply.background(3) { ... } } public static func userInteractive(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.userInteractiveQueue(), block) } public static func userInitiated(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.userInitiatedQueue(), block) } public static func utility(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.utilityQueue(), block) } public static func background(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.backgroundQueue(), block) } public static func customQueue(iterations: Int, queue: dispatch_queue_t, block: Int -> ()) { dispatch_apply(iterations, queue, block) } } // MARK: - qos_class_t extension qos_class_t { // Convenience description of qos_class_t // Calculated property var description: String { get { switch self.id { case qos_class_main().id: return "Main" case QOS_CLASS_USER_INTERACTIVE.id: return "User Interactive" case QOS_CLASS_USER_INITIATED.id: return "User Initiated" case QOS_CLASS_DEFAULT.id: return "Default" case QOS_CLASS_UTILITY.id: return "Utility" case QOS_CLASS_BACKGROUND.id: return "Background" case QOS_CLASS_UNSPECIFIED.id: return "Unspecified" default: return "Unknown" } } } }
5e3140e18551cb27af4ecfe20e86e9ed
35.584459
126
0.715486
false
false
false
false
JGiola/swift-corelibs-foundation
refs/heads/master
Foundation/FileHandle.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016, 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if os(macOS) || os(iOS) import Darwin #elseif os(Linux) || CYGWIN import Glibc #endif open class FileHandle : NSObject, NSSecureCoding { private var _fd: Int32 private var _closeOnDealloc: Bool open var fileDescriptor: Int32 { return _fd } open var readabilityHandler: ((FileHandle) -> Void)? = { (FileHandle) -> Void in NSUnimplemented() } open var writeabilityHandler: ((FileHandle) -> Void)? = { (FileHandle) -> Void in NSUnimplemented() } open var availableData: Data { do { let readResult = try _readDataOfLength(Int.max, untilEOF: false) return readResult.toData() } catch { fatalError("\(error)") } } open func readDataToEndOfFile() -> Data { return readData(ofLength: Int.max) } open func readData(ofLength length: Int) -> Data { do { let readResult = try _readDataOfLength(length, untilEOF: true) return readResult.toData() } catch { fatalError("\(error)") } } internal func _readDataOfLength(_ length: Int, untilEOF: Bool, options: NSData.ReadingOptions = []) throws -> NSData.NSDataReadResult { precondition(_fd >= 0, "Bad file descriptor") if length == 0 && !untilEOF { // Nothing requested, return empty response return NSData.NSDataReadResult(bytes: nil, length: 0, deallocator: nil) } var statbuf = stat() if fstat(_fd, &statbuf) < 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil) } let readBlockSize: Int if statbuf.st_mode & S_IFMT == S_IFREG { // TODO: Should files over a certain size always be mmap()'d? if options.contains(.alwaysMapped) { // Filesizes are often 64bit even on 32bit systems let mapSize = min(length, Int(clamping: statbuf.st_size)) let data = mmap(nil, mapSize, PROT_READ, MAP_PRIVATE, _fd, 0) // Swift does not currently expose MAP_FAILURE if data != UnsafeMutableRawPointer(bitPattern: -1) { return NSData.NSDataReadResult(bytes: data!, length: mapSize) { buffer, length in munmap(buffer, length) } } } if statbuf.st_blksize > 0 { readBlockSize = Int(clamping: statbuf.st_blksize) } else { readBlockSize = 1024 * 8 } } else { /* We get here on sockets, character special files, FIFOs ... */ readBlockSize = 1024 * 8 } var currentAllocationSize = readBlockSize var dynamicBuffer = malloc(currentAllocationSize)! var total = 0 while total < length { let remaining = length - total let amountToRead = min(readBlockSize, remaining) // Make sure there is always at least amountToRead bytes available in the buffer. if (currentAllocationSize - total) < amountToRead { currentAllocationSize *= 2 dynamicBuffer = _CFReallocf(dynamicBuffer, currentAllocationSize) } let amtRead = read(_fd, dynamicBuffer.advanced(by: total), amountToRead) if amtRead < 0 { free(dynamicBuffer) throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil) } total += amtRead if amtRead == 0 || !untilEOF { // If there is nothing more to read or we shouldnt keep reading then exit break } } if total == 0 { free(dynamicBuffer) return NSData.NSDataReadResult(bytes: nil, length: 0, deallocator: nil) } dynamicBuffer = _CFReallocf(dynamicBuffer, total) let bytePtr = dynamicBuffer.bindMemory(to: UInt8.self, capacity: total) return NSData.NSDataReadResult(bytes: bytePtr, length: total) { buffer, length in free(buffer) } } open func write(_ data: Data) { guard _fd >= 0 else { return } data.enumerateBytes() { (bytes, range, stop) in do { try NSData.write(toFileDescriptor: self._fd, path: nil, buf: UnsafeRawPointer(bytes.baseAddress!), length: bytes.count) } catch { fatalError("Write failure") } } } // TODO: Error handling. open var offsetInFile: UInt64 { precondition(_fd >= 0, "Bad file descriptor") return UInt64(lseek(_fd, 0, SEEK_CUR)) } @discardableResult open func seekToEndOfFile() -> UInt64 { precondition(_fd >= 0, "Bad file descriptor") return UInt64(lseek(_fd, 0, SEEK_END)) } open func seek(toFileOffset offset: UInt64) { precondition(_fd >= 0, "Bad file descriptor") lseek(_fd, off_t(offset), SEEK_SET) } open func truncateFile(atOffset offset: UInt64) { precondition(_fd >= 0, "Bad file descriptor") if lseek(_fd, off_t(offset), SEEK_SET) < 0 { fatalError("lseek() failed.") } if ftruncate(_fd, off_t(offset)) < 0 { fatalError("ftruncate() failed.") } } open func synchronizeFile() { precondition(_fd >= 0, "Bad file descriptor") fsync(_fd) } open func closeFile() { if _fd >= 0 { close(_fd) _fd = -1 } } public init(fileDescriptor fd: Int32, closeOnDealloc closeopt: Bool) { _fd = fd _closeOnDealloc = closeopt } public convenience init(fileDescriptor fd: Int32) { self.init(fileDescriptor: fd, closeOnDealloc: false) } internal init?(path: String, flags: Int32, createMode: Int) { _fd = _CFOpenFileWithMode(path, flags, mode_t(createMode)) _closeOnDealloc = true super.init() if _fd < 0 { return nil } } deinit { if _fd >= 0 && _closeOnDealloc { close(_fd) _fd = -1 } } public required init?(coder: NSCoder) { NSUnimplemented() } open func encode(with aCoder: NSCoder) { NSUnimplemented() } public static var supportsSecureCoding: Bool { return true } } extension FileHandle { internal static var _stdinFileHandle: FileHandle = { return FileHandle(fileDescriptor: STDIN_FILENO, closeOnDealloc: false) }() open class var standardInput: FileHandle { return _stdinFileHandle } internal static var _stdoutFileHandle: FileHandle = { return FileHandle(fileDescriptor: STDOUT_FILENO, closeOnDealloc: false) }() open class var standardOutput: FileHandle { return _stdoutFileHandle } internal static var _stderrFileHandle: FileHandle = { return FileHandle(fileDescriptor: STDERR_FILENO, closeOnDealloc: false) }() open class var standardError: FileHandle { return _stderrFileHandle } internal static var _nulldeviceFileHandle: FileHandle = { class NullDevice: FileHandle { override var availableData: Data { return Data() } override func readDataToEndOfFile() -> Data { return Data() } override func readData(ofLength length: Int) -> Data { return Data() } override func write(_ data: Data) {} override var offsetInFile: UInt64 { return 0 } override func seekToEndOfFile() -> UInt64 { return 0 } override func seek(toFileOffset offset: UInt64) {} override func truncateFile(atOffset offset: UInt64) {} override func synchronizeFile() {} override func closeFile() {} deinit {} } return NullDevice(fileDescriptor: -1, closeOnDealloc: false) }() open class var nullDevice: FileHandle { return _nulldeviceFileHandle } public convenience init?(forReadingAtPath path: String) { self.init(path: path, flags: O_RDONLY, createMode: 0) } public convenience init?(forWritingAtPath path: String) { self.init(path: path, flags: O_WRONLY, createMode: 0) } public convenience init?(forUpdatingAtPath path: String) { self.init(path: path, flags: O_RDWR, createMode: 0) } internal static func _openFileDescriptorForURL(_ url : URL, flags: Int32, reading: Bool) throws -> Int32 { let path = url.path let fd = _CFOpenFile(path, flags) if fd < 0 { throw _NSErrorWithErrno(errno, reading: reading, url: url) } return fd } public convenience init(forReadingFrom url: URL) throws { let fd = try FileHandle._openFileDescriptorForURL(url, flags: O_RDONLY, reading: true) self.init(fileDescriptor: fd, closeOnDealloc: true) } public convenience init(forWritingTo url: URL) throws { let fd = try FileHandle._openFileDescriptorForURL(url, flags: O_WRONLY, reading: false) self.init(fileDescriptor: fd, closeOnDealloc: true) } public convenience init(forUpdating url: URL) throws { let fd = try FileHandle._openFileDescriptorForURL(url, flags: O_RDWR, reading: false) self.init(fileDescriptor: fd, closeOnDealloc: true) } } extension NSExceptionName { public static let fileHandleOperationException = NSExceptionName(rawValue: "NSFileHandleOperationException") } extension Notification.Name { public static let NSFileHandleReadToEndOfFileCompletion = Notification.Name(rawValue: "NSFileHandleReadToEndOfFileCompletionNotification") public static let NSFileHandleConnectionAccepted = Notification.Name(rawValue: "NSFileHandleConnectionAcceptedNotification") public static let NSFileHandleDataAvailable = Notification.Name(rawValue: "NSFileHandleDataAvailableNotification") } extension FileHandle { public static let readCompletionNotification = Notification.Name(rawValue: "NSFileHandleReadCompletionNotification") } public let NSFileHandleNotificationDataItem: String = "NSFileHandleNotificationDataItem" public let NSFileHandleNotificationFileHandleItem: String = "NSFileHandleNotificationFileHandleItem" extension FileHandle { open func readInBackgroundAndNotify(forModes modes: [RunLoopMode]?) { NSUnimplemented() } open func readInBackgroundAndNotify() { NSUnimplemented() } open func readToEndOfFileInBackgroundAndNotify(forModes modes: [RunLoopMode]?) { NSUnimplemented() } open func readToEndOfFileInBackgroundAndNotify() { NSUnimplemented() } open func acceptConnectionInBackgroundAndNotify(forModes modes: [RunLoopMode]?) { NSUnimplemented() } open func acceptConnectionInBackgroundAndNotify() { NSUnimplemented() } open func waitForDataInBackgroundAndNotify(forModes modes: [RunLoopMode]?) { NSUnimplemented() } open func waitForDataInBackgroundAndNotify() { NSUnimplemented() } } open class Pipe: NSObject { public let fileHandleForReading: FileHandle public let fileHandleForWriting: FileHandle public override init() { /// the `pipe` system call creates two `fd` in a malloc'ed area var fds = UnsafeMutablePointer<Int32>.allocate(capacity: 2) defer { fds.deallocate() } /// If the operating system prevents us from creating file handles, stop let ret = pipe(fds) switch (ret, errno) { case (0, _): self.fileHandleForReading = FileHandle(fileDescriptor: fds.pointee, closeOnDealloc: true) self.fileHandleForWriting = FileHandle(fileDescriptor: fds.successor().pointee, closeOnDealloc: true) case (-1, EMFILE), (-1, ENFILE): // Unfortunately this initializer does not throw and isnt failable so this is only // way of handling this situation. self.fileHandleForReading = FileHandle(fileDescriptor: -1, closeOnDealloc: false) self.fileHandleForWriting = FileHandle(fileDescriptor: -1, closeOnDealloc: false) default: fatalError("Error calling pipe(): \(errno)") } super.init() } }
7dd96c82d656ac66452c81da153be233
31.880711
142
0.61235
false
false
false
false